GUIDictionaryField.cs 35 KB

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