GUIDictionaryField.cs 47 KB

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