GUIDictionaryField.cs 47 KB

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