GUIDictionaryField.cs 47 KB

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