GUIDictionaryField.cs 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289
  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. /// Creates a brand new dictionary with zero elements in the place of the current dictionary.
  352. /// </summary>
  353. protected abstract void CreateDictionary();
  354. /// <summary>
  355. /// Deletes the current dictionary object.
  356. /// </summary>
  357. protected abstract void DeleteDictionary();
  358. /// <summary>
  359. /// Hides or shows the dictionary rows.
  360. /// </summary>
  361. /// <param name="expanded">True if the rows should be displayed, false otherwise.</param>
  362. private void ToggleFoldout(bool expanded)
  363. {
  364. isExpanded = expanded;
  365. if (guiChildLayout != null)
  366. guiChildLayout.Active = isExpanded && (rows.Count > 0 || IsEditInProgress());
  367. }
  368. /// <summary>
  369. /// Triggered when the user clicks on the create button on the title bar. Creates a brand new dictionary with zero
  370. /// elements in the place of the current dictionary.
  371. /// </summary>
  372. protected void OnCreateButtonClicked()
  373. {
  374. CreateDictionary();
  375. UpdateHeaderGUI();
  376. editRow.Initialize(this, guiContentLayout, 0, depth + 1);
  377. editRow.Enabled = false;
  378. isModified = true;
  379. }
  380. /// <summary>
  381. /// Triggered when the user clicks on the add button on the title bar. Adds a new empty element to the dictionary.
  382. /// </summary>
  383. protected virtual void OnAddButtonClicked()
  384. {
  385. if (IsEditInProgress())
  386. {
  387. DialogBox.Open(
  388. new LocEdString("Edit in progress."),
  389. new LocEdString("You are editing the entry with key \"" + editKey + "\". You cannot add a row " +
  390. "before applying or discarding those changes. Do you wish to apply those changes first?"),
  391. DialogBox.Type.YesNoCancel,
  392. x =>
  393. {
  394. switch (x)
  395. {
  396. case DialogBox.ResultType.Yes:
  397. if (ApplyChanges())
  398. StartAdd();
  399. break;
  400. case DialogBox.ResultType.No:
  401. DiscardChanges();
  402. StartAdd();
  403. break;
  404. }
  405. });
  406. }
  407. else
  408. {
  409. if (!isExpanded)
  410. ToggleFoldout(true);
  411. StartAdd();
  412. }
  413. }
  414. /// <summary>
  415. /// Triggered when the user clicks on the clear button on the title bar. Deletes the current dictionary object.
  416. /// </summary>
  417. protected void OnClearButtonClicked()
  418. {
  419. DeleteDictionary();
  420. UpdateHeaderGUI();
  421. ClearRows();
  422. isModified = true;
  423. }
  424. /// <summary>
  425. /// Triggered when the user clicks on the delete button next to a dictionary entry. Deletes an element in the
  426. /// dictionary.
  427. /// </summary>
  428. /// <param name="rowIdx">Sequential row index of the entry that was clicked.</param>
  429. protected internal virtual void OnDeleteButtonClicked(int rowIdx)
  430. {
  431. if (IsEditInProgress())
  432. DiscardChanges();
  433. else
  434. {
  435. // Remove the entry, but ensure the rows keep referencing the original keys (dictionaries have undefined
  436. // order so we need to compare old vs. new elements to determine if any changed).
  437. int oldNumRows = GetNumRows();
  438. Dictionary<object, int> oldKeys = new Dictionary<object, int>();
  439. for (int i = 0; i < oldNumRows; i++)
  440. oldKeys.Add(GetKey(i), i);
  441. RemoveEntry(GetKey(rowIdx));
  442. int newNumRows = GetNumRows();
  443. Dictionary<object, int> newKeys = new Dictionary<object, int>();
  444. for (int i = 0; i < newNumRows; i++)
  445. newKeys.Add(GetKey(i), i);
  446. foreach (var KVP in oldKeys)
  447. {
  448. int newRowIdx;
  449. if (newKeys.TryGetValue(KVP.Key, out newRowIdx))
  450. {
  451. if (KVP.Value != newRowIdx)
  452. {
  453. GUIDictionaryFieldRow temp = rows[KVP.Value];
  454. temp.SetIndex(newRowIdx);
  455. rows[newRowIdx].SetIndex(KVP.Value);
  456. rows[KVP.Value] = rows[newRowIdx];
  457. rows[newRowIdx] = temp;
  458. }
  459. }
  460. }
  461. for (int i = oldNumRows - 1; i >= newNumRows; i--)
  462. {
  463. rows[i].Destroy();
  464. rows.Remove(i);
  465. }
  466. editRow.SetIndex(newNumRows);
  467. isModified = true;
  468. }
  469. }
  470. /// <summary>
  471. /// Triggered when the user clicks on the clone button next to a dictionary entry. Clones an element and
  472. /// adds the clone to the dictionary.
  473. /// </summary>
  474. /// <param name="rowIdx">Sequential row index of the entry that was clicked.</param>
  475. protected internal virtual void OnCloneButtonClicked(int rowIdx)
  476. {
  477. if (IsEditInProgress())
  478. {
  479. DialogBox.Open(
  480. new LocEdString("Edit in progress."),
  481. new LocEdString("You are editing the entry with key \"" + editKey + "\". You cannot clone a row " +
  482. "before applying or discarding those changes. Do you wish to apply those changes first?"),
  483. DialogBox.Type.YesNoCancel,
  484. x =>
  485. {
  486. switch (x)
  487. {
  488. case DialogBox.ResultType.Yes:
  489. if (ApplyChanges())
  490. StartClone(rowIdx);
  491. break;
  492. case DialogBox.ResultType.No:
  493. DiscardChanges();
  494. StartClone(rowIdx);
  495. break;
  496. }
  497. });
  498. }
  499. else
  500. StartClone(rowIdx);
  501. }
  502. /// <summary>
  503. /// Triggered when user clicks the edit or apply (depending on state) button next to the dictionary entry. Starts
  504. /// edit mode for the element, if not already in edit mode. Applies edit mode changes if already in edit mode.
  505. /// </summary>
  506. /// <param name="rowIdx">Sequential row index of the entry that was clicked.</param>
  507. protected internal virtual void OnEditButtonClicked(int rowIdx)
  508. {
  509. if (editRowIdx == rowIdx)
  510. ApplyChanges();
  511. else
  512. {
  513. if (IsEditInProgress())
  514. {
  515. DialogBox.Open(
  516. new LocEdString("Edit in progress."),
  517. new LocEdString("You are already editing the entry with key \"" + editKey + "\". You cannot edit " +
  518. "another row before applying or discarding those changes. Do you wish to apply those changes first?"),
  519. DialogBox.Type.YesNoCancel,
  520. x =>
  521. {
  522. switch (x)
  523. {
  524. case DialogBox.ResultType.Yes:
  525. if (ApplyChanges())
  526. StartEdit(rowIdx);
  527. break;
  528. case DialogBox.ResultType.No:
  529. DiscardChanges();
  530. StartEdit(rowIdx);
  531. break;
  532. }
  533. });
  534. }
  535. else
  536. StartEdit(rowIdx);
  537. }
  538. }
  539. /// <summary>
  540. /// Starts an edit operation on a row with the specified key. Allows the user to change the key of the specified row.
  541. /// Caller must ensure no edit operation is already in progress.
  542. /// </summary>
  543. /// <param name="rowIdx">Sequential row index of the entry to edit.</param>
  544. private void StartEdit(int rowIdx)
  545. {
  546. object key = GetKey(rowIdx);
  547. editKey = SerializableUtility.Clone(key);
  548. editValue = SerializableUtility.Clone(GetValue(key));
  549. editOriginalKey = key;
  550. editRowIdx = rowIdx;
  551. rows[rowIdx].EditMode = true;
  552. guiChildLayout.Active = rows.Count > 0 && isExpanded;
  553. }
  554. /// <summary>
  555. /// Starts an add operation. Adds a new key/value pair and allows the user to set them up in a temporary row
  556. /// before inserting them into the dictionary. Caller must ensure no edit operation is already in progress.
  557. /// </summary>
  558. private void StartAdd()
  559. {
  560. editKey = CreateKey();
  561. editValue = CreateValue();
  562. editOriginalKey = null;
  563. editRowIdx = rows.Count;
  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. object key = GetKey(rowIdx);
  577. editKey = SerializableUtility.Clone(key);
  578. editValue = SerializableUtility.Clone(GetValue(key));
  579. editOriginalKey = null;
  580. editRowIdx = rows.Count;
  581. editRow.Enabled = true;
  582. editRow.EditMode = true;
  583. ToggleFoldout(isExpanded);
  584. }
  585. /// <summary>
  586. /// Attempts to apply any changes made to the currently edited row.
  587. /// </summary>
  588. /// <returns>True if the changes were successfully applied, false if the new key already exists in the dictionary.
  589. /// </returns>
  590. private bool ApplyChanges()
  591. {
  592. if (!IsEditInProgress())
  593. return true;
  594. if (Contains(editKey) && (editOriginalKey == null || !editOriginalKey.Equals(editKey)))
  595. {
  596. DialogBox.Open(
  597. new LocEdString("Key already exists."),
  598. new LocEdString("Cannot add a key \"" + editKey + "\" to dictionary. Key already exists"),
  599. DialogBox.Type.OK);
  600. return false;
  601. }
  602. else
  603. {
  604. if (IsTemporaryRow(editRowIdx))
  605. {
  606. editRow.EditMode = false;
  607. editRow.Enabled = false;
  608. }
  609. else
  610. {
  611. rows[editRowIdx].EditMode = false;
  612. }
  613. // Add/remove the entry, but ensure the rows keep referencing the original keys (dictionaries have undefined
  614. // order so we need to compare old vs. new elements to determine if any changed).
  615. int oldNumRows = GetNumRows();
  616. Dictionary<object, int> oldKeys = new Dictionary<object, int>();
  617. for (int i = 0; i < oldNumRows; i++)
  618. oldKeys.Add(GetKey(i), i);
  619. if (editOriginalKey != null) // Editing
  620. EditEntry(editOriginalKey, editKey, editValue);
  621. else // Adding/Cloning
  622. AddEntry(editKey, editValue);
  623. int newNumRows = GetNumRows();
  624. Dictionary<object, int> newKeys = new Dictionary<object, int>();
  625. for (int i = 0; i < newNumRows; i++)
  626. newKeys.Add(GetKey(i), i);
  627. // Hidden dependency: Initialize must be called after all elements are
  628. // in the dictionary so we do it in two steps
  629. for (int i = oldNumRows; i < newNumRows; i++)
  630. rows[i] = CreateRow();
  631. for (int i = oldNumRows; i < newNumRows; i++)
  632. rows[i].Initialize(this, guiContentLayout, i, depth + 1);
  633. foreach (var KVP in oldKeys)
  634. {
  635. int newRowIdx;
  636. if (newKeys.TryGetValue(KVP.Key, out newRowIdx))
  637. {
  638. if (KVP.Value != newRowIdx)
  639. {
  640. GUIDictionaryFieldRow temp = rows[KVP.Value];
  641. temp.SetIndex(newRowIdx);
  642. rows[newRowIdx].SetIndex(KVP.Value);
  643. rows[KVP.Value] = rows[newRowIdx];
  644. rows[newRowIdx] = temp;
  645. }
  646. }
  647. }
  648. for (int i = oldNumRows - 1; i >= newNumRows; i--)
  649. {
  650. rows[i].Destroy();
  651. rows.Remove(i);
  652. }
  653. editRow.SetIndex(newNumRows);
  654. editKey = CreateKey();
  655. editValue = CreateValue();
  656. editOriginalKey = null;
  657. editRowIdx = -1;
  658. ToggleFoldout(isExpanded);
  659. isModified = true;
  660. return true;
  661. }
  662. }
  663. /// <summary>
  664. /// Cancels any changes made on the currently edited row.
  665. /// </summary>
  666. private void DiscardChanges()
  667. {
  668. if (IsEditInProgress())
  669. {
  670. if (IsTemporaryRow(editRowIdx))
  671. {
  672. editRow.EditMode = false;
  673. editRow.Enabled = false;
  674. }
  675. else
  676. {
  677. rows[editRowIdx].EditMode = false;
  678. }
  679. editKey = CreateKey();
  680. editValue = CreateValue();
  681. editOriginalKey = null;
  682. editRow.Enabled = false;
  683. editRowIdx = -1;
  684. ToggleFoldout(isExpanded);
  685. }
  686. }
  687. /// <summary>
  688. /// Possible states dictionary GUI can be in.
  689. /// </summary>
  690. private enum State
  691. {
  692. None,
  693. Empty,
  694. Filled
  695. }
  696. }
  697. /// <summary>
  698. /// Creates GUI elements that allow viewing and manipulation of a <see cref="Dictionary{TKey,TValue}"/>. When constructing the
  699. /// object user can provide a custom type that manages GUI for individual dictionary elements.
  700. /// </summary>
  701. /// <typeparam name="Key">Type of key used by the dictionary.</typeparam>
  702. /// <typeparam name="Value">Type of value stored in the dictionary.</typeparam>
  703. /// <typeparam name="RowType">Type of rows that are used to handle GUI for individual dictionary elements.</typeparam>
  704. public class GUIDictionaryField<Key, Value, RowType> : GUIDictionaryFieldBase where RowType : GUIDictionaryFieldRow, new()
  705. {
  706. public delegate int SortDictionaryDelegate(Key a, Key b);
  707. /// <summary>
  708. /// Triggered when the reference array has been changed. This does not include changes that only happen to its
  709. /// internal elements.
  710. /// </summary>
  711. public Action<Dictionary<Key, Value>> OnChanged;
  712. /// <summary>
  713. /// Triggered when an element in the list has been added or changed.
  714. /// </summary>
  715. public Action<Key> OnValueChanged;
  716. /// <summary>
  717. /// Triggered when an element in the dictionary has been removed.
  718. /// </summary>
  719. public Action<Key> OnValueRemoved;
  720. /// <summary>
  721. /// Optional method that will be used for sorting the elements in the dictionary.
  722. /// </summary>
  723. public SortDictionaryDelegate SortMethod;
  724. /// <summary>
  725. /// Array object whose contents are displayed.
  726. /// </summary>
  727. public Dictionary<Key, Value> Dictionary { get { return dictionary; } }
  728. protected Dictionary<Key, Value> dictionary;
  729. private List<Key> orderedKeys = new List<Key>();
  730. /// <summary>
  731. /// Constructs a new dictionary GUI field.
  732. /// </summary>
  733. /// <param name="title">Label to display on the dictionary GUI title.</param>
  734. /// <param name="dictionary">Object containing the data. Can be null.</param>
  735. /// <param name="layout">Layout to which to append the list GUI elements to.</param>
  736. /// <param name="depth">Determines at which depth to render the background. Useful when you have multiple
  737. /// nested containers whose backgrounds are overlaping. Also determines background style,
  738. /// depths divisible by two will use an alternate style.</param>
  739. protected GUIDictionaryField(LocString title, Dictionary<Key, Value> dictionary, GUILayout layout, int depth = 0)
  740. : base(title, layout, depth)
  741. {
  742. this.dictionary = dictionary;
  743. UpdateKeys();
  744. }
  745. /// <summary>
  746. /// Creates a dictionary GUI field containing GUI elements required for displaying the provided dictionary.
  747. /// </summary>
  748. /// <typeparam name="RowType">Type of rows that are used to handle GUI for individual dictionary elements.</typeparam>
  749. /// <param name="title">Label to display on the list GUI title.</param>
  750. /// <param name="dictionary">Object containing the data. Can be null.</param>
  751. /// <param name="layout">Layout to which to append the list GUI elements to.</param>
  752. /// <param name="depth">Determines at which depth to render the background. Useful when you have multiple
  753. /// nested containers whose backgrounds are overlaping. Also determines background style,
  754. /// depths divisible by two will use an alternate style.</param>
  755. /// <returns>New instance of dictionary GUI field.</returns>
  756. public static GUIDictionaryField<Key, Value, RowType> Create(LocString title, Dictionary<Key, Value> dictionary,
  757. GUILayout layout, int depth = 0)
  758. {
  759. GUIDictionaryField<Key, Value, RowType> guiDictionary = new GUIDictionaryField<Key, Value, RowType>(
  760. title, dictionary, layout, depth);
  761. guiDictionary.BuildGUI();
  762. return guiDictionary;
  763. }
  764. /// <summary>
  765. /// Updates the ordered set of keys used for mapping sequential indexes to keys. Should be called whenever a
  766. /// dictionary key changes.
  767. /// </summary>
  768. private void UpdateKeys()
  769. {
  770. orderedKeys.Clear();
  771. if (dictionary != null)
  772. {
  773. foreach (var KVP in dictionary)
  774. orderedKeys.Add(KVP.Key);
  775. if (SortMethod != null)
  776. orderedKeys.Sort((x,y) => SortMethod(x, y));
  777. else
  778. orderedKeys.Sort();
  779. }
  780. }
  781. /// <inheritdoc/>
  782. protected override GUIDictionaryFieldRow CreateRow()
  783. {
  784. return new RowType();
  785. }
  786. /// <inheritdoc/>
  787. protected override int GetNumRows()
  788. {
  789. if (dictionary != null)
  790. return dictionary.Count;
  791. return 0;
  792. }
  793. /// <inheritdoc/>
  794. protected override bool IsNull()
  795. {
  796. return dictionary == null;
  797. }
  798. /// <inheritdoc/>
  799. protected internal override object GetKey(int rowIdx)
  800. {
  801. return orderedKeys[rowIdx];
  802. }
  803. /// <inheritdoc/>
  804. protected internal override object GetValue(object key)
  805. {
  806. return dictionary[(Key)key];
  807. }
  808. /// <inheritdoc/>
  809. protected internal override void SetValue(object key, object value)
  810. {
  811. dictionary[(Key)key] = (Value)value;
  812. if (OnValueChanged != null)
  813. OnValueChanged((Key)key);
  814. }
  815. /// <inheritdoc/>
  816. protected internal override bool Contains(object key)
  817. {
  818. return dictionary.ContainsKey((Key)key); ;
  819. }
  820. /// <inheritdoc/>
  821. protected internal override void EditEntry(object oldKey, object newKey, object value)
  822. {
  823. dictionary.Remove((Key)oldKey);
  824. dictionary[(Key)newKey] = (Value)value;
  825. if (OnValueRemoved != null)
  826. OnValueRemoved((Key)oldKey);
  827. if (OnValueChanged != null)
  828. OnValueChanged((Key)newKey);
  829. UpdateKeys();
  830. }
  831. /// <inheritdoc/>
  832. protected internal override void AddEntry(object key, object value)
  833. {
  834. dictionary[(Key)key] = (Value)value;
  835. if (OnValueChanged != null)
  836. OnValueChanged((Key)key);
  837. UpdateKeys();
  838. }
  839. /// <inheritdoc/>
  840. protected internal override void RemoveEntry(object key)
  841. {
  842. dictionary.Remove((Key) key);
  843. if (OnValueRemoved != null)
  844. OnValueRemoved((Key)key);
  845. UpdateKeys();
  846. }
  847. /// <inheritdoc/>
  848. protected internal override object CreateKey()
  849. {
  850. return SerializableUtility.Create<Key>();
  851. }
  852. /// <inheritdoc/>
  853. protected internal override object CreateValue()
  854. {
  855. return SerializableUtility.Create<Value>();
  856. }
  857. /// <inheritdoc/>
  858. protected override void CreateDictionary()
  859. {
  860. dictionary = new Dictionary<Key, Value>();
  861. if (OnChanged != null)
  862. OnChanged(dictionary);
  863. UpdateKeys();
  864. }
  865. /// <inheritdoc/>
  866. protected override void DeleteDictionary()
  867. {
  868. dictionary = null;
  869. if (OnChanged != null)
  870. OnChanged(dictionary);
  871. UpdateKeys();
  872. }
  873. }
  874. /// <summary>
  875. /// Contains GUI elements for a single entry in a dictionary.
  876. /// </summary>
  877. public abstract class GUIDictionaryFieldRow
  878. {
  879. private GUILayoutY rowLayout;
  880. private GUILayoutX keyRowLayout;
  881. private GUILayoutY keyLayout;
  882. private GUILayoutY valueLayout;
  883. private GUILayoutX titleLayout;
  884. private GUIButton cloneBtn;
  885. private GUIButton deleteBtn;
  886. private GUIButton editBtn;
  887. private bool localTitleLayout;
  888. private bool enabled = true;
  889. private bool editMode = false;
  890. private GUIDictionaryFieldBase parent;
  891. private int rowIdx;
  892. private int depth;
  893. private InspectableState modifiedState;
  894. /// <summary>
  895. /// Returns the depth at which the row is rendered.
  896. /// </summary>
  897. protected int Depth { get { return depth; } }
  898. /// <summary>
  899. /// Determines is the row currently being displayed.
  900. /// </summary>
  901. internal bool Enabled
  902. {
  903. get { return enabled; }
  904. set { enabled = value; rowLayout.Active = value; }
  905. }
  906. /// <summary>
  907. /// Enables or disables the row's edit mode. This determines what type of buttons are shown on the row title bar.
  908. /// </summary>
  909. internal bool EditMode
  910. {
  911. set
  912. {
  913. if (value)
  914. {
  915. GUIContent cancelIcon = new GUIContent(EditorBuiltin.GetInspectorWindowIcon(InspectorWindowIcon.Cancel));
  916. GUIContent applyIcon = new GUIContent(EditorBuiltin.GetInspectorWindowIcon(InspectorWindowIcon.Apply));
  917. deleteBtn.SetContent(cancelIcon);
  918. editBtn.SetContent(applyIcon);
  919. }
  920. else
  921. {
  922. GUIContent deleteIcon = new GUIContent(EditorBuiltin.GetInspectorWindowIcon(InspectorWindowIcon.Delete));
  923. GUIContent editIcon = new GUIContent(EditorBuiltin.GetInspectorWindowIcon(InspectorWindowIcon.Edit));
  924. deleteBtn.SetContent(deleteIcon);
  925. editBtn.SetContent(editIcon);
  926. }
  927. editMode = value;
  928. OnEditModeChanged(value);
  929. }
  930. }
  931. /// <summary>
  932. /// Constructs a new dictionary row object.
  933. /// </summary>
  934. protected GUIDictionaryFieldRow()
  935. {
  936. }
  937. /// <summary>
  938. /// Initializes the row and creates row GUI elements.
  939. /// </summary>
  940. /// <param name="parent">Parent array GUI object that the entry is contained in.</param>
  941. /// <param name="parentLayout">Parent layout that row GUI elements will be added to.</param>
  942. /// <param name="rowIdx">Sequential index of the row.</param>
  943. /// <param name="depth">Determines the depth at which the element is rendered.</param>
  944. internal void Initialize(GUIDictionaryFieldBase parent, GUILayout parentLayout, int rowIdx, int depth)
  945. {
  946. this.parent = parent;
  947. this.rowIdx = rowIdx;
  948. this.depth = depth;
  949. rowLayout = parentLayout.AddLayoutY();
  950. keyRowLayout = rowLayout.AddLayoutX();
  951. keyLayout = keyRowLayout.AddLayoutY();
  952. valueLayout = rowLayout.AddLayoutY();
  953. BuildGUI();
  954. }
  955. /// <summary>
  956. /// Changes the index of the dictionary element this row represents.
  957. /// </summary>
  958. /// <param name="seqIndex">Sequential index of the dictionary entry.</param>
  959. internal void SetIndex(int seqIndex)
  960. {
  961. this.rowIdx = seqIndex;
  962. }
  963. /// <summary>
  964. /// (Re)creates all row GUI elements.
  965. /// </summary>
  966. internal protected void BuildGUI()
  967. {
  968. keyLayout.Clear();
  969. valueLayout.Clear();
  970. GUILayoutX externalTitleLayout = CreateKeyGUI(keyLayout);
  971. CreateValueGUI(valueLayout);
  972. if (localTitleLayout || (titleLayout != null && titleLayout == externalTitleLayout))
  973. return;
  974. if (externalTitleLayout != null)
  975. {
  976. localTitleLayout = false;
  977. titleLayout = externalTitleLayout;
  978. }
  979. else
  980. {
  981. GUILayoutY buttonCenter = keyRowLayout.AddLayoutY();
  982. buttonCenter.AddFlexibleSpace();
  983. titleLayout = buttonCenter.AddLayoutX();
  984. buttonCenter.AddFlexibleSpace();
  985. localTitleLayout = true;
  986. }
  987. GUIContent cloneIcon = new GUIContent(EditorBuiltin.GetInspectorWindowIcon(InspectorWindowIcon.Clone));
  988. GUIContent deleteIcon = new GUIContent(EditorBuiltin.GetInspectorWindowIcon(InspectorWindowIcon.Delete));
  989. GUIContent editIcon = new GUIContent(EditorBuiltin.GetInspectorWindowIcon(InspectorWindowIcon.Edit));
  990. cloneBtn = new GUIButton(cloneIcon, GUIOption.FixedWidth(30));
  991. deleteBtn = new GUIButton(deleteIcon, GUIOption.FixedWidth(30));
  992. editBtn = new GUIButton(editIcon, GUIOption.FixedWidth(30));
  993. cloneBtn.OnClick += () => parent.OnCloneButtonClicked(rowIdx);
  994. deleteBtn.OnClick += () => parent.OnDeleteButtonClicked(rowIdx);
  995. editBtn.OnClick += () => parent.OnEditButtonClicked(rowIdx);
  996. titleLayout.AddElement(cloneBtn);
  997. titleLayout.AddElement(deleteBtn);
  998. titleLayout.AddSpace(10);
  999. titleLayout.AddElement(editBtn);
  1000. EditMode = editMode;
  1001. }
  1002. /// <summary>
  1003. /// Creates GUI elements specific to type in the key portion of a dictionary entry.
  1004. /// </summary>
  1005. /// <param name="layout">Layout to insert the row GUI elements to.</param>
  1006. /// <returns>An optional title bar layout that the standard dictionary buttons will be appended to.</returns>
  1007. protected abstract GUILayoutX CreateKeyGUI(GUILayoutY layout);
  1008. /// <summary>
  1009. /// Creates GUI elements specific to type in the key portion of a dictionary entry.
  1010. /// </summary>
  1011. /// <param name="layout">Layout to insert the row GUI elements to.</param>
  1012. protected abstract void CreateValueGUI(GUILayoutY layout);
  1013. /// <summary>
  1014. /// Triggered when a GUI rows enters or leaves edit mode. Allows the row GUI to be updated accordingly.
  1015. /// </summary>
  1016. /// <param name="editMode">True if the edit mode is being enabled, false otherwise.</param>
  1017. protected virtual void OnEditModeChanged(bool editMode) { }
  1018. /// <summary>
  1019. /// Refreshes the GUI for the dictionary row and checks if anything was modified.
  1020. /// </summary>
  1021. /// <returns>State representing was anything modified between two last calls to <see cref="Refresh"/>.</returns>
  1022. internal protected virtual InspectableState Refresh()
  1023. {
  1024. InspectableState oldState = modifiedState;
  1025. if (modifiedState.HasFlag(InspectableState.Modified))
  1026. modifiedState = InspectableState.NotModified;
  1027. return oldState;
  1028. }
  1029. /// <summary>
  1030. /// Marks the contents of the row as modified.
  1031. /// </summary>
  1032. protected void MarkAsModified()
  1033. {
  1034. modifiedState |= InspectableState.ModifyInProgress;
  1035. }
  1036. /// <summary>
  1037. /// Confirms any queued modifications, signaling parent elements.
  1038. /// </summary>
  1039. protected void ConfirmModify()
  1040. {
  1041. if (modifiedState.HasFlag(InspectableState.ModifyInProgress))
  1042. modifiedState |= InspectableState.Modified;
  1043. }
  1044. /// <summary>
  1045. /// Gets the key contained in this dictionary's row.
  1046. /// </summary>
  1047. /// <typeparam name="T">Type of the key. Must match the dictionary's element type.</typeparam>
  1048. /// <returns>Key in this dictionary's row.</returns>
  1049. protected T GetKey<T>()
  1050. {
  1051. return (T)parent.GetKeyInternal(rowIdx);
  1052. }
  1053. /// <summary>
  1054. /// Sets the key for in this dictionary's row.
  1055. /// </summary>
  1056. /// <typeparam name="T">Type of the key. Must match the dictionary's element type.</typeparam>
  1057. /// <param name="key">Key to assign to this row.</param>
  1058. protected void SetKey<T>(T key)
  1059. {
  1060. parent.SetKey(rowIdx, key);
  1061. }
  1062. /// <summary>
  1063. /// Gets the value contained in this dictionary's row.
  1064. /// </summary>
  1065. /// <typeparam name="T">Type of the value. Must match the dictionary's element type.</typeparam>
  1066. /// <returns>Value in this dictionary's row.</returns>
  1067. protected T GetValue<T>()
  1068. {
  1069. return (T)parent.GetValueInternal(rowIdx);
  1070. }
  1071. /// <summary>
  1072. /// Sets the value contained in this dictionary's row.
  1073. /// </summary>
  1074. /// <typeparam name="T">Type of the value. Must match the dictionary's element type.</typeparam>
  1075. /// <param name="value">Value to set.</param>
  1076. protected void SetValue<T>(T value)
  1077. {
  1078. parent.SetValueInternal(rowIdx, value);
  1079. }
  1080. /// <summary>
  1081. /// Destroys all row GUI elements.
  1082. /// </summary>
  1083. public void Destroy()
  1084. {
  1085. if (rowLayout != null)
  1086. {
  1087. rowLayout.Destroy();
  1088. rowLayout = null;
  1089. }
  1090. keyRowLayout = null;
  1091. keyLayout = null;
  1092. valueLayout = null;
  1093. titleLayout = null;
  1094. cloneBtn = null;
  1095. deleteBtn = null;
  1096. editBtn = null;
  1097. localTitleLayout = false;
  1098. }
  1099. }
  1100. }