GUIDictionaryField.cs 45 KB

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