2
0

GUIDictionaryField.cs 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. using System;
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using BansheeEngine;
  7. namespace BansheeEditor
  8. {
  9. /** @addtogroup GUI-Editor
  10. * @{
  11. */
  12. /// <summary>
  13. /// Base class for objects that display GUI for a modifyable dictionary of elements. Elements can be added, modified or
  14. /// removed.
  15. /// </summary>
  16. public abstract class GUIDictionaryFieldBase
  17. {
  18. private const int IndentAmount = 5;
  19. protected Dictionary<int, GUIDictionaryFieldRow> rows = new Dictionary<int, GUIDictionaryFieldRow>();
  20. protected GUIDictionaryFieldRow editRow;
  21. protected GUILayoutY guiLayout;
  22. protected GUILayoutX guiChildLayout;
  23. protected GUILayoutX guiTitleLayout;
  24. protected GUILayoutX guiInternalTitleLayout;
  25. protected GUILayoutY guiContentLayout;
  26. protected bool isExpanded;
  27. protected int depth;
  28. protected LocString title;
  29. private int editRowIdx = -1;
  30. private object editKey;
  31. private object editValue;
  32. private object editOriginalKey;
  33. private State state;
  34. private bool isModified;
  35. /// <summary>
  36. /// Expands or collapses the entries of the dictionary.
  37. /// </summary>
  38. public bool IsExpanded
  39. {
  40. get { return isExpanded; }
  41. set
  42. {
  43. if (isExpanded != value)
  44. ToggleFoldout(value);
  45. }
  46. }
  47. /// <summary>
  48. /// Event that triggers when the list foldout is expanded or collapsed (rows are shown or hidden).
  49. /// </summary>
  50. public Action<bool> OnExpand;
  51. /// <summary>
  52. /// Constructs a new GUI dictionary.
  53. /// </summary>
  54. /// <param name="title">Label to display on the dictionary GUI title.</param>
  55. /// <param name="layout">Layout to which to append the list GUI elements to.</param>
  56. /// <param name="depth">Determines at which depth to render the background. Useful when you have multiple
  57. /// nested containers whose backgrounds are overlaping. Also determines background style,
  58. /// depths divisible by two will use an alternate style.</param>
  59. protected GUIDictionaryFieldBase(LocString title, GUILayout layout, int depth = 0)
  60. {
  61. this.title = title;
  62. this.depth = depth;
  63. guiLayout = layout.AddLayoutY();
  64. guiTitleLayout = guiLayout.AddLayoutX();
  65. }
  66. /// <summary>
  67. /// Completely rebuilds the dictionary GUI elements.
  68. /// </summary>
  69. public void BuildGUI()
  70. {
  71. editKey = CreateKey();
  72. editValue = CreateValue();
  73. UpdateHeaderGUI();
  74. foreach (var KVP in rows)
  75. KVP.Value.Destroy();
  76. rows.Clear();
  77. if (editRow != null)
  78. {
  79. editRow.Destroy();
  80. editRow = null;
  81. }
  82. if (!IsNull())
  83. {
  84. // Hidden dependency: BuildGUI must be called after all elements are
  85. // in the dictionary so we do it in two steps
  86. int numRows = GetNumRows();
  87. for (int i = 0; i < numRows; i++)
  88. {
  89. GUIDictionaryFieldRow newRow = CreateRow();
  90. rows.Add(i, newRow);
  91. }
  92. editRow = CreateRow();
  93. editRow.Initialize(this, guiContentLayout, numRows, depth + 1);
  94. editRow.Enabled = false;
  95. for (int i = 0; i < numRows; i++)
  96. rows[i].Initialize(this, guiContentLayout, i, depth + 1);
  97. }
  98. }
  99. /// <summary>
  100. /// Rebuilds the GUI dictionary header if needed.
  101. /// </summary>
  102. protected void UpdateHeaderGUI()
  103. {
  104. Action BuildEmptyGUI = () =>
  105. {
  106. guiInternalTitleLayout = guiTitleLayout.InsertLayoutX(0);
  107. guiInternalTitleLayout.AddElement(new GUILabel(title));
  108. guiInternalTitleLayout.AddElement(new GUILabel("Empty", GUIOption.FixedWidth(100)));
  109. GUIContent createIcon = new GUIContent(EditorBuiltin.GetInspectorWindowIcon(InspectorWindowIcon.Create),
  110. new LocEdString("Create"));
  111. GUIButton createBtn = new GUIButton(createIcon, GUIOption.FixedWidth(30));
  112. createBtn.OnClick += OnCreateButtonClicked;
  113. guiInternalTitleLayout.AddElement(createBtn);
  114. };
  115. Action BuildFilledGUI = () =>
  116. {
  117. guiInternalTitleLayout = guiTitleLayout.InsertLayoutX(0);
  118. GUIToggle guiFoldout = new GUIToggle(title, EditorStyles.Foldout);
  119. guiFoldout.Value = isExpanded;
  120. guiFoldout.OnToggled += ToggleFoldout;
  121. GUIContent clearIcon = new GUIContent(EditorBuiltin.GetInspectorWindowIcon(InspectorWindowIcon.Clear),
  122. new LocEdString("Clear"));
  123. GUIButton guiClearBtn = new GUIButton(clearIcon, GUIOption.FixedWidth(30));
  124. guiClearBtn.OnClick += OnClearButtonClicked;
  125. GUIContent addIcon = new GUIContent(EditorBuiltin.GetInspectorWindowIcon(InspectorWindowIcon.Add),
  126. new LocEdString("Add"));
  127. GUIButton guiAddBtn = new GUIButton(addIcon, GUIOption.FixedWidth(30));
  128. guiAddBtn.OnClick += OnAddButtonClicked;
  129. guiInternalTitleLayout.AddElement(guiFoldout);
  130. guiInternalTitleLayout.AddElement(guiAddBtn);
  131. guiInternalTitleLayout.AddElement(guiClearBtn);
  132. guiChildLayout = guiLayout.AddLayoutX();
  133. guiChildLayout.AddSpace(IndentAmount);
  134. GUIPanel guiContentPanel = guiChildLayout.AddPanel();
  135. GUILayoutX guiIndentLayoutX = guiContentPanel.AddLayoutX();
  136. guiIndentLayoutX.AddSpace(IndentAmount);
  137. GUILayoutY guiIndentLayoutY = guiIndentLayoutX.AddLayoutY();
  138. guiIndentLayoutY.AddSpace(IndentAmount);
  139. guiContentLayout = guiIndentLayoutY.AddLayoutY();
  140. guiIndentLayoutY.AddSpace(IndentAmount);
  141. guiIndentLayoutX.AddSpace(IndentAmount);
  142. guiChildLayout.AddSpace(IndentAmount);
  143. short backgroundDepth = (short)(Inspector.START_BACKGROUND_DEPTH - depth - 1);
  144. string bgPanelStyle = depth % 2 == 0
  145. ? EditorStyles.InspectorContentBgAlternate
  146. : EditorStyles.InspectorContentBg;
  147. GUIPanel backgroundPanel = guiContentPanel.AddPanel(backgroundDepth);
  148. GUITexture inspectorContentBg = new GUITexture(null, bgPanelStyle);
  149. backgroundPanel.AddElement(inspectorContentBg);
  150. ToggleFoldout(isExpanded);
  151. };
  152. if (state == State.None)
  153. {
  154. if (!IsNull())
  155. {
  156. BuildFilledGUI();
  157. state = State.Filled;
  158. }
  159. else
  160. {
  161. BuildEmptyGUI();
  162. state = State.Empty;
  163. }
  164. }
  165. else if (state == State.Empty)
  166. {
  167. if (!IsNull())
  168. {
  169. guiInternalTitleLayout.Destroy();
  170. BuildFilledGUI();
  171. state = State.Filled;
  172. }
  173. }
  174. else if (state == State.Filled)
  175. {
  176. if (IsNull())
  177. {
  178. guiInternalTitleLayout.Destroy();
  179. guiChildLayout.Destroy();
  180. BuildEmptyGUI();
  181. state = State.Empty;
  182. }
  183. }
  184. }
  185. /// <summary>
  186. /// Destroys all rows and clears the row list.
  187. /// </summary>
  188. private void ClearRows()
  189. {
  190. foreach (var KVP in rows)
  191. KVP.Value.Destroy();
  192. editRow.Destroy();
  193. rows.Clear();
  194. }
  195. /// <summary>
  196. /// Returns the layout that is used for positioning the elements in the title bar.
  197. /// </summary>
  198. /// <returns>Horizontal layout for positioning the title bar elements.</returns>
  199. public GUILayoutX GetTitleLayout()
  200. {
  201. return guiTitleLayout;
  202. }
  203. /// <summary>
  204. /// Refreshes contents of all dictionary rows and checks if anything was modified.
  205. /// </summary>
  206. /// <returns>State representing was anything modified between two last calls to <see cref="Refresh"/>.</returns>
  207. public virtual InspectableState Refresh()
  208. {
  209. InspectableState state = InspectableState.NotModified;
  210. for (int i = 0; i < rows.Count; i++)
  211. state |= rows[i].Refresh();
  212. if (editRow != null && editRow.Enabled)
  213. state |= editRow.Refresh();
  214. if (isModified)
  215. {
  216. state |= InspectableState.Modified;
  217. isModified = false;
  218. }
  219. return state;
  220. }
  221. /// <summary>
  222. /// Destroys the GUI elements.
  223. /// </summary>
  224. public void Destroy()
  225. {
  226. if (guiLayout != null)
  227. {
  228. guiLayout.Destroy();
  229. guiLayout = null;
  230. }
  231. guiLayout = null;
  232. guiTitleLayout = null;
  233. guiChildLayout = null;
  234. for (int i = 0; i < rows.Count; i++)
  235. rows[i].Destroy();
  236. rows.Clear();
  237. if (editRow != null)
  238. editRow.Destroy();
  239. editRow = null;
  240. }
  241. /// <summary>
  242. /// Checks is the specified row index the temporary edit row.
  243. /// </summary>
  244. /// <param name="rowIdx">Sequential index of the row to check.</param>
  245. /// <returns>True if the index is of an edit row.</returns>
  246. private bool IsTemporaryRow(int rowIdx)
  247. {
  248. return rowIdx == rows.Count;
  249. }
  250. /// <summary>
  251. /// Checks is any row being currently edited.
  252. /// </summary>
  253. /// <returns>True if a row is being edited, false otherwise.</returns>
  254. private bool IsEditInProgress()
  255. {
  256. return editRowIdx != -1;
  257. }
  258. /// <summary>
  259. /// Returns the number of rows in the dictionary.
  260. /// </summary>
  261. /// <returns>Number of rows in the dictionary.</returns>
  262. protected abstract int GetNumRows();
  263. /// <summary>
  264. /// Checks is the dictionary instance not assigned.
  265. /// </summary>
  266. /// <returns>True if there is not a dictionary instance.</returns>
  267. protected abstract bool IsNull();
  268. /// <summary>
  269. /// Gets a value of an element at the specified index in the list. Also handles temporary edit fields.
  270. /// </summary>
  271. /// <param name="rowIdx">Sequential index of the row to set the value for.</param>
  272. /// <returns>Value of the list element at the specified key.</returns>
  273. protected internal virtual object GetValueInternal(int rowIdx)
  274. {
  275. if (rowIdx == editRowIdx || IsTemporaryRow(rowIdx))
  276. return editValue;
  277. else
  278. return GetValue(GetKey(rowIdx));
  279. }
  280. /// <summary>
  281. /// Sets a value of an element at the specified index in the list. Also handles temporary edit fields.
  282. /// </summary>
  283. /// <param name="rowIdx">Sequential index of the row to set the value for.</param>
  284. /// <param name="value">Value to assign to the element. Caller must ensure it is of valid type.</param>
  285. protected internal virtual void SetValueInternal(int rowIdx, object value)
  286. {
  287. if (rowIdx == editRowIdx || IsTemporaryRow(rowIdx))
  288. editValue = value;
  289. else
  290. SetValue(GetKey(rowIdx), value);
  291. }
  292. /// <summary>
  293. /// Changes the value of the key of the specified row.
  294. /// </summary>
  295. /// <param name="rowIdx">Sequential index of the row to set the key for.</param>
  296. /// <param name="key">Key to assign to the specified row.</param>
  297. protected internal void SetKey(int rowIdx, object key)
  298. {
  299. if (editRowIdx != rowIdx)
  300. {
  301. Debug.LogError("Cannot change a dictionary row that is not in edit state.");
  302. return;
  303. }
  304. editKey = key;
  305. }
  306. /// <summary>
  307. /// Gets a key for a row at the specified index. Handles the special case for the currently edited row.
  308. /// </summary>
  309. /// <param name="rowIdx">Sequential index of the row for which to retrieve the key.</param>
  310. /// <returns>Key for a row at the specified index.</returns>
  311. protected internal object GetKeyInternal(int rowIdx)
  312. {
  313. if (editRowIdx == rowIdx || IsTemporaryRow(rowIdx))
  314. return editKey;
  315. return GetKey(rowIdx);
  316. }
  317. /// <summary>
  318. /// Creates a new dictionary row GUI.
  319. /// </summary>
  320. /// <returns>Object containing the dictionary row GUI.</returns>
  321. protected abstract GUIDictionaryFieldRow CreateRow();
  322. /// <summary>
  323. /// Gets a key for a row at the specified index.
  324. /// </summary>
  325. /// <param name="rowIdx">Sequential index of the row for which to retrieve the key.</param>
  326. /// <returns>Key for a row at the specified index.</returns>
  327. protected internal abstract object GetKey(int rowIdx);
  328. /// <summary>
  329. /// Gets a value of an element at the specified index in the list.
  330. /// </summary>
  331. /// <param name="key">Key of the element whose value to retrieve.</param>
  332. /// <returns>Value of the dictionary entry for the specified key.</returns>
  333. protected internal abstract object GetValue(object key);
  334. /// <summary>
  335. /// Sets a value of an element at the specified index in the list.
  336. /// </summary>
  337. /// <param name="key">Key of the element whose value to set.</param>
  338. /// <param name="value">Value to assign to the element. Caller must ensure it is of valid type.</param>
  339. protected internal abstract void SetValue(object key, object value);
  340. /// <summary>
  341. /// Updates both key and value of an existing entry.
  342. /// </summary>
  343. /// <param name="oldKey">Original key of the entry.</param>
  344. /// <param name="newKey">New key of the entry.</param>
  345. /// <param name="value">New value of the entry.</param>
  346. protected internal abstract void EditEntry(object oldKey, object newKey, object value);
  347. /// <summary>
  348. /// Adds a new entry to the dictionary.
  349. /// </summary>
  350. /// <param name="key">Key of the entry to add.</param>
  351. /// <param name="value">Value of the entry to add.</param>
  352. protected internal abstract void AddEntry(object key, object value);
  353. /// <summary>
  354. /// Removes the specified entry from the dictionary.
  355. /// </summary>
  356. /// <param name="key">Key of the entry to remove.</param>
  357. protected internal abstract void RemoveEntry(object key);
  358. /// <summary>
  359. /// Creates a new empty key object of a valid type that can be used in the dictionary.
  360. /// </summary>
  361. /// <returns>New empty key object.</returns>
  362. protected internal abstract object CreateKey();
  363. /// <summary>
  364. /// Creates a new empty value object of a valid type that can be used in the dictionary.
  365. /// </summary>
  366. /// <returns>New empty value object.</returns>
  367. protected internal abstract object CreateValue();
  368. /// <summary>
  369. /// Checks does the element with the specified key exist in the dictionary.
  370. /// </summary>
  371. /// <param name="key">Key of the element to check for existence.</param>
  372. /// <returns>True if the key exists in the dictionary, false otherwise.</returns>
  373. protected internal abstract bool Contains(object key);
  374. /// <summary>
  375. /// Clones the specified dictionary element.
  376. /// </summary>
  377. /// <param name="index">Sequential index of the element in the dictionary to clone.</param>
  378. protected internal abstract KeyValuePair<object, object> CloneElement(int index);
  379. /// <summary>
  380. /// Creates a brand new dictionary with zero elements in the place of the current dictionary.
  381. /// </summary>
  382. protected abstract void CreateDictionary();
  383. /// <summary>
  384. /// Deletes the current dictionary object.
  385. /// </summary>
  386. protected abstract void DeleteDictionary();
  387. /// <summary>
  388. /// Hides or shows the dictionary rows.
  389. /// </summary>
  390. /// <param name="expanded">True if the rows should be displayed, false otherwise.</param>
  391. private void ToggleFoldout(bool expanded)
  392. {
  393. isExpanded = expanded;
  394. if (guiChildLayout != null)
  395. guiChildLayout.Active = isExpanded && (rows.Count > 0 || IsEditInProgress());
  396. if (OnExpand != null)
  397. OnExpand(expanded);
  398. }
  399. /// <summary>
  400. /// Triggered when the user clicks on the create button on the title bar. Creates a brand new dictionary with zero
  401. /// elements in the place of the current dictionary.
  402. /// </summary>
  403. protected void OnCreateButtonClicked()
  404. {
  405. CreateDictionary();
  406. UpdateHeaderGUI();
  407. editRow.Initialize(this, guiContentLayout, 0, depth + 1);
  408. editRow.Enabled = false;
  409. isModified = true;
  410. }
  411. /// <summary>
  412. /// Triggered when the user clicks on the add button on the title bar. Adds a new empty element to the dictionary.
  413. /// </summary>
  414. protected virtual void OnAddButtonClicked()
  415. {
  416. if (IsEditInProgress())
  417. {
  418. DialogBox.Open(
  419. new LocEdString("Edit in progress."),
  420. new LocEdString("You are editing the entry with key \"" + editKey + "\". You cannot add a row " +
  421. "before applying or discarding those changes. Do you wish to apply those changes first?"),
  422. DialogBox.Type.YesNoCancel,
  423. x =>
  424. {
  425. switch (x)
  426. {
  427. case DialogBox.ResultType.Yes:
  428. if (ApplyChanges())
  429. StartAdd();
  430. break;
  431. case DialogBox.ResultType.No:
  432. DiscardChanges();
  433. StartAdd();
  434. break;
  435. }
  436. });
  437. }
  438. else
  439. {
  440. if (!isExpanded)
  441. ToggleFoldout(true);
  442. StartAdd();
  443. }
  444. }
  445. /// <summary>
  446. /// Triggered when the user clicks on the clear button on the title bar. Deletes the current dictionary object.
  447. /// </summary>
  448. protected void OnClearButtonClicked()
  449. {
  450. DeleteDictionary();
  451. UpdateHeaderGUI();
  452. ClearRows();
  453. isModified = true;
  454. }
  455. /// <summary>
  456. /// Triggered when the user clicks on the delete button next to a dictionary entry. Deletes an element in the
  457. /// dictionary.
  458. /// </summary>
  459. /// <param name="rowIdx">Sequential row index of the entry that was clicked.</param>
  460. protected internal virtual void OnDeleteButtonClicked(int rowIdx)
  461. {
  462. if (IsEditInProgress())
  463. DiscardChanges();
  464. else
  465. {
  466. RemoveEntry(GetKey(rowIdx));
  467. rows[rows.Count - 1].Destroy();
  468. rows.Remove(rows.Count - 1);
  469. editRow.SetIndex(GetNumRows());
  470. isModified = true;
  471. }
  472. }
  473. /// <summary>
  474. /// Triggered when the user clicks on the clone button next to a dictionary entry. Clones an element and
  475. /// adds the clone to the dictionary.
  476. /// </summary>
  477. /// <param name="rowIdx">Sequential row index of the entry that was clicked.</param>
  478. protected internal virtual void OnCloneButtonClicked(int rowIdx)
  479. {
  480. if (IsEditInProgress())
  481. {
  482. DialogBox.Open(
  483. new LocEdString("Edit in progress."),
  484. new LocEdString("You are editing the entry with key \"" + editKey + "\". You cannot clone a row " +
  485. "before applying or discarding those changes. Do you wish to apply those changes first?"),
  486. DialogBox.Type.YesNoCancel,
  487. x =>
  488. {
  489. switch (x)
  490. {
  491. case DialogBox.ResultType.Yes:
  492. if (ApplyChanges())
  493. StartClone(rowIdx);
  494. break;
  495. case DialogBox.ResultType.No:
  496. DiscardChanges();
  497. StartClone(rowIdx);
  498. break;
  499. }
  500. });
  501. }
  502. else
  503. StartClone(rowIdx);
  504. }
  505. /// <summary>
  506. /// Triggered when user clicks the edit or apply (depending on state) button next to the dictionary entry. Starts
  507. /// edit mode for the element, if not already in edit mode. Applies edit mode changes if already in edit mode.
  508. /// </summary>
  509. /// <param name="rowIdx">Sequential row index of the entry that was clicked.</param>
  510. protected internal virtual void OnEditButtonClicked(int rowIdx)
  511. {
  512. if (editRowIdx == rowIdx)
  513. ApplyChanges();
  514. else
  515. {
  516. if (IsEditInProgress())
  517. {
  518. DialogBox.Open(
  519. new LocEdString("Edit in progress."),
  520. new LocEdString("You are already editing the entry with key \"" + editKey + "\". You cannot edit " +
  521. "another row before applying or discarding those changes. Do you wish to apply those changes first?"),
  522. DialogBox.Type.YesNoCancel,
  523. x =>
  524. {
  525. switch (x)
  526. {
  527. case DialogBox.ResultType.Yes:
  528. if (ApplyChanges())
  529. StartEdit(rowIdx);
  530. break;
  531. case DialogBox.ResultType.No:
  532. DiscardChanges();
  533. StartEdit(rowIdx);
  534. break;
  535. }
  536. });
  537. }
  538. else
  539. StartEdit(rowIdx);
  540. }
  541. }
  542. /// <summary>
  543. /// Starts an edit operation on a row with the specified key. Allows the user to change the key of the specified row.
  544. /// Caller must ensure no edit operation is already in progress.
  545. /// </summary>
  546. /// <param name="rowIdx">Sequential row index of the entry to edit.</param>
  547. private void StartEdit(int rowIdx)
  548. {
  549. object key = GetKey(rowIdx);
  550. KeyValuePair<object, object> clone = CloneElement(rowIdx);
  551. editKey = clone.Key;
  552. editValue = clone.Value;
  553. editOriginalKey = key;
  554. editRowIdx = rowIdx;
  555. rows[rowIdx].EditMode = true;
  556. guiChildLayout.Active = rows.Count > 0 && isExpanded;
  557. }
  558. /// <summary>
  559. /// Starts an add operation. Adds a new key/value pair and allows the user to set them up in a temporary row
  560. /// before inserting them into the dictionary. Caller must ensure no edit operation is already in progress.
  561. /// </summary>
  562. private void StartAdd()
  563. {
  564. editKey = CreateKey();
  565. editValue = CreateValue();
  566. editOriginalKey = null;
  567. editRowIdx = rows.Count;
  568. editRow.BuildGUI();
  569. editRow.Enabled = true;
  570. editRow.EditMode = true;
  571. ToggleFoldout(isExpanded);
  572. }
  573. /// <summary>
  574. /// Starts a clone operation. Adds a new key/value pair by cloning an existing one. Allows the user to modify the
  575. /// new pair in a temporary row before inserting them into the dictionary. Caller must ensure no edit operation is
  576. /// already in progress.
  577. /// </summary>
  578. /// <param name="rowIdx">Sequential row index of the entry to clone.</param>
  579. private void StartClone(int rowIdx)
  580. {
  581. KeyValuePair<object, object> clone = CloneElement(rowIdx);
  582. editKey = clone.Key;
  583. editValue = clone.Value;
  584. editOriginalKey = null;
  585. editRowIdx = rows.Count;
  586. editRow.BuildGUI();
  587. editRow.Enabled = true;
  588. editRow.EditMode = true;
  589. ToggleFoldout(isExpanded);
  590. }
  591. /// <summary>
  592. /// Attempts to apply any changes made to the currently edited row.
  593. /// </summary>
  594. /// <returns>True if the changes were successfully applied, false if the new key already exists in the dictionary.
  595. /// </returns>
  596. private bool ApplyChanges()
  597. {
  598. if (!IsEditInProgress())
  599. return true;
  600. if (Contains(editKey) && (editOriginalKey == null || !editOriginalKey.Equals(editKey)))
  601. {
  602. DialogBox.Open(
  603. new LocEdString("Key already exists."),
  604. new LocEdString("Cannot add a key \"" + editKey + "\" to dictionary. Key already exists"),
  605. DialogBox.Type.OK);
  606. return false;
  607. }
  608. else
  609. {
  610. if (IsTemporaryRow(editRowIdx))
  611. {
  612. editRow.EditMode = false;
  613. editRow.Enabled = false;
  614. }
  615. else
  616. {
  617. rows[editRowIdx].EditMode = false;
  618. }
  619. if (editOriginalKey != null) // Editing
  620. EditEntry(editOriginalKey, editKey, editValue);
  621. else // Adding/Cloning
  622. {
  623. AddEntry(editKey, editValue);
  624. // Hidden dependency: Initialize must be called after all elements are
  625. // in the dictionary so we do it in two steps
  626. int newRowIdx = rows.Count;
  627. rows[newRowIdx] = CreateRow();
  628. rows[newRowIdx].Initialize(this, guiContentLayout, newRowIdx, depth + 1);
  629. }
  630. editRow.SetIndex(rows.Count);
  631. editKey = CreateKey();
  632. editValue = CreateValue();
  633. editOriginalKey = null;
  634. editRowIdx = -1;
  635. ToggleFoldout(isExpanded);
  636. isModified = true;
  637. return true;
  638. }
  639. }
  640. /// <summary>
  641. /// Cancels any changes made on the currently edited row.
  642. /// </summary>
  643. private void DiscardChanges()
  644. {
  645. if (IsEditInProgress())
  646. {
  647. if (IsTemporaryRow(editRowIdx))
  648. {
  649. editRow.EditMode = false;
  650. editRow.Enabled = false;
  651. }
  652. else
  653. {
  654. rows[editRowIdx].EditMode = false;
  655. }
  656. editKey = CreateKey();
  657. editValue = CreateValue();
  658. editOriginalKey = null;
  659. editRow.Enabled = false;
  660. editRowIdx = -1;
  661. ToggleFoldout(isExpanded);
  662. }
  663. }
  664. /// <summary>
  665. /// Possible states dictionary GUI can be in.
  666. /// </summary>
  667. private enum State
  668. {
  669. None,
  670. Empty,
  671. Filled
  672. }
  673. }
  674. /// <summary>
  675. /// Creates GUI elements that allow viewing and manipulation of a <see cref="Dictionary{TKey,TValue}"/>. When constructing the
  676. /// object user can provide a custom type that manages GUI for individual dictionary elements.
  677. /// </summary>
  678. /// <typeparam name="Key">Type of key used by the dictionary.</typeparam>
  679. /// <typeparam name="Value">Type of value stored in the dictionary.</typeparam>
  680. /// <typeparam name="RowType">Type of rows that are used to handle GUI for individual dictionary elements.</typeparam>
  681. public class GUIDictionaryField<Key, Value, RowType> : GUIDictionaryFieldBase where RowType : GUIDictionaryFieldRow, new()
  682. {
  683. public delegate int SortDictionaryDelegate(Key a, Key b);
  684. /// <summary>
  685. /// Triggered when the reference array has been changed. This does not include changes that only happen to its
  686. /// internal elements.
  687. /// </summary>
  688. public Action<Dictionary<Key, Value>> OnChanged;
  689. /// <summary>
  690. /// Triggered when an element in the list has been added or changed.
  691. /// </summary>
  692. public Action<Key> OnValueChanged;
  693. /// <summary>
  694. /// Triggered when an element in the dictionary has been removed.
  695. /// </summary>
  696. public Action<Key> OnValueRemoved;
  697. /// <summary>
  698. /// Optional method that will be used for sorting the elements in the dictionary.
  699. /// </summary>
  700. public SortDictionaryDelegate SortMethod;
  701. /// <summary>
  702. /// Array object whose contents are displayed.
  703. /// </summary>
  704. public Dictionary<Key, Value> Dictionary { get { return dictionary; } }
  705. protected Dictionary<Key, Value> dictionary;
  706. private List<Key> orderedKeys = new List<Key>();
  707. /// <summary>
  708. /// Constructs a new dictionary GUI field.
  709. /// </summary>
  710. /// <param name="title">Label to display on the dictionary GUI title.</param>
  711. /// <param name="dictionary">Object containing the data. Can be null.</param>
  712. /// <param name="layout">Layout to which to append the list GUI elements to.</param>
  713. /// <param name="depth">Determines at which depth to render the background. Useful when you have multiple
  714. /// nested containers whose backgrounds are overlaping. Also determines background style,
  715. /// depths divisible by two will use an alternate style.</param>
  716. protected GUIDictionaryField(LocString title, Dictionary<Key, Value> dictionary, GUILayout layout, int depth = 0)
  717. : base(title, layout, depth)
  718. {
  719. this.dictionary = dictionary;
  720. UpdateKeys();
  721. }
  722. /// <summary>
  723. /// Creates a dictionary GUI field containing GUI elements required for displaying the provided dictionary.
  724. /// </summary>
  725. /// <typeparam name="RowType">Type of rows that are used to handle GUI for individual dictionary elements.</typeparam>
  726. /// <param name="title">Label to display on the list GUI title.</param>
  727. /// <param name="dictionary">Object containing the data. Can be null.</param>
  728. /// <param name="layout">Layout to which to append the list GUI elements to.</param>
  729. /// <param name="depth">Determines at which depth to render the background. Useful when you have multiple
  730. /// nested containers whose backgrounds are overlaping. Also determines background style,
  731. /// depths divisible by two will use an alternate style.</param>
  732. /// <returns>New instance of dictionary GUI field.</returns>
  733. public static GUIDictionaryField<Key, Value, RowType> Create(LocString title, Dictionary<Key, Value> dictionary,
  734. GUILayout layout, int depth = 0)
  735. {
  736. GUIDictionaryField<Key, Value, RowType> guiDictionary = new GUIDictionaryField<Key, Value, RowType>(
  737. title, dictionary, layout, depth);
  738. guiDictionary.BuildGUI();
  739. return guiDictionary;
  740. }
  741. /// <summary>
  742. /// Updates the ordered set of keys used for mapping sequential indexes to keys. Should be called whenever a
  743. /// dictionary key changes.
  744. /// </summary>
  745. private void UpdateKeys()
  746. {
  747. orderedKeys.Clear();
  748. if (dictionary != null)
  749. {
  750. foreach (var KVP in dictionary)
  751. orderedKeys.Add(KVP.Key);
  752. if (SortMethod != null)
  753. orderedKeys.Sort((x,y) => SortMethod(x, y));
  754. else
  755. orderedKeys.Sort();
  756. }
  757. }
  758. /// <inheritdoc/>
  759. protected override GUIDictionaryFieldRow CreateRow()
  760. {
  761. return new RowType();
  762. }
  763. /// <inheritdoc/>
  764. protected override int GetNumRows()
  765. {
  766. if (dictionary != null)
  767. return dictionary.Count;
  768. return 0;
  769. }
  770. /// <inheritdoc/>
  771. protected override bool IsNull()
  772. {
  773. return dictionary == null;
  774. }
  775. /// <inheritdoc/>
  776. protected internal override object GetKey(int rowIdx)
  777. {
  778. return orderedKeys[rowIdx];
  779. }
  780. /// <inheritdoc/>
  781. protected internal override object GetValue(object key)
  782. {
  783. return dictionary[(Key)key];
  784. }
  785. /// <inheritdoc/>
  786. protected internal override void SetValue(object key, object value)
  787. {
  788. dictionary[(Key)key] = (Value)value;
  789. if (OnValueChanged != null)
  790. OnValueChanged((Key)key);
  791. }
  792. /// <inheritdoc/>
  793. protected internal override bool Contains(object key)
  794. {
  795. return dictionary.ContainsKey((Key)key); ;
  796. }
  797. /// <inheritdoc/>
  798. protected internal override void EditEntry(object oldKey, object newKey, object value)
  799. {
  800. dictionary.Remove((Key)oldKey);
  801. dictionary[(Key)newKey] = (Value)value;
  802. if (OnValueRemoved != null)
  803. OnValueRemoved((Key)oldKey);
  804. if (OnValueChanged != null)
  805. OnValueChanged((Key)newKey);
  806. UpdateKeys();
  807. }
  808. /// <inheritdoc/>
  809. protected internal override void AddEntry(object key, object value)
  810. {
  811. dictionary[(Key)key] = (Value)value;
  812. if (OnValueChanged != null)
  813. OnValueChanged((Key)key);
  814. UpdateKeys();
  815. }
  816. /// <inheritdoc/>
  817. protected internal override void RemoveEntry(object key)
  818. {
  819. dictionary.Remove((Key) key);
  820. if (OnValueRemoved != null)
  821. OnValueRemoved((Key)key);
  822. UpdateKeys();
  823. }
  824. /// <inheritdoc/>
  825. protected internal override object CreateKey()
  826. {
  827. return SerializableUtility.Create<Key>();
  828. }
  829. /// <inheritdoc/>
  830. protected internal override object CreateValue()
  831. {
  832. return SerializableUtility.Create<Value>();
  833. }
  834. /// <inheritdoc/>
  835. protected internal override KeyValuePair<object, object> CloneElement(int index)
  836. {
  837. object key = GetKey(index);
  838. object value = GetValue(key);
  839. KeyValuePair<object, object> clone = new KeyValuePair<object, object>(
  840. SerializableUtility.Clone(key), SerializableUtility.Clone(value));
  841. return clone;
  842. }
  843. /// <inheritdoc/>
  844. protected override void CreateDictionary()
  845. {
  846. dictionary = new Dictionary<Key, Value>();
  847. if (OnChanged != null)
  848. OnChanged(dictionary);
  849. UpdateKeys();
  850. }
  851. /// <inheritdoc/>
  852. protected override void DeleteDictionary()
  853. {
  854. dictionary = null;
  855. if (OnChanged != null)
  856. OnChanged(dictionary);
  857. UpdateKeys();
  858. }
  859. }
  860. /// <summary>
  861. /// Contains GUI elements for a single entry in a dictionary.
  862. /// </summary>
  863. public abstract class GUIDictionaryFieldRow
  864. {
  865. private GUILayoutY rowLayout;
  866. private GUILayoutX keyRowLayout;
  867. private GUILayoutY keyLayout;
  868. private GUILayoutY valueLayout;
  869. private GUILayoutX titleLayout;
  870. private GUIButton cloneBtn;
  871. private GUIButton deleteBtn;
  872. private GUIButton editBtn;
  873. private bool localTitleLayout;
  874. private bool enabled = true;
  875. private bool editMode = false;
  876. private int rowIdx;
  877. private int depth;
  878. private InspectableState modifiedState;
  879. protected GUIDictionaryFieldBase parent;
  880. /// <summary>
  881. /// Returns the depth at which the row is rendered.
  882. /// </summary>
  883. protected int Depth { get { return depth; } }
  884. /// <summary>
  885. /// Determines is the row currently being displayed.
  886. /// </summary>
  887. internal bool Enabled
  888. {
  889. get { return enabled; }
  890. set { enabled = value; rowLayout.Active = value; }
  891. }
  892. /// <summary>
  893. /// Sequential index of the entry in the dictionary.
  894. /// </summary>
  895. internal int RowIdx
  896. {
  897. get { return rowIdx; }
  898. }
  899. /// <summary>
  900. /// Enables or disables the row's edit mode. This determines what type of buttons are shown on the row title bar.
  901. /// </summary>
  902. internal bool EditMode
  903. {
  904. set
  905. {
  906. if (value)
  907. {
  908. GUIContent cancelIcon = new GUIContent(EditorBuiltin.GetInspectorWindowIcon(InspectorWindowIcon.Cancel),
  909. new LocEdString("Cancel"));
  910. GUIContent applyIcon = new GUIContent(EditorBuiltin.GetInspectorWindowIcon(InspectorWindowIcon.Apply),
  911. new LocEdString("Apply"));
  912. deleteBtn.SetContent(cancelIcon);
  913. editBtn.SetContent(applyIcon);
  914. }
  915. else
  916. {
  917. GUIContent deleteIcon = new GUIContent(EditorBuiltin.GetInspectorWindowIcon(InspectorWindowIcon.Delete),
  918. new LocEdString("Delete"));
  919. GUIContent editIcon = new GUIContent(EditorBuiltin.GetInspectorWindowIcon(InspectorWindowIcon.Edit),
  920. new LocEdString("Edit"));
  921. deleteBtn.SetContent(deleteIcon);
  922. editBtn.SetContent(editIcon);
  923. }
  924. editMode = value;
  925. OnEditModeChanged(value);
  926. }
  927. }
  928. /// <summary>
  929. /// Constructs a new dictionary row object.
  930. /// </summary>
  931. protected GUIDictionaryFieldRow()
  932. {
  933. }
  934. /// <summary>
  935. /// Initializes the row and creates row GUI elements.
  936. /// </summary>
  937. /// <param name="parent">Parent array GUI object that the entry is contained in.</param>
  938. /// <param name="parentLayout">Parent layout that row GUI elements will be added to.</param>
  939. /// <param name="rowIdx">Sequential index of the row.</param>
  940. /// <param name="depth">Determines the depth at which the element is rendered.</param>
  941. internal void Initialize(GUIDictionaryFieldBase parent, GUILayout parentLayout, int rowIdx, int depth)
  942. {
  943. this.parent = parent;
  944. this.rowIdx = rowIdx;
  945. this.depth = depth;
  946. rowLayout = parentLayout.AddLayoutY();
  947. keyRowLayout = rowLayout.AddLayoutX();
  948. keyLayout = keyRowLayout.AddLayoutY();
  949. valueLayout = rowLayout.AddLayoutY();
  950. BuildGUI();
  951. }
  952. /// <summary>
  953. /// Changes the index of the dictionary element this row represents.
  954. /// </summary>
  955. /// <param name="seqIndex">Sequential index of the dictionary entry.</param>
  956. internal void SetIndex(int seqIndex)
  957. {
  958. this.rowIdx = seqIndex;
  959. }
  960. /// <summary>
  961. /// (Re)creates all row GUI elements.
  962. /// </summary>
  963. internal protected void BuildGUI()
  964. {
  965. keyLayout.Clear();
  966. valueLayout.Clear();
  967. GUILayoutX externalTitleLayout = CreateKeyGUI(keyLayout);
  968. CreateValueGUI(valueLayout);
  969. if (localTitleLayout || (titleLayout != null && titleLayout == externalTitleLayout))
  970. return;
  971. if (externalTitleLayout != null)
  972. {
  973. localTitleLayout = false;
  974. titleLayout = externalTitleLayout;
  975. }
  976. else
  977. {
  978. GUILayoutY buttonCenter = keyRowLayout.AddLayoutY();
  979. buttonCenter.AddFlexibleSpace();
  980. titleLayout = buttonCenter.AddLayoutX();
  981. buttonCenter.AddFlexibleSpace();
  982. localTitleLayout = true;
  983. }
  984. GUIContent cloneIcon = new GUIContent(EditorBuiltin.GetInspectorWindowIcon(InspectorWindowIcon.Clone),
  985. new LocEdString("Clone"));
  986. GUIContent deleteIcon = new GUIContent(EditorBuiltin.GetInspectorWindowIcon(InspectorWindowIcon.Delete),
  987. new LocEdString("Delete"));
  988. GUIContent editIcon = new GUIContent(EditorBuiltin.GetInspectorWindowIcon(InspectorWindowIcon.Edit),
  989. new LocEdString("Edit"));
  990. cloneBtn = new GUIButton(cloneIcon, GUIOption.FixedWidth(30));
  991. deleteBtn = new GUIButton(deleteIcon, GUIOption.FixedWidth(30));
  992. editBtn = new GUIButton(editIcon, GUIOption.FixedWidth(30));
  993. cloneBtn.OnClick += () => parent.OnCloneButtonClicked(rowIdx);
  994. deleteBtn.OnClick += () => parent.OnDeleteButtonClicked(rowIdx);
  995. editBtn.OnClick += () => parent.OnEditButtonClicked(rowIdx);
  996. titleLayout.AddElement(cloneBtn);
  997. titleLayout.AddElement(deleteBtn);
  998. titleLayout.AddSpace(10);
  999. titleLayout.AddElement(editBtn);
  1000. EditMode = editMode;
  1001. }
  1002. /// <summary>
  1003. /// Creates GUI elements specific to type in the key portion of a dictionary entry.
  1004. /// </summary>
  1005. /// <param name="layout">Layout to insert the row GUI elements to.</param>
  1006. /// <returns>An optional title bar layout that the standard dictionary buttons will be appended to.</returns>
  1007. protected abstract GUILayoutX CreateKeyGUI(GUILayoutY layout);
  1008. /// <summary>
  1009. /// Creates GUI elements specific to type in the key portion of a dictionary entry.
  1010. /// </summary>
  1011. /// <param name="layout">Layout to insert the row GUI elements to.</param>
  1012. protected abstract void CreateValueGUI(GUILayoutY layout);
  1013. /// <summary>
  1014. /// Triggered when a GUI rows enters or leaves edit mode. Allows the row GUI to be updated accordingly.
  1015. /// </summary>
  1016. /// <param name="editMode">True if the edit mode is being enabled, false otherwise.</param>
  1017. protected virtual void OnEditModeChanged(bool editMode) { }
  1018. /// <summary>
  1019. /// Refreshes the GUI for the dictionary row and checks if anything was modified.
  1020. /// </summary>
  1021. /// <returns>State representing was anything modified between two last calls to <see cref="Refresh"/>.</returns>
  1022. internal protected virtual InspectableState Refresh()
  1023. {
  1024. InspectableState oldState = modifiedState;
  1025. if (modifiedState.HasFlag(InspectableState.Modified))
  1026. modifiedState = InspectableState.NotModified;
  1027. return oldState;
  1028. }
  1029. /// <summary>
  1030. /// Marks the contents of the row as modified.
  1031. /// </summary>
  1032. protected void MarkAsModified()
  1033. {
  1034. modifiedState |= InspectableState.ModifyInProgress;
  1035. }
  1036. /// <summary>
  1037. /// Confirms any queued modifications, signaling parent elements.
  1038. /// </summary>
  1039. protected void ConfirmModify()
  1040. {
  1041. if (modifiedState.HasFlag(InspectableState.ModifyInProgress))
  1042. modifiedState |= InspectableState.Modified;
  1043. }
  1044. /// <summary>
  1045. /// Gets the key contained in this dictionary's row.
  1046. /// </summary>
  1047. /// <typeparam name="T">Type of the key. Must match the dictionary's element type.</typeparam>
  1048. /// <returns>Key in this dictionary's row.</returns>
  1049. protected T GetKey<T>()
  1050. {
  1051. return (T)parent.GetKeyInternal(rowIdx);
  1052. }
  1053. /// <summary>
  1054. /// Sets the key for in this dictionary's row.
  1055. /// </summary>
  1056. /// <typeparam name="T">Type of the key. Must match the dictionary's element type.</typeparam>
  1057. /// <param name="key">Key to assign to this row.</param>
  1058. protected void SetKey<T>(T key)
  1059. {
  1060. parent.SetKey(rowIdx, key);
  1061. }
  1062. /// <summary>
  1063. /// Gets the value contained in this dictionary's row.
  1064. /// </summary>
  1065. /// <typeparam name="T">Type of the value. Must match the dictionary's element type.</typeparam>
  1066. /// <returns>Value in this dictionary's row.</returns>
  1067. protected T GetValue<T>()
  1068. {
  1069. return (T)parent.GetValueInternal(rowIdx);
  1070. }
  1071. /// <summary>
  1072. /// Sets the value contained in this dictionary's row.
  1073. /// </summary>
  1074. /// <typeparam name="T">Type of the value. Must match the dictionary's element type.</typeparam>
  1075. /// <param name="value">Value to set.</param>
  1076. protected void SetValue<T>(T value)
  1077. {
  1078. parent.SetValueInternal(rowIdx, value);
  1079. }
  1080. /// <summary>
  1081. /// Destroys all row GUI elements.
  1082. /// </summary>
  1083. public void Destroy()
  1084. {
  1085. if (rowLayout != null)
  1086. {
  1087. rowLayout.Destroy();
  1088. rowLayout = null;
  1089. }
  1090. keyRowLayout = null;
  1091. keyLayout = null;
  1092. valueLayout = null;
  1093. titleLayout = null;
  1094. cloneBtn = null;
  1095. deleteBtn = null;
  1096. editBtn = null;
  1097. localTitleLayout = false;
  1098. }
  1099. }
  1100. /** @} */
  1101. }