GUIDictionaryField.cs 45 KB

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