Inspector.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. using System;
  4. using System.Collections.Generic;
  5. using bs;
  6. namespace bs.Editor
  7. {
  8. /** @addtogroup Inspector
  9. * @{
  10. */
  11. /// <summary>
  12. /// Displays GUI elements for all the inspectable fields in an object.
  13. /// </summary>
  14. public abstract class Inspector
  15. {
  16. public const short START_BACKGROUND_DEPTH = 50;
  17. /// <summary>
  18. /// Returns the main GUI layout for the inspector.
  19. /// </summary>
  20. protected GUILayoutY Layout
  21. {
  22. get { return layout; }
  23. }
  24. /// <summary>
  25. /// Returns the main GUI panel for the inspector. <see cref="Layout"/> is a child of this panel.
  26. /// </summary>
  27. protected GUIPanel GUI
  28. {
  29. get { return mainPanel; }
  30. }
  31. /// <summary>
  32. /// Returns the secondary GUI panel. Located at the bottom of the inspector window and unlike <see cref="GUI"/> has
  33. /// no padding or styling applied. Only available when inspecting resources.
  34. /// </summary>
  35. protected GUIPanel PreviewGUI
  36. {
  37. get { return previewPanel; }
  38. }
  39. /// <summary>
  40. /// Returns the object the inspector is currently displaying. If the current object is a resource use
  41. /// <see cref="InspectedResourcePath"/> instead;
  42. /// </summary>
  43. protected object InspectedObject
  44. {
  45. get { return inspectedObject; }
  46. }
  47. /// <summary>
  48. /// Returns the path to the resource the inspector is currently displaying.
  49. /// </summary>
  50. protected string InspectedResourcePath
  51. {
  52. get { return inspectedResourcePath; }
  53. }
  54. /// <summary>
  55. /// A set of properties that the inspector can read/write. They will be persisted even after the inspector is closed
  56. /// and restored when it is re-opened.
  57. /// </summary>
  58. protected internal SerializableProperties Persistent
  59. {
  60. get { return persistent; }
  61. }
  62. protected InspectorFieldDrawer drawer;
  63. private GUIPanel rootGUI;
  64. private GUIPanel mainPanel;
  65. private GUIPanel previewPanel;
  66. private GUILayoutY layout;
  67. private object inspectedObject;
  68. private string inspectedResourcePath;
  69. private SerializableProperties persistent;
  70. /// <summary>
  71. /// Common code called by both Initialize() overloads.
  72. /// </summary>
  73. /// <param name="mainGui">Primary GUI panel to add the GUI elements to.</param>
  74. /// <param name="previewGui">Secondary GUI panel located at the bottom of the inspector window, aimed primarily for
  75. /// resource previews, but can be used for any purpose.</param>
  76. /// <param name="persistent">A set of properties that the inspector can read/write. They will be persisted even
  77. /// after the inspector is closed and restored when it is re-opened.</param>
  78. private void InitializeBase(GUIPanel mainGui, GUIPanel previewGui, SerializableProperties persistent)
  79. {
  80. rootGUI = mainGui;
  81. this.persistent = persistent;
  82. GUILayout contentLayoutX = mainGui.AddLayoutX();
  83. contentLayoutX.AddSpace(5);
  84. GUILayout contentLayoutY = contentLayoutX.AddLayoutY();
  85. contentLayoutY.AddSpace(5);
  86. GUIPanel contentPanel = contentLayoutY.AddPanel();
  87. contentLayoutY.AddSpace(5);
  88. contentLayoutX.AddSpace(5);
  89. GUIPanel backgroundPanel = mainGui.AddPanel(START_BACKGROUND_DEPTH);
  90. GUITexture inspectorContentBg = new GUITexture(null, EditorStylesInternal.InspectorContentBg);
  91. backgroundPanel.AddElement(inspectorContentBg);
  92. mainPanel = contentPanel;
  93. previewPanel = previewGui;
  94. layout = GUI.AddLayoutY();
  95. }
  96. /// <summary>
  97. /// Initializes the inspector using an object instance. Must be called after construction.
  98. /// </summary>
  99. /// <param name="gui">GUI panel to add the GUI elements to.</param>
  100. /// <param name="instance">Instance of the object whose fields to display GUI for.</param>
  101. /// <param name="persistent">A set of properties that the inspector can read/write. They will be persisted even
  102. /// after the inspector is closed and restored when it is re-opened.</param>
  103. internal virtual void Initialize(GUIPanel gui, object instance, SerializableProperties persistent)
  104. {
  105. InitializeBase(gui, null, persistent);
  106. drawer = new InspectorFieldDrawer(new InspectableContext(Persistent, instance as Component), Layout);
  107. inspectedObject = instance;
  108. Initialize();
  109. Refresh();
  110. }
  111. /// <summary>
  112. /// Initializes the inspector using a resource path. Must be called after construction.
  113. /// </summary>
  114. /// <param name="mainGui">Primary GUI panel to add the GUI elements to.</param>
  115. /// <param name="previewGui">Secondary GUI panel located at the bottom of the inspector window, aimed primarily for
  116. /// resource previews, but can be used for any purpose.</param>
  117. /// <param name="path">Path to the resource for which to display GUI for.</param>
  118. /// <param name="persistent">A set of properties that the inspector can read/write. They will be persisted even
  119. /// after the inspector is closed and restored when it is re-opened.</param>
  120. internal virtual void Initialize(GUIPanel mainGui, GUIPanel previewGui, string path,
  121. SerializableProperties persistent)
  122. {
  123. InitializeBase(mainGui, previewGui, persistent);
  124. drawer = new InspectorFieldDrawer(new InspectableContext(Persistent), Layout);
  125. inspectedResourcePath = path;
  126. Initialize();
  127. Refresh();
  128. }
  129. /// <summary>
  130. /// Changes keyboard focus to the provided field.
  131. /// </summary>
  132. /// <param name="path">Path to the field on the object being inspected.</param>
  133. internal virtual void FocusOnField(string path)
  134. {
  135. drawer.FocusOnField(path);
  136. }
  137. /// <summary>
  138. /// Loads the currently inspected resource into the <see cref="InspectedObject"/> field. By default resources
  139. /// are not loaded and you can only retrieve their path through <see cref="InspectedResourcePath"/>.
  140. /// </summary>
  141. protected void LoadResource()
  142. {
  143. if(!string.IsNullOrEmpty(inspectedResourcePath))
  144. inspectedObject = ProjectLibrary.Load<Resource>(inspectedResourcePath);
  145. }
  146. /// <summary>
  147. /// Hides or shows the inspector GUI elements.
  148. /// </summary>
  149. /// <param name="visible">True to make the GUI elements visible.</param>
  150. internal virtual void SetVisible(bool visible)
  151. {
  152. rootGUI.Active = visible;
  153. }
  154. /// <summary>
  155. /// Destroys all inspector GUI elements.
  156. /// </summary>
  157. internal void Destroy()
  158. {
  159. Layout.Destroy();
  160. GUI.Destroy();
  161. }
  162. /// <summary>
  163. /// Called when the inspector is first created.
  164. /// </summary>
  165. protected internal abstract void Initialize();
  166. /// <summary>
  167. /// Checks if contents of the inspector have been modified, and updates them if needed.
  168. /// </summary>
  169. /// <returns>State representing was anything modified between two last calls to <see cref="Refresh"/>.</returns>
  170. protected internal virtual InspectableState Refresh()
  171. {
  172. return drawer.Refresh();
  173. }
  174. }
  175. /// <summary>
  176. /// Helper class that draws the inspector field elements for an object, allowing you to draw default set of fields,
  177. /// override certain fields with your own, or add new fields manually.
  178. /// </summary>
  179. public sealed class InspectorFieldDrawer
  180. {
  181. /// <summary>
  182. /// Contains information about a conditional that determines whether a field will be active or not.
  183. /// </summary>
  184. private struct ConditionalInfo
  185. {
  186. public Func<bool> callback;
  187. public string field;
  188. public ConditionalInfo(string field, Func<bool> callback)
  189. {
  190. this.field = field;
  191. this.callback = callback;
  192. }
  193. }
  194. /// <summary>
  195. /// Allows the user to override the default inspector GUI for a specific field in an object. If this method
  196. /// returns null the default field will be used instead.
  197. /// </summary>
  198. /// <param name="field">Field to generate inspector GUI for.</param>
  199. /// <param name="context">Context shared by all inspectable fields created by the same parent.</param>
  200. /// <param name="path">Full path to the provided field (includes name of this field and all parent fields).</param>
  201. /// <param name="layout">Parent layout that all the field elements will be added to.</param>
  202. /// <param name="layoutIndex">Index into the parent layout at which to insert the GUI elements for the field .</param>
  203. /// <param name="depth">
  204. /// Determines how deep within the inspector nesting hierarchy is this field. Some fields may contain other fields,
  205. /// in which case you should increase this value by one.
  206. /// </param>
  207. /// <returns>
  208. /// Inspectable field implementation that can be used for displaying the GUI for the provided field. Or null if
  209. /// default field GUI should be used instead.
  210. /// </returns>
  211. public delegate InspectableField FieldOverrideCallback(SerializableField field, InspectableContext context, string path,
  212. InspectableFieldLayout layout, int layoutIndex, int depth);
  213. /// <summary>
  214. /// List of fields created and updated by the drawer.
  215. /// </summary>
  216. public List<InspectableField> Fields { get; } = new List<InspectableField>();
  217. private InspectableContext context;
  218. private GUILayoutY layout;
  219. private string path;
  220. private int depth;
  221. private int rootIndex;
  222. private List<ConditionalInfo> conditionals;
  223. /// <summary>
  224. /// Creates new empty inspector field drawer.
  225. /// </summary>
  226. /// <param name="context">Context shared by all inspectable fields created by the same parent.</param>
  227. /// <param name="layout">Parent layout that all the field GUI elements will be added to.</param>
  228. /// <param name="path">Root path to be used for all created child fields.</param>
  229. /// <param name="depth">
  230. /// Determines how deep within the inspector nesting hierarchy will the generated fields be. Some fields may
  231. /// contain other fields, in which case you should increase this value by one.
  232. /// </param>
  233. public InspectorFieldDrawer(InspectableContext context, GUILayoutY layout, string path = "", int depth = 0)
  234. {
  235. this.context = context;
  236. this.layout = layout;
  237. this.path = path;
  238. this.depth = depth;
  239. }
  240. /// <summary>
  241. /// Creates the default inspector GUI for the provided object.
  242. /// </summary>
  243. /// <param name="obj">Object whose fields to create the GUI for.</param>
  244. /// <param name="subType">
  245. /// If not null, the added fields will be limited to this particular type (not including any base types the actual
  246. /// object type might be a part of). If null, then fields for the entire class hierarchy of the provided object's
  247. /// type will be created.
  248. /// </param>
  249. /// <param name="overrideCallback">
  250. /// Optional callback that allows you to override the look of individual fields in the object. If non-null the
  251. /// callback will be called with information about every field in the provided object. If the callback returns
  252. /// non-null that inspectable field will be used for drawing the GUI, otherwise the default inspector field type
  253. /// will be used.
  254. /// </param>
  255. public void AddDefault(object obj, Type subType = null, FieldOverrideCallback overrideCallback = null)
  256. {
  257. if (obj == null)
  258. return;
  259. SerializableObject serializableObject = new SerializableObject(obj.GetType(), obj);
  260. AddDefault(serializableObject, subType, overrideCallback);
  261. }
  262. /// <summary>
  263. /// Creates the default inspector GUI for the provided object.
  264. /// </summary>
  265. /// <param name="obj">Object whose fields to create the GUI for.</param>
  266. /// <param name="subType">
  267. /// If not null, the added fields will be limited to this particular type (not including any base types the actual
  268. /// object type might be a part of). If null, then fields for the entire class hierarchy of the provided object's
  269. /// type will be created.
  270. /// </param>
  271. /// <param name="overrideCallback">
  272. /// Optional callback that allows you to override the look of individual fields in the object. If non-null the
  273. /// callback will be called with information about every field in the provided object. If the callback returns
  274. /// non-null that inspectable field will be used for drawing the GUI, otherwise the default inspector field type
  275. /// will be used.
  276. /// </param>
  277. public void AddDefault(SerializableObject obj, Type subType = null, FieldOverrideCallback overrideCallback = null)
  278. {
  279. if (obj == null)
  280. return;
  281. // Retrieve fields and sort by order
  282. List<SerializableField> fields = new List<SerializableField>();
  283. while (obj != null)
  284. {
  285. if (subType == null || subType == obj.Type)
  286. {
  287. SerializableField[] subTypeFields = obj.Fields;
  288. Array.Sort(subTypeFields,
  289. (x, y) =>
  290. {
  291. int orderX = x.Flags.HasFlag(SerializableFieldAttributes.Order) ? x.Style.Order : 0;
  292. int orderY = y.Flags.HasFlag(SerializableFieldAttributes.Order) ? y.Style.Order : 0;
  293. return orderX.CompareTo(orderY);
  294. });
  295. fields.AddRange(subTypeFields);
  296. }
  297. obj = obj.Base;
  298. }
  299. // Generate per-field GUI while grouping by category
  300. int categoryIndex = 0;
  301. string categoryName = null;
  302. InspectableCategory category = null;
  303. foreach (var field in fields)
  304. {
  305. if (!field.Flags.HasFlag(SerializableFieldAttributes.Inspectable))
  306. continue;
  307. if (field.Flags.HasFlag(SerializableFieldAttributes.Category))
  308. {
  309. string newCategory = field.Style.CategoryName;
  310. if (!string.IsNullOrEmpty(newCategory) && categoryName != newCategory)
  311. {
  312. string categoryPath = string.IsNullOrEmpty(path) ? $"[{newCategory}]" : $"{path}/[{newCategory}]";
  313. category = new InspectableCategory(context, newCategory, categoryPath, depth,
  314. new InspectableFieldLayout(layout));
  315. category.Initialize(rootIndex);
  316. category.Refresh(rootIndex);
  317. rootIndex += category.GetNumLayoutElements();
  318. Fields.Add(category);
  319. categoryName = newCategory;
  320. categoryIndex = 0;
  321. }
  322. else
  323. {
  324. categoryName = null;
  325. category = null;
  326. }
  327. }
  328. int currentIndex;
  329. int childDepth;
  330. GUILayoutY parentLayout;
  331. if (category != null)
  332. {
  333. currentIndex = categoryIndex;
  334. parentLayout = category.ChildLayout;
  335. childDepth = depth + 1;
  336. }
  337. else
  338. {
  339. currentIndex = rootIndex;
  340. parentLayout = layout;
  341. childDepth = depth;
  342. }
  343. string fieldName = field.Name;
  344. string readableName = InspectableField.GetReadableIdentifierName(fieldName);
  345. string childPath = string.IsNullOrEmpty(path) ? fieldName : $"{path}/{fieldName}";
  346. InspectableField inspectableField = null;
  347. if (overrideCallback != null)
  348. inspectableField = overrideCallback(field, context, path, new InspectableFieldLayout(parentLayout),
  349. currentIndex, depth);
  350. if (inspectableField == null)
  351. {
  352. inspectableField = InspectableField.CreateField(context, readableName, childPath,
  353. currentIndex, childDepth, new InspectableFieldLayout(parentLayout), field.GetProperty(),
  354. InspectableFieldStyle.Create(field));
  355. }
  356. if (category != null)
  357. category.AddChild(inspectableField);
  358. else
  359. Fields.Add(inspectableField);
  360. currentIndex += inspectableField.GetNumLayoutElements();
  361. if (category != null)
  362. categoryIndex = currentIndex;
  363. else
  364. rootIndex = currentIndex;
  365. }
  366. }
  367. /// <summary>
  368. /// Adds a custom inspectable field with a custom getter and setter.
  369. /// </summary>
  370. /// <typeparam name="T">Type the field is inspecting.</typeparam>
  371. /// <param name="name">Name of the field.</param>
  372. /// <param name="getter">Method that returns the current value of the field.</param>
  373. /// <param name="setter">Method that sets a new value of the field.</param>
  374. public void AddField<T>(string name, Func<T> getter, Action<T> setter)
  375. {
  376. string childPath = string.IsNullOrEmpty(path) ? name : $"{path}/{name}";
  377. SerializableProperty property = SerializableProperty.Create(getter, setter);
  378. InspectableField inspectableField = InspectableField.CreateField(context, name, childPath,
  379. rootIndex, depth, new InspectableFieldLayout(layout), property);
  380. Fields.Add(inspectableField);
  381. rootIndex += inspectableField.GetNumLayoutElements();
  382. }
  383. /// <summary>
  384. /// Adds a condition that determines whether a field will be shown or hidde.
  385. /// </summary>
  386. /// <param name="field">Name of the field the condition applies to.</param>
  387. /// <param name="callback">The callback that returns true if the field should be shown, false otherwise.</param>
  388. public void AddConditional(string field, Func<bool> callback)
  389. {
  390. if(conditionals == null)
  391. conditionals = new List<ConditionalInfo>();
  392. conditionals.Add(new ConditionalInfo(field, callback));
  393. }
  394. /// <summary>
  395. /// Checks if contents of the inspector fields have been modified, and updates them if needed.
  396. /// </summary>
  397. /// <returns>State representing was anything modified between two last calls to <see cref="Refresh"/>.</returns>
  398. public InspectableState Refresh()
  399. {
  400. InspectableState state = InspectableState.NotModified;
  401. int currentIndex = 0;
  402. foreach (var field in Fields)
  403. {
  404. state |= field.Refresh(currentIndex);
  405. currentIndex += field.GetNumLayoutElements();
  406. if (conditionals != null)
  407. {
  408. foreach (var conditional in conditionals)
  409. {
  410. if (conditional.field == field.Name && conditional.callback != null)
  411. {
  412. bool active = conditional.callback();
  413. if (active != field.Active)
  414. field.Active = active;
  415. }
  416. }
  417. }
  418. }
  419. return state;
  420. }
  421. /// <summary>
  422. /// Destroys and removes all the child inspector fields.
  423. /// </summary>
  424. public void Clear()
  425. {
  426. foreach(var field in Fields)
  427. field.Destroy();
  428. Fields.Clear();
  429. conditionals?.Clear();
  430. rootIndex = 0;
  431. }
  432. /// <summary>
  433. /// Changes keyboard focus to the provided field.
  434. /// </summary>
  435. /// <param name="path">Path to the field on the object being inspected.</param>
  436. public void FocusOnField(string path)
  437. {
  438. InspectableField field = InspectableField.FindPath(path, 0, Fields);
  439. field?.SetHasFocus();
  440. }
  441. }
  442. /** @} */
  443. }