GUIDictionaryField.cs 45 KB

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