2
0

GUIDictionaryField.cs 47 KB

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