GUIDictionaryField.cs 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279
  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. private bool isModified;
  29. /// <summary>
  30. /// Constructs a new GUI dictionary.
  31. /// </summary>
  32. /// <param name="title">Label to display on the dictionary GUI title.</param>
  33. /// <param name="layout">Layout to which to append the list GUI elements to.</param>
  34. /// <param name="depth">Determines at which depth to render the background. Useful when you have multiple
  35. /// nested containers whose backgrounds are overlaping. Also determines background style,
  36. /// depths divisible by two will use an alternate style.</param>
  37. protected GUIDictionaryFieldBase(LocString title, GUILayout layout, int depth = 0)
  38. {
  39. this.title = title;
  40. this.guiLayout = layout.AddLayoutY();
  41. this.depth = depth;
  42. }
  43. /// <summary>
  44. /// Completely rebuilds the dictionary GUI elements.
  45. /// </summary>
  46. protected void BuildGUI()
  47. {
  48. editKey = CreateKey();
  49. editValue = CreateValue();
  50. UpdateHeaderGUI(true);
  51. if (!IsNull())
  52. {
  53. // Hidden dependency: BuildGUI must be called after all elements are
  54. // in the dictionary so we do it in two steps
  55. int numRows = GetNumRows();
  56. for (int i = 0; i < numRows; i++)
  57. {
  58. GUIDictionaryFieldRow newRow = CreateRow();
  59. rows.Add(i, newRow);
  60. }
  61. editRow = CreateRow();
  62. editRow.Initialize(this, guiContentLayout, numRows, depth + 1);
  63. editRow.Enabled = false;
  64. for (int i = 0; i < numRows; i++)
  65. rows[i].Initialize(this, guiContentLayout, i, depth + 1);
  66. }
  67. }
  68. /// <summary>
  69. /// Rebuilds the GUI dictionary header if needed.
  70. /// </summary>
  71. /// <param name="forceRebuild">Forces the header to be rebuilt.</param>
  72. protected void UpdateHeaderGUI(bool forceRebuild)
  73. {
  74. Action BuildEmptyGUI = () =>
  75. {
  76. guiTitleLayout = guiLayout.AddLayoutX();
  77. guiTitleLayout.AddElement(new GUILabel(title));
  78. guiTitleLayout.AddElement(new GUILabel("Empty", GUIOption.FixedWidth(100)));
  79. GUIContent createIcon = new GUIContent(EditorBuiltin.GetInspectorWindowIcon(InspectorWindowIcon.Create));
  80. GUIButton createBtn = new GUIButton(createIcon, GUIOption.FixedWidth(30));
  81. createBtn.OnClick += OnCreateButtonClicked;
  82. guiTitleLayout.AddElement(createBtn);
  83. };
  84. Action BuildFilledGUI = () =>
  85. {
  86. GUIToggle guiFoldout = new GUIToggle(title, EditorStyles.Foldout);
  87. guiFoldout.Value = isExpanded;
  88. guiFoldout.OnToggled += ToggleFoldout;
  89. GUIContent clearIcon = new GUIContent(EditorBuiltin.GetInspectorWindowIcon(InspectorWindowIcon.Clear));
  90. GUIButton guiClearBtn = new GUIButton(clearIcon, GUIOption.FixedWidth(30));
  91. guiClearBtn.OnClick += OnClearButtonClicked;
  92. GUIContent addIcon = new GUIContent(EditorBuiltin.GetInspectorWindowIcon(InspectorWindowIcon.Add));
  93. GUIButton guiAddBtn = new GUIButton(addIcon, GUIOption.FixedWidth(30));
  94. guiAddBtn.OnClick += OnAddButtonClicked;
  95. guiTitleLayout = guiLayout.AddLayoutX();
  96. guiTitleLayout.AddElement(guiFoldout);
  97. guiTitleLayout.AddElement(guiAddBtn);
  98. guiTitleLayout.AddElement(guiClearBtn);
  99. guiChildLayout = guiLayout.AddLayoutX();
  100. guiChildLayout.AddSpace(IndentAmount);
  101. GUIPanel guiContentPanel = guiChildLayout.AddPanel();
  102. GUILayoutX guiIndentLayoutX = guiContentPanel.AddLayoutX();
  103. guiIndentLayoutX.AddSpace(IndentAmount);
  104. GUILayoutY guiIndentLayoutY = guiIndentLayoutX.AddLayoutY();
  105. guiIndentLayoutY.AddSpace(IndentAmount);
  106. guiContentLayout = guiIndentLayoutY.AddLayoutY();
  107. guiIndentLayoutY.AddSpace(IndentAmount);
  108. guiIndentLayoutX.AddSpace(IndentAmount);
  109. guiChildLayout.AddSpace(IndentAmount);
  110. short backgroundDepth = (short)(Inspector.START_BACKGROUND_DEPTH - depth - 1);
  111. string bgPanelStyle = depth % 2 == 0
  112. ? EditorStyles.InspectorContentBgAlternate
  113. : EditorStyles.InspectorContentBg;
  114. GUIPanel backgroundPanel = guiContentPanel.AddPanel(backgroundDepth);
  115. GUITexture inspectorContentBg = new GUITexture(null, bgPanelStyle);
  116. backgroundPanel.AddElement(inspectorContentBg);
  117. ToggleFoldout(isExpanded);
  118. };
  119. if (forceRebuild)
  120. {
  121. if (state != State.None)
  122. guiTitleLayout.Destroy();
  123. if (state == State.Filled)
  124. guiChildLayout.Destroy();
  125. state = State.None;
  126. }
  127. if (state == State.None)
  128. {
  129. if (!IsNull())
  130. {
  131. BuildFilledGUI();
  132. state = State.Filled;
  133. }
  134. else
  135. {
  136. BuildEmptyGUI();
  137. state = State.Empty;
  138. }
  139. }
  140. else if (state == State.Empty)
  141. {
  142. if (!IsNull())
  143. {
  144. guiTitleLayout.Destroy();
  145. BuildFilledGUI();
  146. state = State.Filled;
  147. }
  148. }
  149. else if (state == State.Filled)
  150. {
  151. if (IsNull())
  152. {
  153. guiTitleLayout.Destroy();
  154. guiChildLayout.Destroy();
  155. BuildEmptyGUI();
  156. state = State.Empty;
  157. }
  158. }
  159. }
  160. /// <summary>
  161. /// Destroys all rows and clears the row list.
  162. /// </summary>
  163. private void ClearRows()
  164. {
  165. foreach (var KVP in rows)
  166. KVP.Value.Destroy();
  167. editRow.Destroy();
  168. rows.Clear();
  169. }
  170. /// <summary>
  171. /// Returns the layout that is used for positioning the elements in the title bar.
  172. /// </summary>
  173. /// <returns>Horizontal layout for positioning the title bar elements.</returns>
  174. public GUILayoutX GetTitleLayout()
  175. {
  176. return guiTitleLayout;
  177. }
  178. /// <summary>
  179. /// Refreshes contents of all dictionary rows and checks if anything was modified.
  180. /// </summary>
  181. /// <returns>State representing was anything modified between two last calls to <see cref="Refresh"/>.</returns>
  182. public InspectableState Refresh()
  183. {
  184. InspectableState state = InspectableState.NotModified;
  185. for (int i = 0; i < rows.Count; i++)
  186. state |= rows[i].Refresh();
  187. if (editRow != null && editRow.Enabled)
  188. state |= editRow.Refresh();
  189. if (isModified)
  190. {
  191. state |= InspectableState.ModifiedConfirm;
  192. isModified = false;
  193. }
  194. return state;
  195. }
  196. /// <summary>
  197. /// Destroys the GUI elements.
  198. /// </summary>
  199. public void Destroy()
  200. {
  201. if (guiLayout != null)
  202. {
  203. guiLayout.Destroy();
  204. guiLayout = null;
  205. }
  206. guiLayout = null;
  207. guiTitleLayout = null;
  208. guiChildLayout = null;
  209. for (int i = 0; i < rows.Count; i++)
  210. rows[i].Destroy();
  211. rows.Clear();
  212. if (editRow != null)
  213. editRow.Destroy();
  214. editRow = null;
  215. }
  216. /// <summary>
  217. /// Checks is the specified row index the temporary edit row.
  218. /// </summary>
  219. /// <param name="rowIdx">Sequential index of the row to check.</param>
  220. /// <returns>True if the index is of an edit row.</returns>
  221. private bool IsTemporaryRow(int rowIdx)
  222. {
  223. return rowIdx == rows.Count;
  224. }
  225. /// <summary>
  226. /// Checks is any row being currently edited.
  227. /// </summary>
  228. /// <returns>True if a row is being edited, false otherwise.</returns>
  229. private bool IsEditInProgress()
  230. {
  231. return editRowIdx != -1;
  232. }
  233. /// <summary>
  234. /// Returns the number of rows in the dictionary.
  235. /// </summary>
  236. /// <returns>Number of rows in the dictionary.</returns>
  237. protected abstract int GetNumRows();
  238. /// <summary>
  239. /// Checks is the dictionary instance not assigned.
  240. /// </summary>
  241. /// <returns>True if there is not a dictionary instance.</returns>
  242. protected abstract bool IsNull();
  243. /// <summary>
  244. /// Gets a value of an element at the specified index in the list. Also handles temporary edit fields.
  245. /// </summary>
  246. /// <param name="rowIdx">Sequential index of the row to set the value for.</param>
  247. /// <returns>Value of the list element at the specified key.</returns>
  248. protected internal virtual object GetValueInternal(int rowIdx)
  249. {
  250. if (rowIdx == editRowIdx || IsTemporaryRow(rowIdx))
  251. return editValue;
  252. else
  253. return GetValue(GetKey(rowIdx));
  254. }
  255. /// <summary>
  256. /// Sets a value of an element at the specified index in the list. Also handles temporary edit fields.
  257. /// </summary>
  258. /// <param name="rowIdx">Sequential index of the row to set the value for.</param>
  259. /// <param name="value">Value to assign to the element. Caller must ensure it is of valid type.</param>
  260. protected internal virtual void SetValueInternal(int rowIdx, object value)
  261. {
  262. if (rowIdx == editRowIdx || IsTemporaryRow(rowIdx))
  263. editValue = value;
  264. else
  265. SetValue(GetKey(rowIdx), value);
  266. }
  267. /// <summary>
  268. /// Changes the value of the key of the specified row.
  269. /// </summary>
  270. /// <param name="rowIdx">Sequential index of the row to set the key for.</param>
  271. /// <param name="key">Key to assign to the specified row.</param>
  272. protected internal void SetKey(int rowIdx, object key)
  273. {
  274. if (editRowIdx != rowIdx)
  275. {
  276. Debug.LogError("Cannot change a dictionary row that is not in edit state.");
  277. return;
  278. }
  279. editKey = key;
  280. }
  281. /// <summary>
  282. /// Gets a key for a row at the specified index. Handles the special case for the currently edited row.
  283. /// </summary>
  284. /// <param name="rowIdx">Sequential index of the row for which to retrieve the key.</param>
  285. /// <returns>Key for a row at the specified index.</returns>
  286. protected internal object GetKeyInternal(int rowIdx)
  287. {
  288. if (editRowIdx == rowIdx || IsTemporaryRow(rowIdx))
  289. return editKey;
  290. return GetKey(rowIdx);
  291. }
  292. /// <summary>
  293. /// Creates a new dictionary row GUI.
  294. /// </summary>
  295. /// <returns>Object containing the dictionary row GUI.</returns>
  296. protected abstract GUIDictionaryFieldRow CreateRow();
  297. /// <summary>
  298. /// Gets a key for a row at the specified index.
  299. /// </summary>
  300. /// <param name="rowIdx">Sequential index of the row for which to retrieve the key.</param>
  301. /// <returns>Key for a row at the specified index.</returns>
  302. protected internal abstract object GetKey(int rowIdx);
  303. /// <summary>
  304. /// Gets a value of an element at the specified index in the list.
  305. /// </summary>
  306. /// <param name="key">Key of the element whose value to retrieve.</param>
  307. /// <returns>Value of the dictionary entry for the specified key.</returns>
  308. protected internal abstract object GetValue(object key);
  309. /// <summary>
  310. /// Sets a value of an element at the specified index in the list.
  311. /// </summary>
  312. /// <param name="key">Key of the element whose value to set.</param>
  313. /// <param name="value">Value to assign to the element. Caller must ensure it is of valid type.</param>
  314. protected internal abstract void SetValue(object key, object value);
  315. /// <summary>
  316. /// Updates both key and value of an existing entry.
  317. /// </summary>
  318. /// <param name="oldKey">Original key of the entry.</param>
  319. /// <param name="newKey">New key of the entry.</param>
  320. /// <param name="value">New value of the entry.</param>
  321. protected internal abstract void EditEntry(object oldKey, object newKey, object value);
  322. /// <summary>
  323. /// Adds a new entry to the dictionary.
  324. /// </summary>
  325. /// <param name="key">Key of the entry to add.</param>
  326. /// <param name="value">Value of the entry to add.</param>
  327. protected internal abstract void AddEntry(object key, object value);
  328. /// <summary>
  329. /// Removes the specified entry from the dictionary.
  330. /// </summary>
  331. /// <param name="key">Key of the entry to remove.</param>
  332. protected internal abstract void RemoveEntry(object key);
  333. /// <summary>
  334. /// Creates a new empty key object of a valid type that can be used in the dictionary.
  335. /// </summary>
  336. /// <returns>New empty key object.</returns>
  337. protected internal abstract object CreateKey();
  338. /// <summary>
  339. /// Creates a new empty value object of a valid type that can be used in the dictionary.
  340. /// </summary>
  341. /// <returns>New empty value object.</returns>
  342. protected internal abstract object CreateValue();
  343. /// <summary>
  344. /// Checks does the element with the specified key exist in the dictionary.
  345. /// </summary>
  346. /// <param name="key">Key of the element to check for existence.</param>
  347. /// <returns>True if the key exists in the dictionary, false otherwise.</returns>
  348. protected internal abstract bool Contains(object key);
  349. /// <summary>
  350. /// Creates a brand new dictionary with zero elements in the place of the current dictionary.
  351. /// </summary>
  352. protected abstract void CreateDictionary();
  353. /// <summary>
  354. /// Deletes the current dictionary object.
  355. /// </summary>
  356. protected abstract void DeleteDictionary();
  357. /// <summary>
  358. /// Hides or shows the dictionary rows.
  359. /// </summary>
  360. /// <param name="expanded">True if the rows should be displayed, false otherwise.</param>
  361. private void ToggleFoldout(bool expanded)
  362. {
  363. isExpanded = expanded;
  364. if (guiChildLayout != null)
  365. guiChildLayout.Active = isExpanded && (rows.Count > 0 || IsEditInProgress());
  366. }
  367. /// <summary>
  368. /// Triggered when the user clicks on the create button on the title bar. Creates a brand new dictionary with zero
  369. /// elements in the place of the current dictionary.
  370. /// </summary>
  371. protected void OnCreateButtonClicked()
  372. {
  373. CreateDictionary();
  374. UpdateHeaderGUI(false);
  375. editRow.Initialize(this, guiContentLayout, 0, depth + 1);
  376. editRow.Enabled = false;
  377. isModified = true;
  378. }
  379. /// <summary>
  380. /// Triggered when the user clicks on the add button on the title bar. Adds a new empty element to the dictionary.
  381. /// </summary>
  382. protected virtual void OnAddButtonClicked()
  383. {
  384. if (IsEditInProgress())
  385. {
  386. DialogBox.Open(
  387. new LocEdString("Edit in progress."),
  388. new LocEdString("You are editing the entry with key \"" + editKey + "\". You cannot add a row " +
  389. "before applying or discarding those changes. Do you wish to apply those changes first?"),
  390. DialogBox.Type.YesNoCancel,
  391. x =>
  392. {
  393. switch (x)
  394. {
  395. case DialogBox.ResultType.Yes:
  396. if (ApplyChanges())
  397. StartAdd();
  398. break;
  399. case DialogBox.ResultType.No:
  400. DiscardChanges();
  401. StartAdd();
  402. break;
  403. }
  404. });
  405. }
  406. else
  407. {
  408. if (!isExpanded)
  409. ToggleFoldout(true);
  410. StartAdd();
  411. }
  412. }
  413. /// <summary>
  414. /// Triggered when the user clicks on the clear button on the title bar. Deletes the current dictionary object.
  415. /// </summary>
  416. protected void OnClearButtonClicked()
  417. {
  418. DeleteDictionary();
  419. UpdateHeaderGUI(false);
  420. ClearRows();
  421. isModified = true;
  422. }
  423. /// <summary>
  424. /// Triggered when the user clicks on the delete button next to a dictionary entry. Deletes an element in the
  425. /// dictionary.
  426. /// </summary>
  427. /// <param name="rowIdx">Sequential row index of the entry that was clicked.</param>
  428. protected internal virtual void OnDeleteButtonClicked(int rowIdx)
  429. {
  430. if (IsEditInProgress())
  431. DiscardChanges();
  432. else
  433. {
  434. // Remove the entry, but ensure the rows keep referencing the original keys (dictionaries have undefined
  435. // order so we need to compare old vs. new elements to determine if any changed).
  436. int oldNumRows = GetNumRows();
  437. Dictionary<object, int> oldKeys = new Dictionary<object, int>();
  438. for (int i = 0; i < oldNumRows; i++)
  439. oldKeys.Add(GetKey(i), i);
  440. RemoveEntry(GetKey(rowIdx));
  441. int newNumRows = GetNumRows();
  442. Dictionary<object, int> newKeys = new Dictionary<object, int>();
  443. for (int i = 0; i < newNumRows; i++)
  444. newKeys.Add(GetKey(i), i);
  445. foreach (var KVP in oldKeys)
  446. {
  447. int newRowIdx;
  448. if (newKeys.TryGetValue(KVP.Key, out newRowIdx))
  449. {
  450. if (KVP.Value != newRowIdx)
  451. {
  452. GUIDictionaryFieldRow temp = rows[KVP.Value];
  453. rows[KVP.Value] = rows[newRowIdx];
  454. rows[newRowIdx] = temp;
  455. }
  456. }
  457. }
  458. for (int i = oldNumRows; i >= newNumRows; i--)
  459. {
  460. rows[i].Destroy();
  461. rows.Remove(i);
  462. }
  463. editRow.SetIndex(newNumRows);
  464. isModified = true;
  465. }
  466. }
  467. /// <summary>
  468. /// Triggered when the user clicks on the clone button next to a dictionary entry. Clones an element and
  469. /// adds the clone to the dictionary.
  470. /// </summary>
  471. /// <param name="rowIdx">Sequential row index of the entry that was clicked.</param>
  472. protected internal virtual void OnCloneButtonClicked(int rowIdx)
  473. {
  474. if (IsEditInProgress())
  475. {
  476. DialogBox.Open(
  477. new LocEdString("Edit in progress."),
  478. new LocEdString("You are editing the entry with key \"" + editKey + "\". You cannot clone a row " +
  479. "before applying or discarding those changes. Do you wish to apply those changes first?"),
  480. DialogBox.Type.YesNoCancel,
  481. x =>
  482. {
  483. switch (x)
  484. {
  485. case DialogBox.ResultType.Yes:
  486. if (ApplyChanges())
  487. StartClone(rowIdx);
  488. break;
  489. case DialogBox.ResultType.No:
  490. DiscardChanges();
  491. StartClone(rowIdx);
  492. break;
  493. }
  494. });
  495. }
  496. else
  497. StartClone(rowIdx);
  498. }
  499. /// <summary>
  500. /// Triggered when user clicks the edit or apply (depending on state) button next to the dictionary entry. Starts
  501. /// edit mode for the element, if not already in edit mode. Applies edit mode changes if already in edit mode.
  502. /// </summary>
  503. /// <param name="rowIdx">Sequential row index of the entry that was clicked.</param>
  504. protected internal virtual void OnEditButtonClicked(int rowIdx)
  505. {
  506. if (editRowIdx == rowIdx)
  507. ApplyChanges();
  508. else
  509. {
  510. if (IsEditInProgress())
  511. {
  512. DialogBox.Open(
  513. new LocEdString("Edit in progress."),
  514. new LocEdString("You are already editing the entry with key \"" + editKey + "\". You cannot edit " +
  515. "another row before applying or discarding those changes. Do you wish to apply those changes first?"),
  516. DialogBox.Type.YesNoCancel,
  517. x =>
  518. {
  519. switch (x)
  520. {
  521. case DialogBox.ResultType.Yes:
  522. if (ApplyChanges())
  523. StartEdit(rowIdx);
  524. break;
  525. case DialogBox.ResultType.No:
  526. DiscardChanges();
  527. StartEdit(rowIdx);
  528. break;
  529. }
  530. });
  531. }
  532. else
  533. StartEdit(rowIdx);
  534. }
  535. }
  536. /// <summary>
  537. /// Starts an edit operation on a row with the specified key. Allows the user to change the key of the specified row.
  538. /// Caller must ensure no edit operation is already in progress.
  539. /// </summary>
  540. /// <param name="rowIdx">Sequential row index of the entry to edit.</param>
  541. private void StartEdit(int rowIdx)
  542. {
  543. object key = GetKey(rowIdx);
  544. editKey = SerializableUtility.Clone(key);
  545. editValue = SerializableUtility.Clone(GetValue(key));
  546. editOriginalKey = key;
  547. editRowIdx = rowIdx;
  548. rows[rowIdx].EditMode = true;
  549. guiChildLayout.Active = rows.Count > 0 && isExpanded;
  550. }
  551. /// <summary>
  552. /// Starts an add operation. Adds a new key/value pair and allows the user to set them up in a temporary row
  553. /// before inserting them into the dictionary. Caller must ensure no edit operation is already in progress.
  554. /// </summary>
  555. private void StartAdd()
  556. {
  557. editKey = CreateKey();
  558. editValue = CreateValue();
  559. editOriginalKey = null;
  560. editRowIdx = rows.Count;
  561. editRow.Enabled = true;
  562. editRow.EditMode = true;
  563. ToggleFoldout(isExpanded);
  564. }
  565. /// <summary>
  566. /// Starts a clone operation. Adds a new key/value pair by cloning an existing one. Allows the user to modify the
  567. /// new pair in a temporary row before inserting them into the dictionary. Caller must ensure no edit operation is
  568. /// already in progress.
  569. /// </summary>
  570. /// <param name="rowIdx">Sequential row index of the entry to clone.</param>
  571. private void StartClone(int rowIdx)
  572. {
  573. object key = GetKey(rowIdx);
  574. editKey = SerializableUtility.Clone(key);
  575. editValue = SerializableUtility.Clone(GetValue(key));
  576. editOriginalKey = null;
  577. editRowIdx = rows.Count;
  578. editRow.Enabled = true;
  579. editRow.EditMode = true;
  580. ToggleFoldout(isExpanded);
  581. }
  582. /// <summary>
  583. /// Attempts to apply any changes made to the currently edited row.
  584. /// </summary>
  585. /// <returns>True if the changes were successfully applied, false if the new key already exists in the dictionary.
  586. /// </returns>
  587. private bool ApplyChanges()
  588. {
  589. if (!IsEditInProgress())
  590. return true;
  591. if (Contains(editKey) && (editOriginalKey == null || !editOriginalKey.Equals(editKey)))
  592. {
  593. DialogBox.Open(
  594. new LocEdString("Key already exists."),
  595. new LocEdString("Cannot add a key \"" + editKey + "\" to dictionary. Key already exists"),
  596. DialogBox.Type.OK);
  597. return false;
  598. }
  599. else
  600. {
  601. if (IsTemporaryRow(editRowIdx))
  602. {
  603. editRow.EditMode = false;
  604. editRow.Enabled = false;
  605. }
  606. else
  607. {
  608. rows[editRowIdx].EditMode = false;
  609. }
  610. // Add/remove the entry, but ensure the rows keep referencing the original keys (dictionaries have undefined
  611. // order so we need to compare old vs. new elements to determine if any changed).
  612. int oldNumRows = GetNumRows();
  613. Dictionary<object, int> oldKeys = new Dictionary<object, int>();
  614. for (int i = 0; i < oldNumRows; i++)
  615. oldKeys.Add(GetKey(i), i);
  616. if (editOriginalKey != null) // Editing
  617. EditEntry(editOriginalKey, editKey, editValue);
  618. else // Adding/Cloning
  619. AddEntry(editKey, editValue);
  620. int newNumRows = GetNumRows();
  621. Dictionary<object, int> newKeys = new Dictionary<object, int>();
  622. for (int i = 0; i < newNumRows; i++)
  623. newKeys.Add(GetKey(i), i);
  624. // Hidden dependency: Initialize must be called after all elements are
  625. // in the dictionary so we do it in two steps
  626. for (int i = oldNumRows; i < newNumRows; i++)
  627. rows[i] = CreateRow();
  628. for (int i = oldNumRows; i < newNumRows; i++)
  629. rows[i].Initialize(this, guiContentLayout, i, depth + 1);
  630. foreach (var KVP in oldKeys)
  631. {
  632. int newRowIdx;
  633. if (newKeys.TryGetValue(KVP.Key, out newRowIdx))
  634. {
  635. if (KVP.Value != newRowIdx)
  636. {
  637. GUIDictionaryFieldRow temp = rows[KVP.Value];
  638. rows[KVP.Value] = rows[newRowIdx];
  639. rows[newRowIdx] = temp;
  640. }
  641. }
  642. }
  643. for (int i = oldNumRows; i >= newNumRows; i--)
  644. {
  645. rows[i].Destroy();
  646. rows.Remove(i);
  647. }
  648. editRow.SetIndex(newNumRows);
  649. editKey = CreateKey();
  650. editValue = CreateValue();
  651. editOriginalKey = null;
  652. editRowIdx = -1;
  653. ToggleFoldout(isExpanded);
  654. isModified = true;
  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 cloneBtn;
  880. private GUIButton deleteBtn;
  881. private GUIButton editBtn;
  882. private bool localTitleLayout;
  883. private bool enabled = true;
  884. private bool editMode = false;
  885. private GUIDictionaryFieldBase parent;
  886. private int rowIdx;
  887. private int depth;
  888. private InspectableState modifiedState;
  889. /// <summary>
  890. /// Returns the depth at which the row is rendered.
  891. /// </summary>
  892. protected int Depth { get { return depth; } }
  893. /// <summary>
  894. /// Determines is the row currently being displayed.
  895. /// </summary>
  896. internal bool Enabled
  897. {
  898. get { return enabled; }
  899. set { enabled = value; rowLayout.Active = value; }
  900. }
  901. /// <summary>
  902. /// Enables or disables the row's edit mode. This determines what type of buttons are shown on the row title bar.
  903. /// </summary>
  904. internal bool EditMode
  905. {
  906. set
  907. {
  908. if (value)
  909. {
  910. GUIContent cancelIcon = new GUIContent(EditorBuiltin.GetInspectorWindowIcon(InspectorWindowIcon.Cancel));
  911. GUIContent applyIcon = new GUIContent(EditorBuiltin.GetInspectorWindowIcon(InspectorWindowIcon.Apply));
  912. deleteBtn.SetContent(cancelIcon);
  913. editBtn.SetContent(applyIcon);
  914. }
  915. else
  916. {
  917. GUIContent deleteIcon = new GUIContent(EditorBuiltin.GetInspectorWindowIcon(InspectorWindowIcon.Delete));
  918. GUIContent editIcon = new GUIContent(EditorBuiltin.GetInspectorWindowIcon(InspectorWindowIcon.Edit));
  919. deleteBtn.SetContent(deleteIcon);
  920. editBtn.SetContent(editIcon);
  921. }
  922. editMode = value;
  923. OnEditModeChanged(value);
  924. }
  925. }
  926. /// <summary>
  927. /// Constructs a new dictionary row object.
  928. /// </summary>
  929. protected GUIDictionaryFieldRow()
  930. {
  931. }
  932. /// <summary>
  933. /// Initializes the row and creates row GUI elements.
  934. /// </summary>
  935. /// <param name="parent">Parent array GUI object that the entry is contained in.</param>
  936. /// <param name="parentLayout">Parent layout that row GUI elements will be added to.</param>
  937. /// <param name="rowIdx">Sequential index of the row.</param>
  938. /// <param name="depth">Determines the depth at which the element is rendered.</param>
  939. internal void Initialize(GUIDictionaryFieldBase parent, GUILayout parentLayout, int rowIdx, int depth)
  940. {
  941. this.parent = parent;
  942. this.rowIdx = rowIdx;
  943. this.depth = depth;
  944. rowLayout = parentLayout.AddLayoutY();
  945. keyRowLayout = rowLayout.AddLayoutX();
  946. keyLayout = keyRowLayout.AddLayoutY();
  947. valueLayout = rowLayout.AddLayoutY();
  948. BuildGUI();
  949. }
  950. /// <summary>
  951. /// Changes the index of the dictionary element this row represents.
  952. /// </summary>
  953. /// <param name="seqIndex">Sequential index of the dictionary entry.</param>
  954. internal void SetIndex(int seqIndex)
  955. {
  956. this.rowIdx = seqIndex;
  957. }
  958. /// <summary>
  959. /// (Re)creates all row GUI elements.
  960. /// </summary>
  961. internal protected void BuildGUI()
  962. {
  963. keyLayout.Clear();
  964. valueLayout.Clear();
  965. GUILayoutX externalTitleLayout = CreateKeyGUI(keyLayout);
  966. CreateValueGUI(valueLayout);
  967. if (localTitleLayout || (titleLayout != null && titleLayout == externalTitleLayout))
  968. return;
  969. if (externalTitleLayout != null)
  970. {
  971. localTitleLayout = false;
  972. titleLayout = externalTitleLayout;
  973. }
  974. else
  975. {
  976. GUILayoutY buttonCenter = keyRowLayout.AddLayoutY();
  977. buttonCenter.AddFlexibleSpace();
  978. titleLayout = buttonCenter.AddLayoutX();
  979. buttonCenter.AddFlexibleSpace();
  980. localTitleLayout = true;
  981. }
  982. GUIContent cloneIcon = new GUIContent(EditorBuiltin.GetInspectorWindowIcon(InspectorWindowIcon.Clone));
  983. GUIContent deleteIcon = new GUIContent(EditorBuiltin.GetInspectorWindowIcon(InspectorWindowIcon.Delete));
  984. GUIContent editIcon = new GUIContent(EditorBuiltin.GetInspectorWindowIcon(InspectorWindowIcon.Edit));
  985. cloneBtn = new GUIButton(cloneIcon, GUIOption.FixedWidth(30));
  986. deleteBtn = new GUIButton(deleteIcon, GUIOption.FixedWidth(30));
  987. editBtn = new GUIButton(editIcon, GUIOption.FixedWidth(30));
  988. cloneBtn.OnClick += () => parent.OnCloneButtonClicked(rowIdx);
  989. deleteBtn.OnClick += () => parent.OnDeleteButtonClicked(rowIdx);
  990. editBtn.OnClick += () => parent.OnEditButtonClicked(rowIdx);
  991. titleLayout.AddElement(cloneBtn);
  992. titleLayout.AddElement(deleteBtn);
  993. titleLayout.AddSpace(10);
  994. titleLayout.AddElement(editBtn);
  995. EditMode = editMode;
  996. }
  997. /// <summary>
  998. /// Creates GUI elements specific to type in the key portion of a dictionary entry.
  999. /// </summary>
  1000. /// <param name="layout">Layout to insert the row GUI elements to.</param>
  1001. /// <returns>An optional title bar layout that the standard dictionary buttons will be appended to.</returns>
  1002. protected abstract GUILayoutX CreateKeyGUI(GUILayoutY layout);
  1003. /// <summary>
  1004. /// Creates GUI elements specific to type in the key portion of a dictionary entry.
  1005. /// </summary>
  1006. /// <param name="layout">Layout to insert the row GUI elements to.</param>
  1007. protected abstract void CreateValueGUI(GUILayoutY layout);
  1008. /// <summary>
  1009. /// Triggered when a GUI rows enters or leaves edit mode. Allows the row GUI to be updated accordingly.
  1010. /// </summary>
  1011. /// <param name="editMode">True if the edit mode is being enabled, false otherwise.</param>
  1012. protected virtual void OnEditModeChanged(bool editMode) { }
  1013. /// <summary>
  1014. /// Refreshes the GUI for the dictionary row and checks if anything was modified.
  1015. /// </summary>
  1016. /// <returns>State representing was anything modified between two last calls to <see cref="Refresh"/>.</returns>
  1017. internal protected virtual InspectableState Refresh()
  1018. {
  1019. InspectableState oldState = modifiedState;
  1020. if (modifiedState.HasFlag(InspectableState.ModifiedConfirm))
  1021. modifiedState = InspectableState.NotModified;
  1022. return oldState;
  1023. }
  1024. /// <summary>
  1025. /// Marks the contents of the row as modified.
  1026. /// </summary>
  1027. protected void MarkAsModified()
  1028. {
  1029. modifiedState |= InspectableState.Modified;
  1030. }
  1031. /// <summary>
  1032. /// Confirms any queued modifications, signaling parent elements.
  1033. /// </summary>
  1034. protected void ConfirmModify()
  1035. {
  1036. if (modifiedState.HasFlag(InspectableState.Modified))
  1037. modifiedState |= InspectableState.ModifiedConfirm;
  1038. }
  1039. /// <summary>
  1040. /// Gets the key contained in this dictionary's row.
  1041. /// </summary>
  1042. /// <typeparam name="T">Type of the key. Must match the dictionary's element type.</typeparam>
  1043. /// <returns>Key in this dictionary's row.</returns>
  1044. protected T GetKey<T>()
  1045. {
  1046. return (T)parent.GetKeyInternal(rowIdx);
  1047. }
  1048. /// <summary>
  1049. /// Sets the key for in this dictionary's row.
  1050. /// </summary>
  1051. /// <typeparam name="T">Type of the key. Must match the dictionary's element type.</typeparam>
  1052. /// <param name="key">Key to assign to this row.</param>
  1053. protected void SetKey<T>(T key)
  1054. {
  1055. parent.SetKey(rowIdx, key);
  1056. }
  1057. /// <summary>
  1058. /// Gets the value contained in this dictionary's row.
  1059. /// </summary>
  1060. /// <typeparam name="T">Type of the value. Must match the dictionary's element type.</typeparam>
  1061. /// <returns>Value in this dictionary's row.</returns>
  1062. protected T GetValue<T>()
  1063. {
  1064. return (T)parent.GetValueInternal(rowIdx);
  1065. }
  1066. /// <summary>
  1067. /// Sets the value contained in this dictionary's row.
  1068. /// </summary>
  1069. /// <typeparam name="T">Type of the value. Must match the dictionary's element type.</typeparam>
  1070. /// <param name="value">Value to set.</param>
  1071. protected void SetValue<T>(T value)
  1072. {
  1073. parent.SetValueInternal(rowIdx, value);
  1074. }
  1075. /// <summary>
  1076. /// Destroys all row GUI elements.
  1077. /// </summary>
  1078. public void Destroy()
  1079. {
  1080. if (rowLayout != null)
  1081. {
  1082. rowLayout.Destroy();
  1083. rowLayout = null;
  1084. }
  1085. keyRowLayout = null;
  1086. keyLayout = null;
  1087. valueLayout = null;
  1088. titleLayout = null;
  1089. cloneBtn = null;
  1090. deleteBtn = null;
  1091. editBtn = null;
  1092. localTitleLayout = false;
  1093. }
  1094. }
  1095. }