説明なし
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

GridView.cs 48KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Collections.Specialized;
  5. using System.Linq;
  6. using UnityEngine;
  7. using UnityEngine.UIElements;
  8. namespace UnityEditor.Tilemaps.External
  9. {
  10. /// <summary>
  11. /// A view containing recycled rows with items inside.
  12. /// </summary>
  13. [UxmlElement]
  14. internal partial class GridView : BindableElement, ISerializationCallbackReceiver
  15. {
  16. const int k_ExtraVisibleRows = 2;
  17. /// <summary>
  18. /// The USS class name for GridView elements.
  19. /// </summary>
  20. /// <remarks>
  21. /// Unity adds this USS class to every instance of the GridView element. Any styling applied to
  22. /// this class affects every GridView located beside, or below the stylesheet in the visual tree.
  23. /// </remarks>
  24. const string k_UssClassName = "unity-grid-view";
  25. /// <summary>
  26. /// The USS class name for GridView elements with a border.
  27. /// </summary>
  28. /// <remarks>
  29. /// Unity adds this USS class to an instance of the GridView element if the instance's
  30. /// <see cref="GridView.showBorder"/> property is set to true. Any styling applied to this class
  31. /// affects every such GridView located beside, or below the stylesheet in the visual tree.
  32. /// </remarks>
  33. const string k_BorderUssClassName = k_UssClassName + "--with-border";
  34. /// <summary>
  35. /// The USS class name of item elements in GridView elements.
  36. /// </summary>
  37. /// <remarks>
  38. /// Unity adds this USS class to every item element the GridView contains. Any styling applied to
  39. /// this class affects every item element located beside, or below the stylesheet in the visual tree.
  40. /// </remarks>
  41. const string k_ItemUssClassName = k_UssClassName + "__item";
  42. /// <summary>
  43. /// The USS class name of selected item elements in the GridView.
  44. /// </summary>
  45. /// <remarks>
  46. /// Unity adds this USS class to every selected element in the GridView. The <see cref="GridView.selectionType"/>
  47. /// property decides if zero, one, or more elements can be selected. Any styling applied to
  48. /// this class affects every GridView item located beside, or below the stylesheet in the visual tree.
  49. /// </remarks>
  50. internal const string itemSelectedVariantUssClassName = k_ItemUssClassName + "--selected";
  51. /// <summary>
  52. /// The USS class name of rows in the GridView.
  53. /// </summary>
  54. const string k_RowUssClassName = k_UssClassName + "__row";
  55. const int k_DefaultItemHeight = 30;
  56. static CustomStyleProperty<int> s_ItemHeightProperty = new CustomStyleProperty<int>("--unity-item-height");
  57. internal readonly ScrollView scrollView;
  58. readonly List<int> m_SelectedIds = new List<int>();
  59. readonly List<int> m_SelectedIndices = new List<int>();
  60. readonly List<object> m_SelectedItems = new List<object>();
  61. Action<VisualElement, int> m_BindItem;
  62. int m_ColumnCount = 1;
  63. int m_FirstVisibleIndex;
  64. Func<int, int> m_GetItemId;
  65. int m_ItemHeight = k_DefaultItemHeight;
  66. bool m_ItemHeightIsInline;
  67. IList m_ItemsSource;
  68. float m_LastHeight;
  69. Func<VisualElement> m_MakeItem;
  70. int m_RangeSelectionOrigin = -1;
  71. List<RecycledRow> m_RowPool = new List<RecycledRow>();
  72. // we keep this list in order to minimize temporary gc allocs
  73. List<RecycledRow> m_ScrollInsertionList = new List<RecycledRow>();
  74. // Persisted.
  75. float m_ScrollOffset;
  76. SelectionType m_SelectionType;
  77. Vector3 m_TouchDownPosition;
  78. long m_TouchDownTime;
  79. int m_VisibleRowCount;
  80. /// <summary>
  81. /// Creates a <see cref="GridView"/> with all default properties. The <see cref="GridView.itemsSource"/>,
  82. /// <see cref="GridView.itemHeight"/>, <see cref="GridView.makeItem"/> and <see cref="GridView.bindItem"/> properties
  83. /// must all be set for the GridView to function properly.
  84. /// </summary>
  85. public GridView()
  86. {
  87. AddStyleSheetPath("Packages/com.unity.2d.tilemap/Editor/UI/External/GridView.uss");
  88. AddToClassList(k_UssClassName);
  89. selectionType = SelectionType.Multiple;
  90. m_ScrollOffset = 0.0f;
  91. scrollView = new ScrollView { viewDataKey = "grid-view__scroll-view" };
  92. scrollView.StretchToParentSize();
  93. scrollView.verticalScroller.valueChanged += OnScroll;
  94. RegisterCallback<GeometryChangedEvent>(OnSizeChanged);
  95. RegisterCallback<CustomStyleResolvedEvent>(OnCustomStyleResolved);
  96. scrollView.contentContainer.RegisterCallback<AttachToPanelEvent>(OnAttachToPanel);
  97. scrollView.contentContainer.RegisterCallback<DetachFromPanelEvent>(OnDetachFromPanel);
  98. hierarchy.Add(scrollView);
  99. scrollView.contentContainer.focusable = true;
  100. scrollView.contentContainer.usageHints &= ~UsageHints.GroupTransform; // Scroll views with virtualized content shouldn't have the "view transform" optimization
  101. }
  102. void OnKeyPress(KeyDownEvent evt)
  103. {
  104. switch (evt.keyCode)
  105. {
  106. case KeyCode.A when evt.actionKey:
  107. SelectAll();
  108. evt.StopPropagation();
  109. break;
  110. case KeyCode.Home:
  111. ScrollToItem(0);
  112. evt.StopPropagation();
  113. break;
  114. case KeyCode.End:
  115. ScrollToItem(-1);
  116. evt.StopPropagation();
  117. break;
  118. case KeyCode.Escape:
  119. ClearSelection();
  120. evt.StopPropagation();
  121. break;
  122. case KeyCode.Return:
  123. onItemsChosen?.Invoke(m_SelectedItems);
  124. evt.StopPropagation();
  125. break;
  126. case KeyCode.LeftArrow:
  127. var firstIndexInRow = selectedIndex - selectedIndex % columnCount;
  128. if (selectedIndex >= 0 && selectedIndex > firstIndexInRow)
  129. {
  130. var next = evt.actionKey ? firstIndexInRow : selectedIndex - 1;
  131. if (next < firstIndexInRow)
  132. next = firstIndexInRow;
  133. if (evt.shiftKey)
  134. DoRangeSelection(next);
  135. else
  136. m_RangeSelectionOrigin = selectedIndex = next;
  137. evt.StopPropagation();
  138. }
  139. break;
  140. case KeyCode.RightArrow:
  141. {
  142. var currentRow = selectedIndex / columnCount;
  143. var lastIndexInRow = Math.Min((currentRow + 1) * columnCount - 1, itemsSource.Count - 1);
  144. if (selectedIndex >= 0 && selectedIndex < lastIndexInRow)
  145. {
  146. var next = evt.actionKey ? lastIndexInRow : selectedIndex + 1;
  147. if (next > lastIndexInRow)
  148. next = lastIndexInRow;
  149. if (evt.shiftKey)
  150. DoRangeSelection(next);
  151. else
  152. m_RangeSelectionOrigin = selectedIndex = next;
  153. evt.StopPropagation();
  154. }
  155. break;
  156. }
  157. case KeyCode.UpArrow:
  158. if (selectedIndex >= 0)
  159. {
  160. var next = evt.actionKey ?
  161. selectedIndex % columnCount :
  162. selectedIndex - columnCount;
  163. if (next >= 0 && selectedIndex != next)
  164. {
  165. if (evt.shiftKey)
  166. DoRangeSelection(next);
  167. else
  168. m_RangeSelectionOrigin = selectedIndex = next;
  169. ScrollToItem(evt.actionKey ? 0 : selectedIndex);
  170. evt.StopPropagation();
  171. }
  172. }
  173. break;
  174. case KeyCode.DownArrow:
  175. {
  176. if (selectedIndex >= 0)
  177. {
  178. var targetId = (Mathf.FloorToInt((float)itemsSource.Count / columnCount)) * columnCount + selectedIndex % columnCount;
  179. var next = evt.actionKey ?
  180. targetId >= itemsSource.Count ? targetId - columnCount : targetId :
  181. selectedIndex + columnCount;
  182. if (next < itemsSource.Count && selectedIndex != next)
  183. {
  184. if (evt.shiftKey)
  185. DoRangeSelection(next);
  186. else
  187. m_RangeSelectionOrigin = selectedIndex = next;
  188. ScrollToItem(evt.actionKey ? -1 : selectedIndex);
  189. evt.StopPropagation();
  190. }
  191. }
  192. break;
  193. }
  194. }
  195. }
  196. /// <summary>
  197. /// Constructs a <see cref="GridView"/>, with all required properties provided.
  198. /// </summary>
  199. /// <param name="itemsSource">The list of items to use as a data source.</param>
  200. /// <param name="itemHeight">The height of each item, in pixels.</param>
  201. /// <param name="makeItem">The factory method to call to create a display item. The method should return a
  202. /// VisualElement that can be bound to a data item.</param>
  203. /// <param name="bindItem">The method to call to bind a data item to a display item. The method
  204. /// receives as parameters the display item to bind, and the index of the data item to bind it to.</param>
  205. public GridView(IList itemsSource, int itemHeight, Func<VisualElement> makeItem, Action<VisualElement, int> bindItem)
  206. : this()
  207. {
  208. m_ItemsSource = itemsSource;
  209. m_ItemHeight = itemHeight;
  210. m_ItemHeightIsInline = true;
  211. m_MakeItem = makeItem;
  212. m_BindItem = bindItem;
  213. }
  214. /// <summary>
  215. /// Callback for binding a data item to the visual element.
  216. /// </summary>
  217. /// <remarks>
  218. /// The method called by this callback receives the VisualElement to bind, and the index of the
  219. /// element to bind it to.
  220. /// </remarks>
  221. public Action<VisualElement, int> bindItem
  222. {
  223. get { return m_BindItem; }
  224. set
  225. {
  226. m_BindItem = value;
  227. Refresh();
  228. }
  229. }
  230. /// <summary>
  231. /// The number of columns for this grid.
  232. /// </summary>
  233. public int columnCount
  234. {
  235. get => m_ColumnCount;
  236. set
  237. {
  238. if (m_ColumnCount != value && value > 0)
  239. {
  240. m_ScrollOffset = 0;
  241. m_ColumnCount = value;
  242. Refresh();
  243. }
  244. }
  245. }
  246. /// <summary>
  247. /// Returns the content container for the <see cref="GridView"/>. Because the GridView control automatically manages
  248. /// its content, this always returns null.
  249. /// </summary>
  250. public override VisualElement contentContainer => null;
  251. /// <summary>
  252. /// The height of a single item in the list, in pixels.
  253. /// </summary>
  254. /// <remarks>
  255. /// GridView requires that all visual elements have the same height so that it can calculate the
  256. /// scroller size.
  257. ///
  258. /// This property must be set for the list view to function.
  259. /// </remarks>
  260. [UxmlAttribute]
  261. public int itemHeight
  262. {
  263. get { return m_ItemHeight; }
  264. set
  265. {
  266. if (m_ItemHeight != value && value > 0)
  267. {
  268. m_ItemHeightIsInline = true;
  269. m_ItemHeight = value;
  270. Refresh();
  271. }
  272. }
  273. }
  274. /// <summary>
  275. ///
  276. /// </summary>
  277. public float itemWidth => (scrollView.contentViewport.layout.width / columnCount);
  278. /// <summary>
  279. /// The data source for list items.
  280. /// </summary>
  281. /// <remarks>
  282. /// This list contains the items that the <see cref="GridView"/> displays.
  283. ///
  284. /// This property must be set for the list view to function.
  285. /// </remarks>
  286. public IList itemsSource
  287. {
  288. get { return m_ItemsSource; }
  289. set
  290. {
  291. if (m_ItemsSource is INotifyCollectionChanged oldCollection)
  292. {
  293. oldCollection.CollectionChanged -= OnItemsSourceCollectionChanged;
  294. }
  295. m_ItemsSource = value;
  296. if (m_ItemsSource is INotifyCollectionChanged newCollection)
  297. {
  298. newCollection.CollectionChanged += OnItemsSourceCollectionChanged;
  299. }
  300. Refresh();
  301. }
  302. }
  303. /// <summary>
  304. /// Callback for constructing the VisualElement that is the template for each recycled and re-bound element in the list.
  305. /// </summary>
  306. /// <remarks>
  307. /// This callback needs to call a function that constructs a blank <see cref="VisualElement"/> that is
  308. /// bound to an element from the list.
  309. ///
  310. /// The GridView automatically creates enough elements to fill the visible area, and adds more if the area
  311. /// is expanded. As the user scrolls, the GridView cycles elements in and out as they appear or disappear.
  312. ///
  313. /// This property must be set for the list view to function.
  314. /// </remarks>
  315. public Func<VisualElement> makeItem
  316. {
  317. get { return m_MakeItem; }
  318. set
  319. {
  320. if (m_MakeItem == value)
  321. return;
  322. m_MakeItem = value;
  323. Refresh();
  324. }
  325. }
  326. /// <summary>
  327. /// The computed pixel-aligned height for the list elements.
  328. /// </summary>
  329. /// <remarks>
  330. /// This value changes depending on the current panel's DPI scaling.
  331. /// </remarks>
  332. /// <seealso cref="GridView.itemHeight"/>
  333. public float resolvedItemHeight
  334. {
  335. get
  336. {
  337. var dpiScaling = 1;//this.GetScaledPixelsPerPoint();
  338. return Mathf.Round(itemHeight * dpiScaling) / dpiScaling;
  339. }
  340. }
  341. /// <summary>
  342. ///
  343. /// </summary>
  344. public float resolvedItemWidth
  345. {
  346. get
  347. {
  348. var dpiScaling = 1;//this.GetScaledPixelsPerPoint();
  349. return Mathf.Round(itemWidth * dpiScaling) / dpiScaling;
  350. }
  351. }
  352. /// <summary>
  353. /// Returns or sets the selected item's index in the data source. If multiple items are selected, returns the
  354. /// first selected item's index. If multiple items are provided, sets them all as selected.
  355. /// </summary>
  356. public int selectedIndex
  357. {
  358. get { return m_SelectedIndices.Count == 0 ? -1 : m_SelectedIndices.First(); }
  359. set { SetSelection(value); }
  360. }
  361. /// <summary>
  362. /// Returns the indices of selected items in the data source. Always returns an enumerable, even if no item is selected, or a
  363. /// single item is selected.
  364. /// </summary>
  365. public IEnumerable<int> selectedIndices => m_SelectedIndices;
  366. /// <summary>
  367. /// Returns the selected item from the data source. If multiple items are selected, returns the first selected item.
  368. /// </summary>
  369. public object selectedItem => m_SelectedItems.Count == 0 ? null : m_SelectedItems.First();
  370. /// <summary>
  371. /// Returns the selected items from the data source. Always returns an enumerable, even if no item is selected, or a single
  372. /// item is selected.
  373. /// </summary>
  374. public IEnumerable<object> selectedItems => m_SelectedItems;
  375. /// <summary>
  376. /// Returns the IDs of selected items in the data source. Always returns an enumerable, even if no item is selected, or a
  377. /// single item is selected.
  378. /// </summary>
  379. public IEnumerable<int> selectedIds => m_SelectedIds;
  380. /// <summary>
  381. /// Controls the selection type.
  382. /// </summary>
  383. /// <remarks>
  384. /// You can set the GridView to make one item selectable at a time, make multiple items selectable, or disable selections completely.
  385. ///
  386. /// When you set the GridView to disable selections, any current selection is cleared.
  387. /// </remarks>
  388. [UxmlAttribute]
  389. public SelectionType selectionType
  390. {
  391. get { return m_SelectionType; }
  392. set
  393. {
  394. m_SelectionType = value;
  395. if (m_SelectionType == SelectionType.None || (m_SelectionType == SelectionType.Single && m_SelectedIndices.Count > 1))
  396. {
  397. ClearSelection();
  398. }
  399. }
  400. }
  401. /// <summary>
  402. /// Enable this property to display a border around the GridView.
  403. /// </summary>
  404. /// <remarks>
  405. /// If set to true, a border appears around the ScrollView.
  406. /// </remarks>
  407. [UxmlAttribute]
  408. public bool showBorder
  409. {
  410. get => ClassListContains(k_BorderUssClassName);
  411. set => EnableInClassList(k_BorderUssClassName, value);
  412. }
  413. /// <summary>
  414. /// Callback for unbinding a data item from the VisualElement.
  415. /// </summary>
  416. /// <remarks>
  417. /// The method called by this callback receives the VisualElement to unbind, and the index of the
  418. /// element to unbind it from.
  419. /// </remarks>
  420. public Action<VisualElement, int> unbindItem { get; set; }
  421. internal Func<int, int> getItemId
  422. {
  423. get { return m_GetItemId; }
  424. set
  425. {
  426. m_GetItemId = value;
  427. Refresh();
  428. }
  429. }
  430. internal List<RecycledRow> rowPool
  431. {
  432. get { return m_RowPool; }
  433. }
  434. void ISerializationCallbackReceiver.OnAfterDeserialize()
  435. {
  436. Refresh();
  437. }
  438. void ISerializationCallbackReceiver.OnBeforeSerialize() {}
  439. /// <summary>
  440. /// Callback triggered when the user acts on a selection of one or more items, for example by double-clicking or pressing Enter.
  441. /// </summary>
  442. /// <remarks>
  443. /// This callback receives an enumerable that contains the item or items chosen.
  444. /// </remarks>
  445. public event Action<IEnumerable<object>> onItemsChosen;
  446. /// <summary>
  447. /// Callback triggered when the selection changes.
  448. /// </summary>
  449. /// <remarks>
  450. /// This callback receives an enumerable that contains the item or items selected.
  451. /// </remarks>
  452. public event Action<IEnumerable<object>> onSelectionChange;
  453. /// <summary>
  454. /// Adds an item to the collection of selected items.
  455. /// </summary>
  456. /// <param name="index">Item index.</param>
  457. public void AddToSelection(int index)
  458. {
  459. AddToSelection(new[] { index });
  460. }
  461. /// <summary>
  462. /// Deselects any selected items.
  463. /// </summary>
  464. public void ClearSelection()
  465. {
  466. if (!HasValidDataAndBindings() || m_SelectedIds.Count == 0)
  467. return;
  468. ClearSelectionWithoutValidation();
  469. NotifyOfSelectionChange();
  470. }
  471. /// <summary>
  472. /// Clears the GridView, recreates all visible visual elements, and rebinds all items.
  473. /// </summary>
  474. /// <remarks>
  475. /// Call this method whenever the data source changes.
  476. /// </remarks>
  477. public void Refresh()
  478. {
  479. foreach (var recycledRow in m_RowPool)
  480. {
  481. recycledRow.Clear();
  482. }
  483. m_RowPool.Clear();
  484. scrollView.Clear();
  485. m_VisibleRowCount = 0;
  486. m_SelectedIndices.Clear();
  487. m_SelectedItems.Clear();
  488. // O(n)
  489. if (m_SelectedIds.Count > 0)
  490. {
  491. // Add selected objects to working lists.
  492. for (var index = 0; index < m_ItemsSource.Count; ++index)
  493. {
  494. if (!m_SelectedIds.Contains(GetIdFromIndex(index))) continue;
  495. m_SelectedIndices.Add(index);
  496. m_SelectedItems.Add(m_ItemsSource[index]);
  497. }
  498. }
  499. if (!HasValidDataAndBindings())
  500. return;
  501. m_LastHeight = scrollView.layout.height;
  502. if (float.IsNaN(m_LastHeight))
  503. return;
  504. m_FirstVisibleIndex = Math.Min((int)(m_ScrollOffset / resolvedItemHeight) * columnCount, m_ItemsSource.Count - 1);
  505. ResizeHeight(m_LastHeight);
  506. }
  507. /// <summary>
  508. /// Rebinds a single item if it is currently visible in the collection view.
  509. /// </summary>
  510. /// <param name="index">The item index.</param>
  511. internal void RefreshItem(int index)
  512. {
  513. foreach (var recycledRow in m_RowPool)
  514. {
  515. if (recycledRow.ContainsIndex(index, out var indexInRow))
  516. {
  517. var item = makeItem != null && index < itemsSource.Count ? makeItem.Invoke() : CreateDummyItemElement();
  518. SetupItemElement(item);
  519. recycledRow.RemoveAt(indexInRow);
  520. recycledRow.Insert(indexInRow, item);
  521. bindItem.Invoke(item, recycledRow.indices[indexInRow]);
  522. recycledRow.SetSelected(indexInRow, m_SelectedIds.Contains(recycledRow.ids[indexInRow]));
  523. break;
  524. }
  525. }
  526. }
  527. /// <summary>
  528. /// Removes an item from the collection of selected items.
  529. /// </summary>
  530. /// <param name="index">The item index.</param>
  531. public void RemoveFromSelection(int index)
  532. {
  533. if (!HasValidDataAndBindings())
  534. return;
  535. RemoveFromSelectionWithoutValidation(index);
  536. NotifyOfSelectionChange();
  537. //SaveViewData();
  538. }
  539. /// <summary>
  540. /// Scrolls to a specific item index and makes it visible.
  541. /// </summary>
  542. /// <param name="index">Item index to scroll to. Specify -1 to make the last item visible.</param>
  543. public void ScrollToItem(int index)
  544. {
  545. if (!HasValidDataAndBindings())
  546. return;
  547. if (m_VisibleRowCount == 0 || index < -1)
  548. return;
  549. var pixelAlignedItemHeight = resolvedItemHeight;
  550. var actualCount = Math.Min(Mathf.FloorToInt(m_LastHeight / pixelAlignedItemHeight) * columnCount, itemsSource.Count);
  551. if (index == -1)
  552. {
  553. // Scroll to last item
  554. if (itemsSource.Count < actualCount)
  555. scrollView.scrollOffset = new Vector2(0, 0);
  556. else
  557. scrollView.scrollOffset = new Vector2(0, Mathf.FloorToInt(itemsSource.Count / (float)columnCount) * pixelAlignedItemHeight);
  558. }
  559. else if (m_FirstVisibleIndex >= index)
  560. {
  561. scrollView.scrollOffset = Vector2.up * (pixelAlignedItemHeight * Mathf.FloorToInt(index / (float)columnCount));
  562. }
  563. else // index > first
  564. {
  565. if (index < m_FirstVisibleIndex + actualCount)
  566. return;
  567. var d = Mathf.FloorToInt(index - actualCount / (float)columnCount);
  568. var visibleOffset = pixelAlignedItemHeight - (m_LastHeight - Mathf.FloorToInt(actualCount / (float)columnCount) * pixelAlignedItemHeight);
  569. var yScrollOffset = pixelAlignedItemHeight * d + visibleOffset;
  570. scrollView.scrollOffset = new Vector2(scrollView.scrollOffset.x, yScrollOffset);
  571. }
  572. }
  573. /// <summary>
  574. /// Sets the currently selected item.
  575. /// </summary>
  576. /// <param name="index">The item index.</param>
  577. public void SetSelection(int index)
  578. {
  579. if (index < 0 || itemsSource == null || index >= itemsSource.Count)
  580. {
  581. ClearSelection();
  582. return;
  583. }
  584. SetSelection(new[] { index });
  585. }
  586. /// <summary>
  587. /// Sets a collection of selected items.
  588. /// </summary>
  589. /// <param name="indices">The collection of the indices of the items to be selected.</param>
  590. public void SetSelection(IEnumerable<int> indices)
  591. {
  592. switch (selectionType)
  593. {
  594. case SelectionType.None:
  595. return;
  596. case SelectionType.Single:
  597. if (indices != null)
  598. indices = new[] { indices.Last() };
  599. break;
  600. case SelectionType.Multiple:
  601. break;
  602. default:
  603. throw new ArgumentOutOfRangeException();
  604. }
  605. SetSelectionInternal(indices, true);
  606. }
  607. /// <summary>
  608. /// Sets a collection of selected items without triggering a selection change callback.
  609. /// </summary>
  610. /// <param name="indices">The collection of items to be selected.</param>
  611. public void SetSelectionWithoutNotify(IEnumerable<int> indices)
  612. {
  613. SetSelectionInternal(indices, false);
  614. }
  615. internal void AddToSelection(IList<int> indexes)
  616. {
  617. if (!HasValidDataAndBindings() || indexes == null || indexes.Count == 0)
  618. return;
  619. foreach (var index in indexes)
  620. {
  621. AddToSelectionWithoutValidation(index);
  622. }
  623. NotifyOfSelectionChange();
  624. //SaveViewData();
  625. }
  626. internal void SelectAll()
  627. {
  628. if (!HasValidDataAndBindings())
  629. return;
  630. if (selectionType != SelectionType.Multiple)
  631. {
  632. return;
  633. }
  634. for (var index = 0; index < itemsSource.Count; index++)
  635. {
  636. var id = GetIdFromIndex(index);
  637. var item = m_ItemsSource[index];
  638. foreach (var recycledRow in m_RowPool)
  639. {
  640. if (recycledRow.ContainsId(id, out var indexInRow))
  641. recycledRow.SetSelected(indexInRow, true);
  642. }
  643. if (!m_SelectedIds.Contains(id))
  644. {
  645. m_SelectedIds.Add(id);
  646. m_SelectedIndices.Add(index);
  647. m_SelectedItems.Add(item);
  648. }
  649. }
  650. NotifyOfSelectionChange();
  651. //SaveViewData();
  652. }
  653. internal void SetSelectionInternal(IEnumerable<int> indices, bool sendNotification)
  654. {
  655. if (!HasValidDataAndBindings() || indices == null)
  656. return;
  657. ClearSelectionWithoutValidation();
  658. foreach (var index in indices.Where(index => index != -1))
  659. {
  660. AddToSelectionWithoutValidation(index);
  661. }
  662. if (sendNotification)
  663. NotifyOfSelectionChange();
  664. //SaveViewData();
  665. }
  666. void AddToSelectionWithoutValidation(int index)
  667. {
  668. if (m_SelectedIndices.Contains(index))
  669. return;
  670. var id = GetIdFromIndex(index);
  671. var item = m_ItemsSource[index];
  672. foreach (var recycledRow in m_RowPool)
  673. {
  674. if (recycledRow.ContainsId(id, out var indexInRow))
  675. recycledRow.SetSelected(indexInRow, true);
  676. }
  677. m_SelectedIds.Add(id);
  678. m_SelectedIndices.Add(index);
  679. m_SelectedItems.Add(item);
  680. }
  681. void ClearSelectionWithoutValidation()
  682. {
  683. foreach (var recycledRow in m_RowPool)
  684. {
  685. recycledRow.ClearSelection();
  686. }
  687. m_SelectedIds.Clear();
  688. m_SelectedIndices.Clear();
  689. m_SelectedItems.Clear();
  690. }
  691. VisualElement CreateDummyItemElement()
  692. {
  693. var item = new VisualElement();
  694. SetupItemElement(item);
  695. return item;
  696. }
  697. void DoRangeSelection(int rangeSelectionFinalIndex)
  698. {
  699. ClearSelectionWithoutValidation();
  700. // Add range
  701. var range = new List<int>();
  702. if (rangeSelectionFinalIndex < m_RangeSelectionOrigin)
  703. {
  704. for (var i = rangeSelectionFinalIndex; i <= m_RangeSelectionOrigin; i++)
  705. {
  706. range.Add(i);
  707. }
  708. }
  709. else
  710. {
  711. for (var i = rangeSelectionFinalIndex; i >= m_RangeSelectionOrigin; i--)
  712. {
  713. range.Add(i);
  714. }
  715. }
  716. AddToSelection(range);
  717. }
  718. void DoSelect(Vector2 localPosition, int clickCount, bool actionKey, bool shiftKey)
  719. {
  720. var clickedIndex = GetIndexByPosition(localPosition);
  721. if (clickedIndex > m_ItemsSource.Count - 1)
  722. return;
  723. var clickedItemId = GetIdFromIndex(clickedIndex);
  724. switch (clickCount)
  725. {
  726. case 1:
  727. if (selectionType == SelectionType.None)
  728. return;
  729. if (selectionType == SelectionType.Multiple && actionKey)
  730. {
  731. m_RangeSelectionOrigin = clickedIndex;
  732. // Add/remove single clicked element
  733. if (m_SelectedIds.Contains(clickedItemId))
  734. RemoveFromSelection(clickedIndex);
  735. else
  736. AddToSelection(clickedIndex);
  737. }
  738. else if (selectionType == SelectionType.Multiple && shiftKey)
  739. {
  740. if (m_RangeSelectionOrigin == -1)
  741. {
  742. m_RangeSelectionOrigin = clickedIndex;
  743. SetSelection(clickedIndex);
  744. }
  745. else
  746. {
  747. DoRangeSelection(clickedIndex);
  748. }
  749. }
  750. else if (selectionType == SelectionType.Multiple && m_SelectedIndices.Contains(clickedIndex))
  751. {
  752. // Do noting, selection will be processed OnPointerUp.
  753. // If drag and drop will be started GridViewDragger will capture the mouse and GridView will not receive the mouse up event.
  754. }
  755. else // single
  756. {
  757. m_RangeSelectionOrigin = clickedIndex;
  758. SetSelection(clickedIndex);
  759. }
  760. break;
  761. case 2:
  762. if (onItemsChosen != null)
  763. {
  764. ProcessSingleClick(clickedIndex);
  765. }
  766. onItemsChosen?.Invoke(m_SelectedItems);
  767. break;
  768. }
  769. }
  770. int GetIdFromIndex(int index)
  771. {
  772. if (m_GetItemId == null)
  773. return index;
  774. return m_GetItemId(index);
  775. }
  776. bool HasValidDataAndBindings()
  777. {
  778. return itemsSource != null && makeItem != null && bindItem != null;
  779. }
  780. void NotifyOfSelectionChange()
  781. {
  782. if (!HasValidDataAndBindings())
  783. return;
  784. onSelectionChange?.Invoke(m_SelectedItems);
  785. }
  786. void OnAttachToPanel(AttachToPanelEvent evt)
  787. {
  788. if (evt.destinationPanel == null)
  789. return;
  790. scrollView.contentContainer.RegisterCallback<PointerDownEvent>(OnPointerDown);
  791. scrollView.contentContainer.RegisterCallback<PointerUpEvent>(OnPointerUp);
  792. scrollView.contentContainer.RegisterCallback<KeyDownEvent>(OnKeyPress);
  793. }
  794. void OnCustomStyleResolved(CustomStyleResolvedEvent e)
  795. {
  796. int height;
  797. if (!m_ItemHeightIsInline && e.customStyle.TryGetValue(s_ItemHeightProperty, out height))
  798. {
  799. if (m_ItemHeight != height)
  800. {
  801. m_ItemHeight = height;
  802. Refresh();
  803. }
  804. }
  805. }
  806. void OnDetachFromPanel(DetachFromPanelEvent evt)
  807. {
  808. if (evt.originPanel == null)
  809. return;
  810. scrollView.contentContainer.UnregisterCallback<PointerDownEvent>(OnPointerDown);
  811. scrollView.contentContainer.UnregisterCallback<PointerUpEvent>(OnPointerUp);
  812. scrollView.contentContainer.UnregisterCallback<KeyDownEvent>(OnKeyPress);
  813. }
  814. void OnPointerDown(PointerDownEvent evt)
  815. {
  816. if (!HasValidDataAndBindings())
  817. return;
  818. if (!evt.isPrimary)
  819. return;
  820. if (evt.button != (int)MouseButton.LeftMouse)
  821. return;
  822. if (evt.pointerType != "mouse")
  823. {
  824. m_TouchDownTime = evt.timestamp;
  825. m_TouchDownPosition = evt.position;
  826. return;
  827. }
  828. DoSelect(evt.localPosition, evt.clickCount, evt.actionKey, evt.shiftKey);
  829. }
  830. void OnPointerUp(PointerUpEvent evt)
  831. {
  832. if (!HasValidDataAndBindings())
  833. return;
  834. if (!evt.isPrimary)
  835. return;
  836. if (evt.button != (int)MouseButton.LeftMouse)
  837. return;
  838. if (evt.pointerType != "mouse")
  839. {
  840. var delay = evt.timestamp - m_TouchDownTime;
  841. var delta = evt.position - m_TouchDownPosition;
  842. if (delay < 500 && delta.sqrMagnitude <= 100)
  843. {
  844. DoSelect(evt.localPosition, evt.clickCount, evt.actionKey, evt.shiftKey);
  845. }
  846. }
  847. else
  848. {
  849. var clickedIndex = GetIndexByPosition(evt.localPosition);
  850. if (selectionType == SelectionType.Multiple
  851. && !evt.shiftKey
  852. && !evt.actionKey
  853. && m_SelectedIndices.Count > 1
  854. && m_SelectedIndices.Contains(clickedIndex))
  855. {
  856. ProcessSingleClick(clickedIndex);
  857. }
  858. }
  859. }
  860. int GetIndexByPosition(Vector2 localPosition)
  861. {
  862. return Mathf.FloorToInt(localPosition.y / resolvedItemHeight) * columnCount + Mathf.FloorToInt(localPosition.x / resolvedItemWidth);
  863. }
  864. internal VisualElement GetElementAt(int index)
  865. {
  866. foreach (var row in m_RowPool)
  867. {
  868. if (row.ContainsId(index, out var indexInRow))
  869. return row[indexInRow];
  870. }
  871. return null;
  872. }
  873. void OnItemsSourceCollectionChanged(object sender, NotifyCollectionChangedEventArgs args)
  874. {
  875. Refresh();
  876. }
  877. void OnScroll(float offset)
  878. {
  879. if (!HasValidDataAndBindings())
  880. return;
  881. m_ScrollOffset = offset;
  882. var pixelAlignedItemHeight = resolvedItemHeight;
  883. var firstVisibleIndex = Mathf.FloorToInt(offset / pixelAlignedItemHeight) * columnCount;
  884. scrollView.contentContainer.style.paddingTop = Mathf.FloorToInt(firstVisibleIndex / (float)columnCount) * pixelAlignedItemHeight;
  885. scrollView.contentContainer.style.height = (Mathf.CeilToInt(itemsSource.Count / (float)columnCount) * pixelAlignedItemHeight);
  886. if (firstVisibleIndex != m_FirstVisibleIndex)
  887. {
  888. m_FirstVisibleIndex = firstVisibleIndex;
  889. if (m_RowPool.Count > 0)
  890. {
  891. // we try to avoid rebinding a few items
  892. if (m_FirstVisibleIndex < m_RowPool[0].firstIndex) //we're scrolling up
  893. {
  894. //How many do we have to swap back
  895. var count = m_RowPool[0].firstIndex - m_FirstVisibleIndex;
  896. var inserting = m_ScrollInsertionList;
  897. for (var i = 0; i < count && m_RowPool.Count > 0; ++i)
  898. {
  899. var last = m_RowPool[m_RowPool.Count - 1];
  900. inserting.Add(last);
  901. m_RowPool.RemoveAt(m_RowPool.Count - 1); //we remove from the end
  902. last.SendToBack(); //We send the element to the top of the list (back in z-order)
  903. }
  904. inserting.Reverse();
  905. m_ScrollInsertionList = m_RowPool;
  906. m_RowPool = inserting;
  907. m_RowPool.AddRange(m_ScrollInsertionList);
  908. m_ScrollInsertionList.Clear();
  909. }
  910. else if (m_FirstVisibleIndex > m_RowPool[0].firstIndex) //down
  911. {
  912. var inserting = m_ScrollInsertionList;
  913. var checkIndex = 0;
  914. while (checkIndex < m_RowPool.Count && m_FirstVisibleIndex > m_RowPool[checkIndex].firstIndex)
  915. {
  916. var first = m_RowPool[checkIndex];
  917. inserting.Add(first);
  918. first.BringToFront(); //We send the element to the bottom of the list (front in z-order)
  919. checkIndex++;
  920. }
  921. m_RowPool.RemoveRange(0, checkIndex); //we remove them all at once
  922. m_RowPool.AddRange(inserting); // add them back to the end
  923. inserting.Clear();
  924. }
  925. //Let's rebind everything
  926. for (var rowIndex = 0; rowIndex < m_RowPool.Count; rowIndex++)
  927. {
  928. for (var colIndex = 0; colIndex < columnCount; colIndex++)
  929. {
  930. var index = rowIndex * columnCount + colIndex + m_FirstVisibleIndex;
  931. if (index < itemsSource.Count)
  932. {
  933. var item = m_RowPool[rowIndex].ElementAt(colIndex);
  934. if (m_RowPool[rowIndex].indices[colIndex] == RecycledRow.kUndefinedIndex)
  935. {
  936. var newItem = makeItem != null ? makeItem.Invoke() : CreateDummyItemElement();
  937. SetupItemElement(newItem);
  938. m_RowPool[rowIndex].RemoveAt(colIndex);
  939. m_RowPool[rowIndex].Insert(colIndex, newItem);
  940. item = newItem;
  941. }
  942. Setup(item, index);
  943. }
  944. else
  945. {
  946. var remainingOldItems = columnCount - colIndex;
  947. while (remainingOldItems > 0)
  948. {
  949. m_RowPool[rowIndex].RemoveAt(colIndex);
  950. m_RowPool[rowIndex].Insert(colIndex, CreateDummyItemElement());
  951. m_RowPool[rowIndex].ids.RemoveAt(colIndex);
  952. m_RowPool[rowIndex].ids.Insert(colIndex, RecycledRow.kUndefinedIndex);
  953. m_RowPool[rowIndex].indices.RemoveAt(colIndex);
  954. m_RowPool[rowIndex].indices.Insert(colIndex, RecycledRow.kUndefinedIndex);
  955. remainingOldItems--;
  956. }
  957. }
  958. }
  959. }
  960. }
  961. }
  962. }
  963. void OnSizeChanged(GeometryChangedEvent evt)
  964. {
  965. if (!HasValidDataAndBindings())
  966. return;
  967. if (Mathf.Approximately(evt.newRect.height, evt.oldRect.height))
  968. return;
  969. ResizeHeight(evt.newRect.height);
  970. }
  971. void ProcessSingleClick(int clickedIndex)
  972. {
  973. m_RangeSelectionOrigin = clickedIndex;
  974. SetSelection(clickedIndex);
  975. }
  976. void RemoveFromSelectionWithoutValidation(int index)
  977. {
  978. if (!m_SelectedIndices.Contains(index))
  979. return;
  980. var id = GetIdFromIndex(index);
  981. var item = m_ItemsSource[index];
  982. foreach (var recycledRow in m_RowPool)
  983. {
  984. if (recycledRow.ContainsId(id, out var indexInRow))
  985. recycledRow.SetSelected(indexInRow, false);
  986. }
  987. m_SelectedIds.Remove(id);
  988. m_SelectedIndices.Remove(index);
  989. m_SelectedItems.Remove(item);
  990. }
  991. void ResizeHeight(float height)
  992. {
  993. if (!HasValidDataAndBindings())
  994. return;
  995. var pixelAlignedItemHeight = resolvedItemHeight;
  996. var rowCountForSource = Mathf.CeilToInt(itemsSource.Count / (float)columnCount);
  997. var contentHeight = rowCountForSource * pixelAlignedItemHeight;
  998. scrollView.contentContainer.style.height = contentHeight;
  999. var scrollableHeight = Mathf.Max(0, contentHeight - scrollView.contentViewport.layout.height);
  1000. scrollView.verticalScroller.highValue = scrollableHeight;
  1001. scrollView.verticalScroller.value = Mathf.Min(m_ScrollOffset, scrollView.verticalScroller.highValue);
  1002. var rowCountForHeight = Mathf.FloorToInt(height / pixelAlignedItemHeight) + k_ExtraVisibleRows;
  1003. var rowCount = Math.Min(rowCountForHeight, rowCountForSource);
  1004. if (m_VisibleRowCount != rowCount)
  1005. {
  1006. if (m_VisibleRowCount > rowCount)
  1007. {
  1008. // Shrink
  1009. var removeCount = m_VisibleRowCount - rowCount;
  1010. for (var i = 0; i < removeCount; i++)
  1011. {
  1012. var lastIndex = m_RowPool.Count - 1;
  1013. m_RowPool[lastIndex].Clear();
  1014. scrollView.Remove(m_RowPool[lastIndex]);
  1015. m_RowPool.RemoveAt(lastIndex);
  1016. }
  1017. }
  1018. else
  1019. {
  1020. // Grow
  1021. var addCount = rowCount - m_VisibleRowCount;
  1022. for (var i = 0; i < addCount; i++)
  1023. {
  1024. var recycledRow = new RecycledRow(resolvedItemHeight);
  1025. for (var indexInRow = 0; indexInRow < columnCount; indexInRow++)
  1026. {
  1027. var index = m_FirstVisibleIndex + m_RowPool.Count * columnCount + indexInRow;
  1028. var item = makeItem != null && index < itemsSource.Count ? makeItem.Invoke() : CreateDummyItemElement();
  1029. SetupItemElement(item);
  1030. recycledRow.Add(item);
  1031. if (index < itemsSource.Count)
  1032. {
  1033. Setup(item, index);
  1034. }
  1035. else
  1036. {
  1037. recycledRow.ids.Add(RecycledRow.kUndefinedIndex);
  1038. recycledRow.indices.Add(RecycledRow.kUndefinedIndex);
  1039. }
  1040. }
  1041. m_RowPool.Add(recycledRow);
  1042. recycledRow.style.height = pixelAlignedItemHeight;
  1043. scrollView.Add(recycledRow);
  1044. }
  1045. }
  1046. m_VisibleRowCount = rowCount;
  1047. }
  1048. m_LastHeight = height;
  1049. }
  1050. void Setup(VisualElement item, int newIndex)
  1051. {
  1052. var newId = GetIdFromIndex(newIndex);
  1053. if (!(item.parent is RecycledRow recycledRow))
  1054. throw new Exception("The item to setup can't be orphan");
  1055. var indexInRow = recycledRow.IndexOf(item);
  1056. if (recycledRow.indices.Count <= indexInRow)
  1057. {
  1058. recycledRow.indices.Add(RecycledRow.kUndefinedIndex);
  1059. recycledRow.ids.Add(RecycledRow.kUndefinedIndex);
  1060. }
  1061. if (recycledRow.indices[indexInRow] == newIndex)
  1062. return;
  1063. if (recycledRow.indices[indexInRow] != RecycledRow.kUndefinedIndex)
  1064. unbindItem?.Invoke(item, recycledRow.indices[indexInRow]);
  1065. recycledRow.indices[indexInRow] = newIndex;
  1066. recycledRow.ids[indexInRow] = newId;
  1067. bindItem.Invoke(item, recycledRow.indices[indexInRow]);
  1068. recycledRow.SetSelected(indexInRow, m_SelectedIds.Contains(recycledRow.ids[indexInRow]));
  1069. }
  1070. void SetupItemElement(VisualElement item)
  1071. {
  1072. item.AddToClassList(k_ItemUssClassName);
  1073. item.style.position = Position.Relative;
  1074. item.style.height = itemHeight;
  1075. item.style.width = itemWidth;
  1076. }
  1077. internal class RecycledRow : VisualElement
  1078. {
  1079. public const int kUndefinedIndex = -1;
  1080. public readonly List<int> ids;
  1081. public readonly List<int> indices;
  1082. public RecycledRow(float height)
  1083. {
  1084. AddToClassList(k_RowUssClassName);
  1085. style.height = height;
  1086. indices = new List<int>();
  1087. ids = new List<int>();
  1088. }
  1089. public int firstIndex => indices.Count > 0 ? indices[0] : kUndefinedIndex;
  1090. public int lastIndex => indices.Count > 0 ? indices[indices.Count - 1] : kUndefinedIndex;
  1091. public void ClearSelection()
  1092. {
  1093. for (var i = 0; i < childCount; i++)
  1094. {
  1095. SetSelected(i, false);
  1096. }
  1097. }
  1098. public bool ContainsId(int id, out int indexInRow)
  1099. {
  1100. indexInRow = ids.IndexOf(id);
  1101. return indexInRow >= 0;
  1102. }
  1103. public bool ContainsIndex(int index, out int indexInRow)
  1104. {
  1105. indexInRow = indices.IndexOf(index);
  1106. return indexInRow >= 0;
  1107. }
  1108. public void SetSelected(int indexInRow, bool selected)
  1109. {
  1110. if (childCount > indexInRow && indexInRow >= 0)
  1111. {
  1112. if (selected)
  1113. {
  1114. AddElementToClass(ElementAt(indexInRow), itemSelectedVariantUssClassName, true);
  1115. }
  1116. else
  1117. {
  1118. RemoveElementFromClass(ElementAt(indexInRow), itemSelectedVariantUssClassName, true);
  1119. }
  1120. }
  1121. }
  1122. static void AddElementToClass(VisualElement element, string className, bool includeChildren = false)
  1123. {
  1124. element.AddToClassList(className);
  1125. if (includeChildren)
  1126. {
  1127. foreach (var child in element.Children())
  1128. child.AddToClassList(className);
  1129. }
  1130. }
  1131. static void RemoveElementFromClass(VisualElement element, string className, bool includeChildren = false)
  1132. {
  1133. element.RemoveFromClassList(className);
  1134. if (includeChildren)
  1135. {
  1136. foreach (var child in element.Children())
  1137. child.RemoveFromClassList(className);
  1138. }
  1139. }
  1140. }
  1141. }
  1142. }