GUIDictionaryField.cs 36 KB

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