GUIDictionaryField.cs 47 KB

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