GUIDictionaryField.cs 45 KB

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