InspectableDictionary.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. using System;
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using System.Runtime.CompilerServices;
  7. using System.Text;
  8. using bs;
  9. namespace bs.Editor
  10. {
  11. /** @addtogroup Inspector
  12. * @{
  13. */
  14. /// <summary>
  15. /// Displays GUI for a serializable property containing a dictionary. Dictionary contents are displayed as rows of
  16. /// entries that can be shown, hidden or manipulated.
  17. /// </summary>
  18. public class InspectableDictionary : InspectableField
  19. {
  20. private InspectableDictionaryGUI dictionaryGUIField;
  21. /// <summary>
  22. /// Creates a new inspectable dictionary GUI for the specified property.
  23. /// </summary>
  24. /// <param name="context">Context shared by all inspectable fields created by the same parent.</param>
  25. /// <param name="title">Name of the property, or some other value to set as the title.</param>
  26. /// <param name="path">Full path to this property (includes name of this property and all parent properties).</param>
  27. /// <param name="depth">Determines how deep within the inspector nesting hierarchy is this field. Some fields may
  28. /// contain other fields, in which case you should increase this value by one.</param>
  29. /// <param name="layout">Parent layout that all the field elements will be added to.</param>
  30. /// <param name="property">Serializable property referencing the dictionary whose contents to display.</param>
  31. public InspectableDictionary(InspectableContext context, string title, string path, int depth, InspectableFieldLayout layout,
  32. SerializableProperty property)
  33. : base(context, title, path, SerializableProperty.FieldType.Dictionary, depth, layout, property)
  34. {
  35. }
  36. /// <inheritdoc/>
  37. public override GUILayoutX GetTitleLayout()
  38. {
  39. return dictionaryGUIField.GetTitleLayout();
  40. }
  41. /// <inheritdoc/>
  42. public override InspectableState Refresh(int layoutIndex)
  43. {
  44. return dictionaryGUIField.Refresh();
  45. }
  46. /// <inheritdoc/>
  47. protected internal override void Initialize(int layoutIndex)
  48. {
  49. GUILayout dictionaryLayout = layout.AddLayoutY(layoutIndex);
  50. dictionaryGUIField = InspectableDictionaryGUI.Create(context, title, path, property, dictionaryLayout, depth);
  51. dictionaryGUIField.IsExpanded = context.Persistent.GetBool(path + "_Expanded");
  52. dictionaryGUIField.OnExpand += x => context.Persistent.SetBool(path + "_Expanded", x);
  53. }
  54. /// <inheritdoc />
  55. public override InspectableField FindPath(string path)
  56. {
  57. string subPath = GetSubPath(path, depth + 1);
  58. if (string.IsNullOrEmpty(subPath))
  59. return null;
  60. int lastLeftIdx = subPath.LastIndexOf("Key[");
  61. int lastRightIdx = -1;
  62. bool isKey;
  63. if (lastLeftIdx != -1)
  64. {
  65. lastRightIdx = subPath.LastIndexOf(']', lastLeftIdx);
  66. isKey = true;
  67. }
  68. else
  69. {
  70. lastLeftIdx = subPath.LastIndexOf("Value[");
  71. lastRightIdx = subPath.LastIndexOf(']', lastLeftIdx);
  72. isKey = false;
  73. }
  74. if (lastLeftIdx == -1 || lastRightIdx == -1)
  75. return null;
  76. int count = lastRightIdx - 1 - lastLeftIdx;
  77. if (count <= 0)
  78. return null;
  79. string arrayIdxStr = subPath.Substring(lastLeftIdx, count);
  80. if (!int.TryParse(arrayIdxStr, out int idx))
  81. return null;;
  82. if (idx >= dictionaryGUIField.NumRows)
  83. return null;
  84. InspectableDictionaryGUIRow row = dictionaryGUIField.GetRow(idx);
  85. InspectableField field = null;
  86. if (isKey)
  87. field = row?.FieldKey;
  88. else
  89. field = row?.FieldValue;
  90. if (field != null)
  91. {
  92. if (field.Path == path)
  93. return field;
  94. return field.FindPath(path);
  95. }
  96. return null;
  97. }
  98. /// <summary>
  99. /// Creates GUI elements that allow viewing and manipulation of a <see cref="SerializableDictionary"/> referenced
  100. /// by a serializable property.
  101. /// </summary>
  102. private class InspectableDictionaryGUI : GUIDictionaryFieldBase
  103. {
  104. private SerializableProperty property;
  105. private IDictionary dictionary;
  106. private int numElements;
  107. private InspectableContext context;
  108. private string path;
  109. private List<SerializableProperty> orderedKeys = new List<SerializableProperty>();
  110. /// <summary>
  111. /// Context shared by all inspectable fields created by the same parent.
  112. /// </summary>
  113. public InspectableContext Context
  114. {
  115. get { return context; }
  116. }
  117. /// <summary>
  118. /// Returns a property path to the array field (name of the array field and all parent object fields).
  119. /// </summary>
  120. public string Path
  121. {
  122. get { return path; }
  123. }
  124. /// <summary>
  125. /// Returns the number of rows in the array.
  126. /// </summary>
  127. public int NumRows
  128. {
  129. get { return GetNumRows(); }
  130. }
  131. /// <summary>
  132. /// Constructs a new dictionary GUI.
  133. /// </summary>
  134. /// <param name="context">Context shared by all inspectable fields created by the same parent.</param>
  135. /// <param name="title">Label to display on the list GUI title.</param>
  136. /// <param name="path">Full path to this property (includes name of this property and all parent properties).
  137. /// </param>
  138. /// <param name="property">Serializable property referencing a dictionary</param>
  139. /// <param name="layout">Layout to which to append the list GUI elements to.</param>
  140. /// <param name="depth">Determines at which depth to render the background. Useful when you have multiple
  141. /// nested containers whose backgrounds are overlaping. Also determines background style,
  142. /// depths divisible by two will use an alternate style.</param>
  143. protected InspectableDictionaryGUI(InspectableContext context, LocString title, string path, SerializableProperty property,
  144. GUILayout layout, int depth = 0)
  145. : base(title, layout, depth)
  146. {
  147. this.property = property;
  148. this.context = context;
  149. this.path = path;
  150. dictionary = property.GetValue<IDictionary>();
  151. if (dictionary != null)
  152. numElements = dictionary.Count;
  153. UpdateKeys();
  154. }
  155. /// <summary>
  156. /// Builds the inspectable dictionary GUI elements. Must be called at least once in order for the contents to
  157. /// be populated.
  158. /// </summary>
  159. /// <param name="context">Context shared by all inspectable fields created by the same parent.</param>
  160. /// <param name="title">Label to display on the list GUI title.</param>
  161. /// <param name="path">Full path to this property (includes name of this property and all parent properties).
  162. /// </param>
  163. /// <param name="property">Serializable property referencing a dictionary</param>
  164. /// <param name="layout">Layout to which to append the list GUI elements to.</param>
  165. /// <param name="depth">Determines at which depth to render the background. Useful when you have multiple
  166. /// nested containers whose backgrounds are overlaping. Also determines background style,
  167. /// depths divisible by two will use an alternate style.</param>
  168. public static InspectableDictionaryGUI Create(InspectableContext context, LocString title, string path,
  169. SerializableProperty property, GUILayout layout, int depth = 0)
  170. {
  171. InspectableDictionaryGUI guiDictionary = new InspectableDictionaryGUI(context, title, path, property,
  172. layout, depth);
  173. guiDictionary.BuildGUI();
  174. return guiDictionary;
  175. }
  176. /// <summary>
  177. /// Returns an array row at the specified index.
  178. /// </summary>
  179. /// <param name="idx">Index of the row.</param>
  180. /// <returns>Array row representation or null if index is out of range.</returns>
  181. public InspectableDictionaryGUIRow GetRow(int idx)
  182. {
  183. if (idx < GetNumRows())
  184. return (InspectableDictionaryGUIRow)rows[idx];
  185. return null;
  186. }
  187. /// <inheritdoc/>
  188. public override InspectableState Refresh()
  189. {
  190. // Check if any modifications to the array were made outside the inspector
  191. IDictionary newDict = property.GetValue<IDictionary>();
  192. if (dictionary == null && newDict != null)
  193. {
  194. dictionary = newDict;
  195. numElements = dictionary.Count;
  196. BuildGUI();
  197. }
  198. else if (newDict == null && dictionary != null)
  199. {
  200. dictionary = null;
  201. numElements = 0;
  202. BuildGUI();
  203. }
  204. else
  205. {
  206. if (dictionary != null)
  207. {
  208. if (numElements != dictionary.Count)
  209. {
  210. numElements = dictionary.Count;
  211. BuildGUI();
  212. }
  213. }
  214. }
  215. return base.Refresh();
  216. }
  217. /// <summary>
  218. /// Updates the ordered set of keys used for mapping sequential indexes to keys. Should be called whenever a
  219. /// dictionary key changes.
  220. /// </summary>
  221. private void UpdateKeys()
  222. {
  223. orderedKeys.Clear();
  224. if (dictionary != null)
  225. {
  226. SerializableDictionary dict = property.GetDictionary();
  227. foreach (var key in dictionary.Keys)
  228. orderedKeys.Add(dict.GetProperty(key).Key);
  229. }
  230. }
  231. /// <inheritdoc/>
  232. protected override GUIDictionaryFieldRow CreateRow()
  233. {
  234. return new InspectableDictionaryGUIRow();
  235. }
  236. /// <inheritdoc/>
  237. protected override int GetNumRows()
  238. {
  239. if (dictionary != null)
  240. return dictionary.Count;
  241. return 0;
  242. }
  243. /// <inheritdoc/>
  244. protected override bool IsNull()
  245. {
  246. return dictionary == null;
  247. }
  248. /// <inheritdoc/>
  249. protected internal override object GetKey(int rowIdx)
  250. {
  251. return orderedKeys[rowIdx];
  252. }
  253. /// <inheritdoc/>
  254. protected internal override object GetValue(object key)
  255. {
  256. SerializableProperty keyProperty = (SerializableProperty)key;
  257. SerializableDictionary dictionary = property.GetDictionary();
  258. return dictionary.GetProperty(keyProperty.GetValue<object>()).Value;
  259. }
  260. /// <inheritdoc/>
  261. protected internal override void SetValue(object key, object value)
  262. {
  263. // Setting the value should be done through the property
  264. throw new InvalidOperationException();
  265. }
  266. /// <inheritdoc/>
  267. protected internal override bool Contains(object key)
  268. {
  269. SerializableProperty keyProperty = (SerializableProperty)key;
  270. return dictionary.Contains(keyProperty.GetValue<object>()); ;
  271. }
  272. /// <inheritdoc/>
  273. protected internal override void EditEntry(object oldKey, object newKey, object value)
  274. {
  275. SerializableProperty oldKeyProperty = (SerializableProperty)oldKey;
  276. SerializableProperty newKeyProperty = (SerializableProperty)newKey;
  277. SerializableProperty valueProperty = (SerializableProperty)value;
  278. dictionary.Remove(oldKeyProperty.GetValue<object>());
  279. dictionary.Add(newKeyProperty.GetValue<object>(), valueProperty.GetValue<object>());
  280. numElements = dictionary.Count;
  281. UpdateKeys();
  282. }
  283. /// <inheritdoc/>
  284. protected internal override void AddEntry(object key, object value)
  285. {
  286. StartUndo();
  287. SerializableProperty keyProperty = (SerializableProperty)key;
  288. SerializableProperty valueProperty = (SerializableProperty)value;
  289. dictionary.Add(keyProperty.GetValue<object>(), valueProperty.GetValue<object>());
  290. numElements = dictionary.Count;
  291. EndUndo();
  292. UpdateKeys();
  293. }
  294. /// <inheritdoc/>
  295. protected internal override void RemoveEntry(object key)
  296. {
  297. StartUndo();
  298. SerializableProperty keyProperty = (SerializableProperty)key;
  299. dictionary.Remove(keyProperty.GetValue<object>());
  300. numElements = dictionary.Count;
  301. EndUndo();
  302. UpdateKeys();
  303. }
  304. /// <inheritdoc/>
  305. protected internal override object CreateKey()
  306. {
  307. SerializableDictionary dictionary = property.GetDictionary();
  308. DictionaryDataWrapper data = new DictionaryDataWrapper();
  309. data.value = SerializableUtility.Create(dictionary.KeyType);
  310. SerializableProperty keyProperty = new SerializableProperty(dictionary.KeyPropertyType,
  311. dictionary.KeyType,
  312. () => data.value, (x) => data.value = x);
  313. return keyProperty;
  314. }
  315. /// <inheritdoc/>
  316. protected internal override object CreateValue()
  317. {
  318. SerializableDictionary dictionary = property.GetDictionary();
  319. DictionaryDataWrapper data = new DictionaryDataWrapper();
  320. data.value = SerializableUtility.Create(dictionary.ValueType);
  321. SerializableProperty valueProperty = new SerializableProperty(dictionary.ValuePropertyType,
  322. dictionary.ValueType,
  323. () => data.value, (x) => data.value = x);
  324. return valueProperty;
  325. }
  326. /// <inheritdoc/>
  327. protected internal override KeyValuePair<object, object> CloneElement(int index)
  328. {
  329. SerializableProperty keyProperty = (SerializableProperty)GetKey(index);
  330. SerializableProperty valueProperty = (SerializableProperty)GetValue(keyProperty);
  331. SerializableDictionary dictionary = property.GetDictionary();
  332. DictionaryDataWrapper keyData = new DictionaryDataWrapper();
  333. keyData.value = SerializableUtility.Clone(keyProperty.GetValue<object>());
  334. SerializableProperty clonedKeyProperty = new SerializableProperty(dictionary.KeyPropertyType,
  335. dictionary.KeyType,
  336. () => keyData.value, (x) => keyData.value = x);
  337. DictionaryDataWrapper valueData = new DictionaryDataWrapper();
  338. valueData.value = SerializableUtility.Clone(valueProperty.GetValue<object>());
  339. SerializableProperty clonedValueProperty = new SerializableProperty(dictionary.ValuePropertyType,
  340. dictionary.ValueType,
  341. () => valueData.value, (x) => valueData.value = x);
  342. return new KeyValuePair<object,object>(clonedKeyProperty, clonedValueProperty);
  343. }
  344. /// <inheritdoc/>
  345. protected override void CreateDictionary()
  346. {
  347. StartUndo();
  348. dictionary = property.CreateDictionaryInstance();
  349. numElements = dictionary.Count;
  350. property.SetValue(dictionary);
  351. EndUndo();
  352. UpdateKeys();
  353. }
  354. /// <inheritdoc/>
  355. protected override void DeleteDictionary()
  356. {
  357. StartUndo();
  358. dictionary = null;
  359. numElements = 0;
  360. property.SetValue<object>(null);
  361. EndUndo();
  362. UpdateKeys();
  363. }
  364. /// <summary>
  365. /// Notifies the system to start recording a new undo command. Any changes to the field after this is called
  366. /// will be recorded in the command. User must call <see cref="EndUndo"/> after field is done being changed.
  367. /// </summary>
  368. protected void StartUndo()
  369. {
  370. if (context.Component != null)
  371. GameObjectUndo.RecordComponent(context.Component, path);
  372. }
  373. /// <summary>
  374. /// Finishes recording an undo command started via <see cref="StartUndo"/>. If any changes are detected on the
  375. /// field an undo command is recorded onto the undo-redo stack, otherwise nothing is done.
  376. /// </summary>
  377. protected void EndUndo()
  378. {
  379. GameObjectUndo.ResolveDiffs();
  380. }
  381. /// <summary>
  382. /// Wraps a dictionary key or a value.
  383. /// </summary>
  384. class DictionaryDataWrapper
  385. {
  386. public object value;
  387. }
  388. }
  389. /// <summary>
  390. /// Contains GUI elements for a single key/value pair in the dictionary.
  391. /// </summary>
  392. private class InspectableDictionaryGUIRow : GUIDictionaryFieldRow
  393. {
  394. /// <summary>
  395. /// Inspectable field displaying the key on the dictionary row.
  396. /// </summary>
  397. public InspectableField FieldKey { get; private set; }
  398. /// <summary>
  399. /// Inspectable field displaying the value on the dictionary row.
  400. /// </summary>
  401. public InspectableField FieldValue { get; private set; }
  402. private GUILayoutY keyLayout;
  403. /// <inheritdoc/>
  404. protected override GUILayoutX CreateKeyGUI(GUILayoutY layout)
  405. {
  406. keyLayout = layout;
  407. InspectableDictionaryGUI dictParent = (InspectableDictionaryGUI)parent;
  408. SerializableProperty property = GetKey<SerializableProperty>();
  409. string entryPath = dictParent.Path + "Key[" + RowIdx + "]";
  410. FieldKey = CreateField(dictParent.Context, "Key", entryPath, 0, Depth + 1,
  411. new InspectableFieldLayout(layout), property);
  412. return FieldKey.GetTitleLayout();
  413. }
  414. /// <inheritdoc/>
  415. protected override void CreateValueGUI(GUILayoutY layout)
  416. {
  417. InspectableDictionaryGUI dictParent = (InspectableDictionaryGUI)parent;
  418. SerializableProperty property = GetValue<SerializableProperty>();
  419. string entryPath = dictParent.Path + "Value[" + RowIdx + "]";
  420. FieldValue = CreateField(dictParent.Context, "Value", entryPath, 0, Depth + 1,
  421. new InspectableFieldLayout(layout), property);
  422. }
  423. /// <inheritdoc/>
  424. protected override void OnEditModeChanged(bool editMode)
  425. {
  426. keyLayout.Disabled = !editMode;
  427. }
  428. /// <inheritdoc/>
  429. protected internal override InspectableState Refresh()
  430. {
  431. FieldKey.Property = GetKey<SerializableProperty>();
  432. FieldValue.Property = GetValue<SerializableProperty>();
  433. return FieldValue.Refresh(0);
  434. }
  435. }
  436. }
  437. /** @} */
  438. }