Inspector.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  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. /// Zero parameter wrapper for <see cref="StartUndo(string)"/>
  139. /// </summary>
  140. protected void StartUndo()
  141. {
  142. StartUndo(null);
  143. }
  144. /// <summary>
  145. /// Notifies the system to start recording a new undo command. Any changes to the field after this is called
  146. /// will be recorded in the command. User must call <see cref="EndUndo"/> after field is done being changed.
  147. /// </summary>
  148. /// <param name="field">Name of the field being modified.</param>
  149. protected void StartUndo(string field)
  150. {
  151. if (inspectedObject is Component component)
  152. GameObjectUndo.RecordComponent(component, field);
  153. }
  154. /// <summary>
  155. /// Finishes recording an undo command started via <see cref="StartUndo(string)"/>. If any changes are detected on
  156. /// the object an undo command is recorded onto the undo-redo stack, otherwise nothing is done.
  157. /// </summary>
  158. protected void EndUndo()
  159. {
  160. GameObjectUndo.ResolveDiffs();
  161. }
  162. /// <summary>
  163. /// Loads the currently inspected resource into the <see cref="InspectedObject"/> field. By default resources
  164. /// are not loaded and you can only retrieve their path through <see cref="InspectedResourcePath"/>.
  165. /// </summary>
  166. protected void LoadResource()
  167. {
  168. if(!string.IsNullOrEmpty(inspectedResourcePath))
  169. inspectedObject = ProjectLibrary.Load<Resource>(inspectedResourcePath);
  170. }
  171. /// <summary>
  172. /// Hides or shows the inspector GUI elements.
  173. /// </summary>
  174. /// <param name="visible">True to make the GUI elements visible.</param>
  175. internal virtual void SetVisible(bool visible)
  176. {
  177. rootGUI.Active = visible;
  178. }
  179. /// <summary>
  180. /// Destroys all inspector GUI elements.
  181. /// </summary>
  182. internal void Destroy()
  183. {
  184. Layout.Destroy();
  185. GUI.Destroy();
  186. }
  187. /// <summary>
  188. /// Called when the inspector is first created.
  189. /// </summary>
  190. protected internal abstract void Initialize();
  191. /// <summary>
  192. /// Checks if contents of the inspector have been modified, and updates them if needed.
  193. /// </summary>
  194. /// <param name="force">Forces the GUI fields to display the latest values assigned on the object.</param>
  195. /// <returns>State representing was anything modified between two last calls to <see cref="Refresh"/>.</returns>
  196. protected internal virtual InspectableState Refresh(bool force = false)
  197. {
  198. return drawer.Refresh(force);
  199. }
  200. }
  201. /// <summary>
  202. /// Helper class that draws the inspector field elements for an object, allowing you to draw default set of fields,
  203. /// override certain fields with your own, or add new fields manually.
  204. /// </summary>
  205. public sealed class InspectorFieldDrawer
  206. {
  207. /// <summary>
  208. /// Contains information about a conditional that determines whether a field will be active or not.
  209. /// </summary>
  210. private struct ConditionalInfo
  211. {
  212. public Func<bool> callback;
  213. public string field;
  214. public ConditionalInfo(string field, Func<bool> callback)
  215. {
  216. this.field = field;
  217. this.callback = callback;
  218. }
  219. }
  220. /// <summary>
  221. /// Allows the user to override the default inspector GUI for a specific field in an object. If this method
  222. /// returns null the default field will be used instead.
  223. /// </summary>
  224. /// <param name="field">Field to generate inspector GUI for.</param>
  225. /// <param name="context">Context shared by all inspectable fields created by the same parent.</param>
  226. /// <param name="path">Full path to the provided field (includes name of this field and all parent fields).</param>
  227. /// <param name="layout">Parent layout that all the field elements will be added to.</param>
  228. /// <param name="layoutIndex">Index into the parent layout at which to insert the GUI elements for the field .</param>
  229. /// <param name="depth">
  230. /// Determines how deep within the inspector nesting hierarchy is this field. Some fields may contain other fields,
  231. /// in which case you should increase this value by one.
  232. /// </param>
  233. /// <returns>
  234. /// Inspectable field implementation that can be used for displaying the GUI for the provided field. Or null if
  235. /// default field GUI should be used instead.
  236. /// </returns>
  237. public delegate InspectableField FieldOverrideCallback(SerializableField field, InspectableContext context, string path,
  238. InspectableFieldLayout layout, int layoutIndex, int depth);
  239. /// <summary>
  240. /// List of fields created and updated by the drawer.
  241. /// </summary>
  242. public List<InspectableField> Fields { get; } = new List<InspectableField>();
  243. private InspectableContext context;
  244. private GUILayoutY layout;
  245. private string path;
  246. private int depth;
  247. private int rootIndex;
  248. private List<ConditionalInfo> conditionals;
  249. // Category
  250. private int categoryIndex;
  251. private string categoryName;
  252. private InspectableCategory category;
  253. /// <summary>
  254. /// Creates new empty inspector field drawer.
  255. /// </summary>
  256. /// <param name="context">Context shared by all inspectable fields created by the same parent.</param>
  257. /// <param name="layout">Parent layout that all the field GUI elements will be added to.</param>
  258. /// <param name="path">Root path to be used for all created child fields.</param>
  259. /// <param name="depth">
  260. /// Determines how deep within the inspector nesting hierarchy will the generated fields be. Some fields may
  261. /// contain other fields, in which case you should increase this value by one.
  262. /// </param>
  263. public InspectorFieldDrawer(InspectableContext context, GUILayoutY layout, string path = "", int depth = 0)
  264. {
  265. this.context = context;
  266. this.layout = layout;
  267. this.path = path;
  268. this.depth = depth;
  269. }
  270. /// <summary>
  271. /// Creates the default inspector GUI for the provided object.
  272. /// </summary>
  273. /// <param name="obj">Object whose fields to create the GUI for.</param>
  274. /// <param name="subType">
  275. /// If not null, the added fields will be limited to this particular type (not including any base types the actual
  276. /// object type might be a part of). If null, then fields for the entire class hierarchy of the provided object's
  277. /// type will be created.
  278. /// </param>
  279. /// <param name="overrideCallback">
  280. /// Optional callback that allows you to override the look of individual fields in the object. If non-null the
  281. /// callback will be called with information about every field in the provided object. If the callback returns
  282. /// non-null that inspectable field will be used for drawing the GUI, otherwise the default inspector field type
  283. /// will be used.
  284. /// </param>
  285. public void AddDefault(object obj, Type subType = null, FieldOverrideCallback overrideCallback = null)
  286. {
  287. if (obj == null)
  288. return;
  289. SerializableObject serializableObject = new SerializableObject(obj.GetType(), obj);
  290. AddDefault(serializableObject, subType, overrideCallback);
  291. }
  292. /// <summary>
  293. /// Creates the default inspector GUI for the provided object.
  294. /// </summary>
  295. /// <param name="obj">Object whose fields to create the GUI for.</param>
  296. /// <param name="subType">
  297. /// If not null, the added fields will be limited to this particular type (not including any base types the actual
  298. /// object type might be a part of). If null, then fields for the entire class hierarchy of the provided object's
  299. /// type will be created.
  300. /// </param>
  301. /// <param name="overrideCallback">
  302. /// Optional callback that allows you to override the look of individual fields in the object. If non-null the
  303. /// callback will be called with information about every field in the provided object. If the callback returns
  304. /// non-null that inspectable field will be used for drawing the GUI, otherwise the default inspector field type
  305. /// will be used.
  306. /// </param>
  307. public void AddDefault(SerializableObject obj, Type subType = null, FieldOverrideCallback overrideCallback = null)
  308. {
  309. if (obj == null)
  310. return;
  311. // Retrieve fields and sort by order
  312. List<SerializableField> fields = new List<SerializableField>();
  313. while (obj != null)
  314. {
  315. if (subType == null || subType == obj.Type)
  316. {
  317. SerializableField[] subTypeFields = obj.Fields;
  318. Array.Sort(subTypeFields,
  319. (x, y) =>
  320. {
  321. int orderX = x.Flags.HasFlag(SerializableFieldAttributes.Order) ? x.Style.Order : 0;
  322. int orderY = y.Flags.HasFlag(SerializableFieldAttributes.Order) ? y.Style.Order : 0;
  323. return orderX.CompareTo(orderY);
  324. });
  325. fields.AddRange(subTypeFields);
  326. }
  327. obj = obj.Base;
  328. }
  329. // Generate per-field GUI while grouping by category
  330. foreach (var field in fields)
  331. {
  332. if (!field.Flags.HasFlag(SerializableFieldAttributes.Inspectable))
  333. continue;
  334. if (field.Flags.HasFlag(SerializableFieldAttributes.Category))
  335. {
  336. string newCategory = field.Style.CategoryName;
  337. if (!string.IsNullOrEmpty(newCategory) && categoryName != newCategory)
  338. BeginCategory(newCategory);
  339. else
  340. EndCategory();
  341. }
  342. string fieldName = field.Name;
  343. string readableName = InspectableField.GetReadableIdentifierName(fieldName);
  344. Func<string, InspectableFieldLayout, int, int, InspectableField> callback = null;
  345. if (overrideCallback != null)
  346. {
  347. callback = (path, fieldLayout, layoutIndex, depth) =>
  348. overrideCallback(field, context, path, fieldLayout, layoutIndex, depth);
  349. }
  350. AddFieldInternal(readableName, fieldName, field.GetProperty(), InspectableFieldStyle.Create(field),
  351. callback);
  352. }
  353. }
  354. /// <summary>
  355. /// Adds a custom inspectable field with a custom getter and setter.
  356. /// </summary>
  357. /// <typeparam name="T">Type the field is inspecting.</typeparam>
  358. /// <param name="name">Name of the field.</param>
  359. /// <param name="getter">Method that returns the current value of the field.</param>
  360. /// <param name="setter">Method that sets a new value of the field.</param>
  361. public void AddField<T>(string name, Func<T> getter, Action<T> setter)
  362. {
  363. SerializableProperty property = SerializableProperty.Create(getter, setter);
  364. AddFieldInternal(name, name, property, null, null);
  365. }
  366. /// <summary>
  367. /// Creates a new field accessing the provided property.
  368. /// </summary>
  369. /// <param name="title">Title to display on the field.</param>
  370. /// <param name="name">Name of the field.</param>
  371. /// <param name="property">Property used to access the field contents.</param>
  372. /// <param name="style">Optional style used to customize the look of the field.</param>
  373. /// <param name="fieldCreateCallback">
  374. /// Optional callback allowing the caller to override how is the field created.
  375. /// </param>
  376. private void AddFieldInternal(string title, string name, SerializableProperty property,
  377. InspectableFieldStyleInfo style,
  378. Func<string, InspectableFieldLayout, int, int, InspectableField> fieldCreateCallback)
  379. {
  380. int currentIndex;
  381. int childDepth;
  382. GUILayoutY parentLayout;
  383. if (category != null)
  384. {
  385. currentIndex = categoryIndex;
  386. parentLayout = category.ChildLayout;
  387. childDepth = depth + 1;
  388. }
  389. else
  390. {
  391. currentIndex = rootIndex;
  392. parentLayout = layout;
  393. childDepth = depth;
  394. }
  395. string childPath = string.IsNullOrEmpty(path) ? name : $"{path}/{name}";
  396. InspectableField inspectableField = null;
  397. if (fieldCreateCallback != null)
  398. inspectableField = fieldCreateCallback(path, new InspectableFieldLayout(parentLayout), currentIndex, depth);
  399. if (inspectableField == null)
  400. {
  401. inspectableField = InspectableField.CreateField(context, title, childPath,
  402. currentIndex, childDepth, new InspectableFieldLayout(parentLayout), property, style);
  403. }
  404. if (category != null)
  405. category.AddChild(inspectableField);
  406. else
  407. Fields.Add(inspectableField);
  408. currentIndex += inspectableField.GetNumLayoutElements();
  409. if (category != null)
  410. categoryIndex = currentIndex;
  411. else
  412. rootIndex = currentIndex;
  413. }
  414. /// <summary>
  415. /// Adds a condition that determines whether a field will be shown or hidde.
  416. /// </summary>
  417. /// <param name="field">Name of the field the condition applies to.</param>
  418. /// <param name="callback">The callback that returns true if the field should be shown, false otherwise.</param>
  419. public void AddConditional(string field, Func<bool> callback)
  420. {
  421. if(conditionals == null)
  422. conditionals = new List<ConditionalInfo>();
  423. conditionals.Add(new ConditionalInfo(field, callback));
  424. }
  425. /// <summary>
  426. /// Opens up a new category. Any new fields will be parented to this category. Category must be closed by calling
  427. /// <see cref="EndCategory"/> or by calling this method with a new category.
  428. /// </summary>
  429. /// <param name="name">Name of the category.</param>
  430. public void BeginCategory(string name)
  431. {
  432. if(category != null)
  433. EndCategory();
  434. string categoryPath = string.IsNullOrEmpty(path) ? $"[{name}]" : $"{path}/[{name}]";
  435. category = new InspectableCategory(context, name, categoryPath, depth,
  436. new InspectableFieldLayout(layout));
  437. category.Initialize(rootIndex);
  438. category.Refresh(rootIndex);
  439. rootIndex += category.GetNumLayoutElements();
  440. Fields.Add(category);
  441. categoryName = name;
  442. categoryIndex = 0;
  443. }
  444. /// <summary>
  445. /// Ends the category started with <see cref="BeginCategory"/>.
  446. /// </summary>
  447. public void EndCategory()
  448. {
  449. category = null;
  450. categoryName = null;
  451. categoryIndex = 0;
  452. }
  453. /// <summary>
  454. /// Checks if contents of the inspector fields have been modified, and updates them if needed.
  455. /// </summary>
  456. /// <param name="force">Forces the GUI fields to display the latest values assigned on the object.</param>
  457. /// <returns>State representing was anything modified between two last calls to <see cref="Refresh"/>.</returns>
  458. public InspectableState Refresh(bool force = false)
  459. {
  460. InspectableState state = InspectableState.NotModified;
  461. int currentIndex = 0;
  462. foreach (var field in Fields)
  463. {
  464. state |= field.Refresh(currentIndex, force);
  465. currentIndex += field.GetNumLayoutElements();
  466. if (conditionals != null)
  467. {
  468. foreach (var conditional in conditionals)
  469. {
  470. if (conditional.field == field.Name && conditional.callback != null)
  471. {
  472. bool active = conditional.callback();
  473. if (active != field.Active)
  474. field.Active = active;
  475. }
  476. }
  477. }
  478. }
  479. return state;
  480. }
  481. /// <summary>
  482. /// Destroys and removes all the child inspector fields.
  483. /// </summary>
  484. public void Clear()
  485. {
  486. foreach(var field in Fields)
  487. field.Destroy();
  488. Fields.Clear();
  489. conditionals?.Clear();
  490. rootIndex = 0;
  491. category = null;
  492. categoryName = null;
  493. categoryIndex = 0;
  494. }
  495. /// <summary>
  496. /// Changes keyboard focus to the provided field.
  497. /// </summary>
  498. /// <param name="path">Path to the field on the object being inspected.</param>
  499. public void FocusOnField(string path)
  500. {
  501. InspectableField field = InspectableField.FindPath(path, 0, Fields);
  502. field?.SetHasFocus();
  503. }
  504. }
  505. /** @} */
  506. }