GUIDictionaryField.cs 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using BansheeEngine;
  5. namespace BansheeEditor
  6. {
  7. /// <summary>
  8. /// Base class for objects that display GUI for a modifyable dictionary of elements. Elements can be added, modified or
  9. /// removed.
  10. /// </summary>
  11. public abstract class GUIDictionaryFieldBase
  12. {
  13. private const int IndentAmount = 5;
  14. protected Dictionary<int, GUIDictionaryFieldRow> rows = new Dictionary<int, GUIDictionaryFieldRow>();
  15. protected GUIDictionaryFieldRow editRow;
  16. protected GUILayoutX guiChildLayout;
  17. protected GUILayoutX guiTitleLayout;
  18. protected GUILayoutY guiContentLayout;
  19. protected bool isExpanded;
  20. protected int depth;
  21. private int editRowIdx = -1;
  22. private object editKey;
  23. private object editValue;
  24. private object editOriginalKey;
  25. /// <summary>
  26. /// Constructs a new GUI dictionary.
  27. /// </summary>
  28. protected GUIDictionaryFieldBase()
  29. { }
  30. /// <summary>
  31. /// Builds the dictionary GUI elements. Must be called at least once in order for the contents to be populated.
  32. /// </summary>
  33. /// <typeparam name="T">Type of rows that are used to handle GUI for individual dictionary elements.</typeparam>
  34. /// <param name="title">Label to display on the dictionary GUI title.</param>
  35. /// <param name="empty">Should the created field represent a null object.</param>
  36. /// <param name="numRows">Number of rows to create GUI for. Only matters for a non-null dictionary.</param>
  37. /// <param name="layout">Layout to which to append the list GUI elements to.</param>
  38. /// <param name="depth">Determines at which depth to render the background. Useful when you have multiple
  39. /// nested containers whose backgrounds are overlaping. Also determines background style,
  40. /// depths divisible by two will use an alternate style.</param>
  41. protected void BuildGUI<T>(LocString title, bool empty, int numRows, GUILayout layout,
  42. int depth = 0) where T : GUIDictionaryFieldRow, new()
  43. {
  44. Destroy();
  45. this.depth = depth;
  46. this.editKey = CreateKey();
  47. this.editValue = CreateValue();
  48. if (empty)
  49. {
  50. rows.Clear();
  51. guiChildLayout = null;
  52. guiContentLayout = null;
  53. guiTitleLayout = layout.AddLayoutX();
  54. guiTitleLayout.AddElement(new GUILabel(title));
  55. guiTitleLayout.AddElement(new GUILabel("Empty", GUIOption.FixedWidth(100)));
  56. GUIContent createIcon = new GUIContent(EditorBuiltin.GetInspectorWindowIcon(InspectorWindowIcon.Create));
  57. GUIButton createBtn = new GUIButton(createIcon, GUIOption.FixedWidth(30));
  58. createBtn.OnClick += OnCreateButtonClicked;
  59. guiTitleLayout.AddElement(createBtn);
  60. }
  61. else
  62. {
  63. GUIToggle guiFoldout = new GUIToggle(title, EditorStyles.Foldout);
  64. guiFoldout.Value = isExpanded;
  65. guiFoldout.OnToggled += ToggleFoldout;
  66. GUIContent clearIcon = new GUIContent(EditorBuiltin.GetInspectorWindowIcon(InspectorWindowIcon.Clear));
  67. GUIButton guiClearBtn = new GUIButton(clearIcon, GUIOption.FixedWidth(30));
  68. guiClearBtn.OnClick += OnClearButtonClicked;
  69. GUIContent addIcon = new GUIContent(EditorBuiltin.GetInspectorWindowIcon(InspectorWindowIcon.Add));
  70. GUIButton guiAddBtn = new GUIButton(addIcon, GUIOption.FixedWidth(30));
  71. guiAddBtn.OnClick += OnAddButtonClicked;
  72. guiTitleLayout = layout.AddLayoutX();
  73. guiTitleLayout.AddElement(guiFoldout);
  74. guiTitleLayout.AddElement(guiAddBtn);
  75. guiTitleLayout.AddElement(guiClearBtn);
  76. guiChildLayout = layout.AddLayoutX();
  77. guiChildLayout.AddSpace(IndentAmount);
  78. GUIPanel guiContentPanel = guiChildLayout.AddPanel();
  79. GUILayoutX guiIndentLayoutX = guiContentPanel.AddLayoutX();
  80. guiIndentLayoutX.AddSpace(IndentAmount);
  81. GUILayoutY guiIndentLayoutY = guiIndentLayoutX.AddLayoutY();
  82. guiIndentLayoutY.AddSpace(IndentAmount);
  83. guiContentLayout = guiIndentLayoutY.AddLayoutY();
  84. guiIndentLayoutY.AddSpace(IndentAmount);
  85. guiIndentLayoutX.AddSpace(IndentAmount);
  86. guiChildLayout.AddSpace(IndentAmount);
  87. short backgroundDepth = (short)(Inspector.START_BACKGROUND_DEPTH - depth - 1);
  88. string bgPanelStyle = depth % 2 == 0
  89. ? EditorStyles.InspectorContentBgAlternate
  90. : EditorStyles.InspectorContentBg;
  91. GUIPanel backgroundPanel = guiContentPanel.AddPanel(backgroundDepth);
  92. GUITexture inspectorContentBg = new GUITexture(null, bgPanelStyle);
  93. backgroundPanel.AddElement(inspectorContentBg);
  94. // Hidden dependency: BuildGUI must be called after all elements are
  95. // in the dictionary so we do it in two steps
  96. for (int i = rows.Count; i < numRows; i++)
  97. {
  98. GUIDictionaryFieldRow newRow = new T();
  99. rows.Add(i, newRow);
  100. }
  101. for (int i = numRows; i < rows.Count; i++)
  102. rows.Remove(i);
  103. if(editRow == null)
  104. editRow = new T();
  105. editRow.BuildGUI(this, guiContentLayout, numRows, depth + 1);
  106. editRow.Enabled = false;
  107. for (int i = 0; i < numRows; i++)
  108. rows[i].BuildGUI(this, guiContentLayout, i, depth + 1);
  109. ToggleFoldout(isExpanded);
  110. }
  111. }
  112. /// <summary>
  113. /// Returns the layout that is used for positioning the elements in the title bar.
  114. /// </summary>
  115. /// <returns>Horizontal layout for positioning the title bar elements.</returns>
  116. public GUILayoutX GetTitleLayout()
  117. {
  118. return guiTitleLayout;
  119. }
  120. /// <summary>
  121. /// Refreshes contents of all dictionary rows and checks if anything was modified.
  122. /// </summary>
  123. /// <returns>True if any entry in the list was modified, false otherwise.</returns>
  124. public bool Refresh()
  125. {
  126. bool anythingModified = false;
  127. for (int i = 0; i < rows.Count; i++)
  128. {
  129. if (rows[i].Refresh())
  130. rows[i].BuildGUI(this, guiContentLayout, i, depth + 1);
  131. }
  132. if (editRow != null && editRow.Enabled)
  133. {
  134. if (editRow.Refresh())
  135. editRow.BuildGUI(this, guiContentLayout, rows.Count, depth + 1);
  136. }
  137. return anythingModified;
  138. }
  139. /// <summary>
  140. /// Destroys the GUI elements.
  141. /// </summary>
  142. public void Destroy()
  143. {
  144. if (guiTitleLayout != null)
  145. {
  146. guiTitleLayout.Destroy();
  147. guiTitleLayout = null;
  148. }
  149. if (guiChildLayout != null)
  150. {
  151. guiChildLayout.Destroy();
  152. guiChildLayout = null;
  153. }
  154. for (int i = 0; i < rows.Count; i++)
  155. rows[i].Destroy();
  156. if (editRow != null)
  157. editRow.Destroy();
  158. }
  159. /// <summary>
  160. /// Checks is the specified row index the temporary edit row.
  161. /// </summary>
  162. /// <param name="rowIdx">Sequential index of the row to check.</param>
  163. /// <returns>True if the index is of an edit row.</returns>
  164. private bool IsTemporaryRow(int rowIdx)
  165. {
  166. return rowIdx == rows.Count;
  167. }
  168. /// <summary>
  169. /// Checks is any row being currently edited.
  170. /// </summary>
  171. /// <returns>True if a row is being edited, false otherwise.</returns>
  172. private bool IsEditInProgress()
  173. {
  174. return editRowIdx != -1;
  175. }
  176. /// <summary>
  177. /// Gets a value of an element at the specified index in the list. Also handles temporary edit fields.
  178. /// </summary>
  179. /// <param name="rowIdx">Sequential index of the row to set the value for.</param>
  180. /// <returns>Value of the list element at the specified key.</returns>
  181. protected internal virtual object GetValueInternal(int rowIdx)
  182. {
  183. if (rowIdx == editRowIdx || IsTemporaryRow(rowIdx))
  184. return editValue;
  185. else
  186. return GetValue(GetKey(rowIdx));
  187. }
  188. /// <summary>
  189. /// Sets a value of an element at the specified index in the list. Also handles temporary edit fields.
  190. /// </summary>
  191. /// <param name="rowIdx">Sequential index of the row to set the value for.</param>
  192. /// <param name="value">Value to assign to the element. Caller must ensure it is of valid type.</param>
  193. protected internal virtual void SetValueInternal(int rowIdx, object value)
  194. {
  195. if (rowIdx == editRowIdx || IsTemporaryRow(rowIdx))
  196. editValue = value;
  197. else
  198. SetValue(GetKey(rowIdx), value);
  199. }
  200. /// <summary>
  201. /// Changes the value of the key of the specified row.
  202. /// </summary>
  203. /// <param name="rowIdx">Sequential index of the row to set the key for.</param>
  204. /// <param name="key">Key to assign to the specified row.</param>
  205. protected internal void SetKey(int rowIdx, object key)
  206. {
  207. if (editRowIdx != rowIdx)
  208. {
  209. Debug.LogError("Cannot change a dictionary row that is not in edit state.");
  210. return;
  211. }
  212. editKey = key;
  213. }
  214. /// <summary>
  215. /// Gets a key for a row at the specified index. Handles the special case for the currently edited row.
  216. /// </summary>
  217. /// <param name="rowIdx">Sequential index of the row for which to retrieve the key.</param>
  218. /// <returns>Key for a row at the specified index.</returns>
  219. protected internal object GetKeyInternal(int rowIdx)
  220. {
  221. if (editRowIdx == rowIdx || IsTemporaryRow(rowIdx))
  222. return editKey;
  223. return GetKey(rowIdx);
  224. }
  225. /// <summary>
  226. /// Gets a key for a row at the specified index.
  227. /// </summary>
  228. /// <param name="rowIdx">Sequential index of the row for which to retrieve the key.</param>
  229. /// <returns>Key for a row at the specified index.</returns>
  230. protected internal abstract object GetKey(int rowIdx);
  231. /// <summary>
  232. /// Gets a value of an element at the specified index in the list.
  233. /// </summary>
  234. /// <param name="key">Key of the element whose value to retrieve.</param>
  235. /// <returns>Value of the dictionary entry for the specified key.</returns>
  236. protected internal abstract object GetValue(object key);
  237. /// <summary>
  238. /// Sets a value of an element at the specified index in the list.
  239. /// </summary>
  240. /// <param name="key">Key of the element whose value to set.</param>
  241. /// <param name="value">Value to assign to the element. Caller must ensure it is of valid type.</param>
  242. protected internal abstract void SetValue(object key, object value);
  243. /// <summary>
  244. /// Updates both key and value of an existing entry.
  245. /// </summary>
  246. /// <param name="oldKey">Original key of the entry.</param>
  247. /// <param name="newKey">New key of the entry.</param>
  248. /// <param name="value">New value of the entry.</param>
  249. protected internal abstract void EditEntry(object oldKey, object newKey, object value);
  250. /// <summary>
  251. /// Adds a new entry to the dictionary.
  252. /// </summary>
  253. /// <param name="key">Key of the entry to add.</param>
  254. /// <param name="value">Value of the entry to add.</param>
  255. protected internal abstract void AddEntry(object key, object value);
  256. /// <summary>
  257. /// Removes the specified entry from the dictionary.
  258. /// </summary>
  259. /// <param name="key">Key of the entry to remove.</param>
  260. protected internal abstract void RemoveEntry(object key);
  261. /// <summary>
  262. /// Creates a new empty key object of a valid type that can be used in the dictionary.
  263. /// </summary>
  264. /// <returns>New empty key object.</returns>
  265. protected internal abstract object CreateKey();
  266. /// <summary>
  267. /// Creates a new empty value object of a valid type that can be used in the dictionary.
  268. /// </summary>
  269. /// <returns>New empty value object.</returns>
  270. protected internal abstract object CreateValue();
  271. /// <summary>
  272. /// Checks does the element with the specified key exist in the dictionary.
  273. /// </summary>
  274. /// <param name="key">Key of the element to check for existence.</param>
  275. /// <returns>True if the key exists in the dictionary, false otherwise.</returns>
  276. protected internal abstract bool Contains(object key);
  277. /// <summary>
  278. /// Hides or shows the dictionary rows.
  279. /// </summary>
  280. /// <param name="expanded">True if the rows should be displayed, false otherwise.</param>
  281. private void ToggleFoldout(bool expanded)
  282. {
  283. isExpanded = expanded;
  284. if (guiChildLayout != null)
  285. guiChildLayout.Active = isExpanded && (rows.Count > 0 || IsEditInProgress());
  286. }
  287. /// <summary>
  288. /// Triggered when the user clicks on the create button on the title bar. Creates a brand new dictionary with zero
  289. /// elements in the place of the current dictionary.
  290. /// </summary>
  291. protected abstract void OnCreateButtonClicked();
  292. /// <summary>
  293. /// Triggered when the user clicks on the add button on the title bar. Adds a new empty element to the dictionary.
  294. /// </summary>
  295. protected virtual void OnAddButtonClicked()
  296. {
  297. if (IsEditInProgress())
  298. {
  299. DialogBox.Open(
  300. new LocEdString("Edit in progress."),
  301. new LocEdString("You are editing the entry with key \"" + editKey + "\". You cannot add a row " +
  302. "before applying or discarding those changes. Do you wish to apply those changes first?"),
  303. DialogBox.Type.YesNoCancel,
  304. x =>
  305. {
  306. switch (x)
  307. {
  308. case DialogBox.ResultType.Yes:
  309. if (ApplyChanges())
  310. StartAdd();
  311. break;
  312. case DialogBox.ResultType.No:
  313. DiscardChanges();
  314. StartAdd();
  315. break;
  316. }
  317. });
  318. }
  319. else
  320. {
  321. if (!isExpanded)
  322. ToggleFoldout(true);
  323. StartAdd();
  324. }
  325. }
  326. /// <summary>
  327. /// Triggered when the user clicks on the clear button on the title bar. Deletes the current dictionary object.
  328. /// </summary>
  329. protected abstract void OnClearButtonClicked();
  330. /// <summary>
  331. /// Triggered when the user clicks on the delete button next to a dictionary entry. Deletes an element in the
  332. /// dictionary.
  333. /// </summary>
  334. /// <param name="rowIdx">Sequential row index of the entry that was clicked.</param>
  335. protected internal virtual void OnDeleteButtonClicked(int rowIdx)
  336. {
  337. if (IsEditInProgress())
  338. DiscardChanges();
  339. else
  340. RemoveEntry(GetKey(rowIdx));
  341. }
  342. /// <summary>
  343. /// Triggered when the user clicks on the clone button next to a dictionary entry. Clones an element and
  344. /// adds the clone to the dictionary.
  345. /// </summary>
  346. /// <param name="rowIdx">Sequential row index of the entry that was clicked.</param>
  347. protected internal virtual void OnCloneButtonClicked(int rowIdx)
  348. {
  349. if (IsEditInProgress())
  350. {
  351. DialogBox.Open(
  352. new LocEdString("Edit in progress."),
  353. new LocEdString("You are editing the entry with key \"" + editKey + "\". You cannot clone a row " +
  354. "before applying or discarding those changes. Do you wish to apply those changes first?"),
  355. DialogBox.Type.YesNoCancel,
  356. x =>
  357. {
  358. switch (x)
  359. {
  360. case DialogBox.ResultType.Yes:
  361. if (ApplyChanges())
  362. StartClone(rowIdx);
  363. break;
  364. case DialogBox.ResultType.No:
  365. DiscardChanges();
  366. StartClone(rowIdx);
  367. break;
  368. }
  369. });
  370. }
  371. else
  372. StartClone(rowIdx);
  373. }
  374. /// <summary>
  375. /// Triggered when user clicks the edit or apply (depending on state) button next to the dictionary entry. Starts
  376. /// edit mode for the element, if not already in edit mode. Applies edit mode changes if already in edit mode.
  377. /// </summary>
  378. /// <param name="rowIdx">Sequential row index of the entry that was clicked.</param>
  379. protected internal virtual void OnEditButtonClicked(int rowIdx)
  380. {
  381. if (editRowIdx == rowIdx)
  382. ApplyChanges();
  383. else
  384. {
  385. if (IsEditInProgress())
  386. {
  387. DialogBox.Open(
  388. new LocEdString("Edit in progress."),
  389. new LocEdString("You are already editing the entry with key \"" + editKey + "\". You cannot edit " +
  390. "another row before applying or discarding those changes. Do you wish to apply those changes first?"),
  391. DialogBox.Type.YesNoCancel,
  392. x =>
  393. {
  394. switch (x)
  395. {
  396. case DialogBox.ResultType.Yes:
  397. if (ApplyChanges())
  398. StartEdit(rowIdx);
  399. break;
  400. case DialogBox.ResultType.No:
  401. DiscardChanges();
  402. StartEdit(rowIdx);
  403. break;
  404. }
  405. });
  406. }
  407. else
  408. StartEdit(rowIdx);
  409. }
  410. }
  411. /// <summary>
  412. /// Starts an edit operation on a row with the specified key. Allows the user to change the key of the specified row.
  413. /// Caller must ensure no edit operation is already in progress.
  414. /// </summary>
  415. /// <param name="rowIdx">Sequential row index of the entry to edit.</param>
  416. private void StartEdit(int rowIdx)
  417. {
  418. object key = GetKey(rowIdx);
  419. editKey = SerializableUtility.Clone(key);
  420. editValue = SerializableUtility.Clone(GetValue(key));
  421. editOriginalKey = key;
  422. editRowIdx = rowIdx;
  423. rows[rowIdx].EditMode = true;
  424. guiChildLayout.Active = rows.Count > 0 && isExpanded;
  425. }
  426. /// <summary>
  427. /// Starts an add operation. Adds a new key/value pair and allows the user to set them up in a temporary row
  428. /// before inserting them into the dictionary. Caller must ensure no edit operation is already in progress.
  429. /// </summary>
  430. private void StartAdd()
  431. {
  432. editKey = CreateKey();
  433. editValue = CreateValue();
  434. editOriginalKey = null;
  435. editRowIdx = rows.Count;
  436. editRow.Enabled = true;
  437. editRow.EditMode = true;
  438. ToggleFoldout(isExpanded);
  439. }
  440. /// <summary>
  441. /// Starts a clone operation. Adds a new key/value pair by cloning an existing one. Allows the user to modify the
  442. /// new pair in a temporary row before inserting them into the dictionary. Caller must ensure no edit operation is
  443. /// already in progress.
  444. /// </summary>
  445. /// <param name="rowIdx">Sequential row index of the entry to clone.</param>
  446. private void StartClone(int rowIdx)
  447. {
  448. object key = GetKey(rowIdx);
  449. editKey = SerializableUtility.Clone(key);
  450. editValue = SerializableUtility.Clone(GetValue(key));
  451. editOriginalKey = null;
  452. editRowIdx = rows.Count;
  453. editRow.Enabled = true;
  454. editRow.EditMode = true;
  455. ToggleFoldout(isExpanded);
  456. }
  457. /// <summary>
  458. /// Attempts to apply any changes made to the currently edited row.
  459. /// </summary>
  460. /// <returns>True if the changes were successfully applied, false if the new key already exists in the dictionary.
  461. /// </returns>
  462. private bool ApplyChanges()
  463. {
  464. if (!IsEditInProgress())
  465. return true;
  466. if (Contains(editKey) && (editOriginalKey == null || !editOriginalKey.Equals(editKey)))
  467. {
  468. DialogBox.Open(
  469. new LocEdString("Key already exists."),
  470. new LocEdString("Cannot add a key \"" + editKey + "\" to dictionary. Key already exists"),
  471. DialogBox.Type.OK);
  472. return false;
  473. }
  474. else
  475. {
  476. if (IsTemporaryRow(editRowIdx))
  477. {
  478. editRow.EditMode = false;
  479. editRow.Enabled = false;
  480. }
  481. else
  482. {
  483. rows[editRowIdx].EditMode = false;
  484. }
  485. if (editOriginalKey != null) // Editing
  486. EditEntry(editOriginalKey, editKey, editValue);
  487. else // Adding/Cloning
  488. AddEntry(editKey, editValue);
  489. editKey = CreateKey();
  490. editValue = CreateValue();
  491. editOriginalKey = null;
  492. editRowIdx = -1;
  493. ToggleFoldout(isExpanded);
  494. return true;
  495. }
  496. }
  497. /// <summary>
  498. /// Cancels any changes made on the currently edited row.
  499. /// </summary>
  500. private void DiscardChanges()
  501. {
  502. if (IsEditInProgress())
  503. {
  504. editKey = CreateKey();
  505. editValue = CreateValue();
  506. editOriginalKey = null;
  507. editRow.Enabled = false;
  508. editRowIdx = -1;
  509. ToggleFoldout(isExpanded);
  510. }
  511. }
  512. }
  513. /// <summary>
  514. /// Creates GUI elements that allow viewing and manipulation of a <see cref="Dictionary{TKey,TValue}"/>. When constructing the
  515. /// object user can provide a custom type that manages GUI for individual dictionary elements.
  516. /// </summary>
  517. /// <typeparam name="Key">Type of key used by the dictionary.</typeparam>
  518. /// <typeparam name="Value">Type of value stored in the dictionary.</typeparam>
  519. public class GUIDictionaryField<Key, Value> : GUIDictionaryFieldBase
  520. {
  521. public delegate int SortDictionaryDelegate(Key a, Key b);
  522. /// <summary>
  523. /// Triggered when the reference array has been changed. This does not include changes that only happen to its
  524. /// internal elements.
  525. /// </summary>
  526. public Action<Dictionary<Key, Value>> OnChanged;
  527. /// <summary>
  528. /// Triggered when an element in the list has been changed.
  529. /// </summary>
  530. public Action<Key> OnValueChanged;
  531. /// <summary>
  532. /// Optional method that will be used for sorting the elements in the dictionary.
  533. /// </summary>
  534. public SortDictionaryDelegate SortMethod;
  535. /// <summary>
  536. /// Array object whose contents are displayed.
  537. /// </summary>
  538. public Dictionary<Key, Value> Dictionary { get { return dictionary; } }
  539. protected Dictionary<Key, Value> dictionary;
  540. private List<Key> orderedKeys = new List<Key>();
  541. /// <summary>
  542. /// Constructs a new empty dictionary GUI.
  543. /// </summary>
  544. public GUIDictionaryField()
  545. { }
  546. /// <summary>
  547. /// Builds the dictionary GUI elements. Must be called at least once in order for the contents to be populated.
  548. /// </summary>
  549. /// <typeparam name="RowType">Type of rows that are used to handle GUI for individual dictionary elements.</typeparam>
  550. /// <param name="title">Label to display on the list GUI title.</param>
  551. /// <param name="dictionary">Object containing the data. Can be null.</param>
  552. /// <param name="layout">Layout to which to append the list GUI elements to.</param>
  553. /// <param name="depth">Determines at which depth to render the background. Useful when you have multiple
  554. /// nested containers whose backgrounds are overlaping. Also determines background style,
  555. /// depths divisible by two will use an alternate style.</param>
  556. public void BuildGUI<RowType>(LocString title, Dictionary<Key, Value> dictionary,
  557. GUILayout layout, int depth = 0)
  558. where RowType : GUIDictionaryFieldRow, new()
  559. {
  560. this.dictionary = dictionary;
  561. UpdateKeys();
  562. if (dictionary != null)
  563. base.BuildGUI<RowType>(title, false, dictionary.Count, layout, depth);
  564. else
  565. base.BuildGUI<RowType>(title, true, 0, layout, depth);
  566. }
  567. /// <summary>
  568. /// Updates the ordered set of keys used for mapping sequential indexes to keys. Should be called whenever a
  569. /// dictionary key changes.
  570. /// </summary>
  571. private void UpdateKeys()
  572. {
  573. orderedKeys.Clear();
  574. if (dictionary != null)
  575. {
  576. foreach (var KVP in dictionary)
  577. orderedKeys.Add(KVP.Key);
  578. if (SortMethod != null)
  579. orderedKeys.Sort((x,y) => SortMethod(x, y));
  580. else
  581. orderedKeys.Sort();
  582. }
  583. }
  584. /// <inheritdoc/>
  585. protected internal override object GetKey(int rowIdx)
  586. {
  587. return orderedKeys[rowIdx];
  588. }
  589. /// <inheritdoc/>
  590. protected internal override object GetValue(object key)
  591. {
  592. return dictionary[(Key)key];
  593. }
  594. /// <inheritdoc/>
  595. protected internal override void SetValue(object key, object value)
  596. {
  597. dictionary[(Key)key] = (Value)value;
  598. if (OnValueChanged != null)
  599. OnValueChanged((Key)key);
  600. }
  601. /// <inheritdoc/>
  602. protected internal override bool Contains(object key)
  603. {
  604. return dictionary.ContainsKey((Key)key); ;
  605. }
  606. /// <inheritdoc/>
  607. protected internal override void EditEntry(object oldKey, object newKey, object value)
  608. {
  609. dictionary.Remove((Key)oldKey);
  610. dictionary[(Key)newKey] = (Value)value;
  611. if (OnChanged != null)
  612. OnChanged(dictionary);
  613. UpdateKeys();
  614. }
  615. /// <inheritdoc/>
  616. protected internal override void AddEntry(object key, object value)
  617. {
  618. dictionary[(Key)key] = (Value)value;
  619. if (OnChanged != null)
  620. OnChanged(dictionary);
  621. UpdateKeys();
  622. }
  623. /// <inheritdoc/>
  624. protected internal override void RemoveEntry(object key)
  625. {
  626. dictionary.Remove((Key) key);
  627. if (OnChanged != null)
  628. OnChanged(dictionary);
  629. UpdateKeys();
  630. }
  631. /// <inheritdoc/>
  632. protected internal override object CreateKey()
  633. {
  634. return SerializableUtility.Create<Key>();
  635. }
  636. /// <inheritdoc/>
  637. protected internal override object CreateValue()
  638. {
  639. return SerializableUtility.Create<Value>();
  640. }
  641. /// <inheritdoc/>
  642. protected override void OnCreateButtonClicked()
  643. {
  644. dictionary = new Dictionary<Key, Value>();
  645. if (OnChanged != null)
  646. OnChanged(dictionary);
  647. UpdateKeys();
  648. }
  649. /// <inheritdoc/>
  650. protected override void OnClearButtonClicked()
  651. {
  652. dictionary = null;
  653. if (OnChanged != null)
  654. OnChanged(dictionary);
  655. UpdateKeys();
  656. }
  657. }
  658. /// <summary>
  659. /// Contains GUI elements for a single entry in a dictionary.
  660. /// </summary>
  661. public abstract class GUIDictionaryFieldRow
  662. {
  663. private GUILayoutY rowLayout;
  664. private GUILayoutX keyRowLayout;
  665. private GUILayoutY keyLayout;
  666. private GUILayoutY valueLayout;
  667. private GUILayoutX titleLayout;
  668. private GUIButton deleteBtn;
  669. private GUIButton editBtn;
  670. private bool localTitleLayout;
  671. private bool enabled = true;
  672. private GUIDictionaryFieldBase parent;
  673. protected int rowIdx;
  674. protected int depth;
  675. /// <summary>
  676. /// Determines is the row currently being displayed.
  677. /// </summary>
  678. internal bool Enabled
  679. {
  680. get { return enabled; }
  681. set { enabled = value; rowLayout.Active = value; }
  682. }
  683. /// <summary>
  684. /// Enables or disables the row's edit mode. This determines what type of buttons are shown on the row title bar.
  685. /// </summary>
  686. internal bool EditMode
  687. {
  688. set
  689. {
  690. if (value)
  691. {
  692. GUIContent cancelIcon = new GUIContent(EditorBuiltin.GetInspectorWindowIcon(InspectorWindowIcon.Cancel));
  693. GUIContent applyIcon = new GUIContent(EditorBuiltin.GetInspectorWindowIcon(InspectorWindowIcon.Apply));
  694. deleteBtn.SetContent(cancelIcon);
  695. editBtn.SetContent(applyIcon);
  696. }
  697. else
  698. {
  699. GUIContent deleteIcon = new GUIContent(EditorBuiltin.GetInspectorWindowIcon(InspectorWindowIcon.Delete));
  700. GUIContent editIcon = new GUIContent(EditorBuiltin.GetInspectorWindowIcon(InspectorWindowIcon.Edit));
  701. deleteBtn.SetContent(deleteIcon);
  702. editBtn.SetContent(editIcon);
  703. }
  704. }
  705. }
  706. /// <summary>
  707. /// Constructs a new dictionary row object.
  708. /// </summary>
  709. protected GUIDictionaryFieldRow()
  710. {
  711. }
  712. /// <summary>
  713. /// (Re)creates all row GUI elements.
  714. /// </summary>
  715. /// <param name="parent">Parent array GUI object that the entry is contained in.</param>
  716. /// <param name="parentLayout">Parent layout that row GUI elements will be added to.</param>
  717. /// <param name="rowIdx">Sequential index of the row.</param>
  718. /// <param name="depth">Determines the depth at which the element is rendered.</param>
  719. internal void BuildGUI(GUIDictionaryFieldBase parent, GUILayout parentLayout, int rowIdx, int depth)
  720. {
  721. this.parent = parent;
  722. this.rowIdx = rowIdx;
  723. this.depth = depth;
  724. if (rowLayout == null)
  725. rowLayout = parentLayout.AddLayoutY();
  726. if (keyRowLayout == null)
  727. keyRowLayout = rowLayout.AddLayoutX();
  728. if (keyLayout == null)
  729. keyLayout = keyRowLayout.AddLayoutY();
  730. if (valueLayout == null)
  731. valueLayout = rowLayout.AddLayoutY();
  732. GUILayoutX externalTitleLayout = CreateKeyGUI(keyLayout);
  733. CreateValueGUI(valueLayout);
  734. if (localTitleLayout || (titleLayout != null && titleLayout == externalTitleLayout))
  735. return;
  736. if (externalTitleLayout != null)
  737. {
  738. localTitleLayout = false;
  739. titleLayout = externalTitleLayout;
  740. }
  741. else
  742. {
  743. GUILayoutY buttonCenter = keyRowLayout.AddLayoutY();
  744. buttonCenter.AddFlexibleSpace();
  745. titleLayout = buttonCenter.AddLayoutX();
  746. buttonCenter.AddFlexibleSpace();
  747. localTitleLayout = true;
  748. }
  749. GUIContent cloneIcon = new GUIContent(EditorBuiltin.GetInspectorWindowIcon(InspectorWindowIcon.Clone));
  750. GUIContent deleteIcon = new GUIContent(EditorBuiltin.GetInspectorWindowIcon(InspectorWindowIcon.Delete));
  751. GUIContent editIcon = new GUIContent(EditorBuiltin.GetInspectorWindowIcon(InspectorWindowIcon.Edit));
  752. GUIButton cloneBtn = new GUIButton(cloneIcon, GUIOption.FixedWidth(30));
  753. deleteBtn = new GUIButton(deleteIcon, GUIOption.FixedWidth(30));
  754. editBtn = new GUIButton(editIcon, GUIOption.FixedWidth(30));
  755. cloneBtn.OnClick += () => parent.OnCloneButtonClicked(rowIdx);
  756. deleteBtn.OnClick += () => parent.OnDeleteButtonClicked(rowIdx);
  757. editBtn.OnClick += () => parent.OnEditButtonClicked(rowIdx);
  758. titleLayout.AddElement(cloneBtn);
  759. titleLayout.AddElement(deleteBtn);
  760. titleLayout.AddSpace(10);
  761. titleLayout.AddElement(editBtn);
  762. }
  763. /// <summary>
  764. /// Creates GUI elements specific to type in the key portion of a dictionary entry.
  765. /// </summary>
  766. /// <param name="layout">Layout to insert the row GUI elements to.</param>
  767. /// <returns>An optional title bar layout that the standard dictionary buttons will be appended to.</returns>
  768. protected abstract GUILayoutX CreateKeyGUI(GUILayoutY layout);
  769. /// <summary>
  770. /// Creates GUI elements specific to type in the key portion of a dictionary entry.
  771. /// </summary>
  772. /// <param name="layout">Layout to insert the row GUI elements to.</param>
  773. protected abstract void CreateValueGUI(GUILayoutY layout);
  774. /// <summary>
  775. /// Refreshes the GUI for the dictionary row and checks if anything was modified.
  776. /// </summary>
  777. /// <returns>Determines should the field's GUI elements be updated due to modifications.</returns>
  778. internal protected virtual bool Refresh()
  779. {
  780. return false;
  781. }
  782. /// <summary>
  783. /// Gets the key contained in this dictionary's row.
  784. /// </summary>
  785. /// <typeparam name="T">Type of the key. Must match the dictionary's element type.</typeparam>
  786. /// <returns>Key in this dictionary's row.</returns>
  787. protected T GetKey<T>()
  788. {
  789. return (T)parent.GetKeyInternal(rowIdx);
  790. }
  791. /// <summary>
  792. /// Sets the key for in this dictionary's row.
  793. /// </summary>
  794. /// <typeparam name="T">Type of the key. Must match the dictionary's element type.</typeparam>
  795. /// <param name="key">Key to assign to this row.</param>
  796. protected void SetKey<T>(T key)
  797. {
  798. parent.SetKey(rowIdx, key);
  799. }
  800. /// <summary>
  801. /// Gets the value contained in this dictionary's row.
  802. /// </summary>
  803. /// <typeparam name="T">Type of the value. Must match the dictionary's element type.</typeparam>
  804. /// <returns>Value in this dictionary's row.</returns>
  805. protected T GetValue<T>()
  806. {
  807. return (T)parent.GetValueInternal(rowIdx);
  808. }
  809. /// <summary>
  810. /// Sets the value contained in this dictionary's row.
  811. /// </summary>
  812. /// <typeparam name="T">Type of the value. Must match the dictionary's element type.</typeparam>
  813. /// <param name="value">Value to set.</param>
  814. protected void SetValue<T>(T value)
  815. {
  816. parent.SetValueInternal(rowIdx, value);
  817. }
  818. /// <summary>
  819. /// Destroys all row GUI elements.
  820. /// </summary>
  821. public void Destroy()
  822. {
  823. if (rowLayout != null)
  824. {
  825. rowLayout.Destroy();
  826. rowLayout = null;
  827. }
  828. keyRowLayout = null;
  829. keyLayout = null;
  830. valueLayout = null;
  831. titleLayout = null;
  832. deleteBtn = null;
  833. editBtn = null;
  834. localTitleLayout = false;
  835. }
  836. }
  837. }