2
0

GUIDictionaryField.cs 46 KB

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