ElementManager.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. // This source file is adapted from the WinUI project.
  2. // (https://github.com/microsoft/microsoft-ui-xaml)
  3. //
  4. // Licensed to The Avalonia Project under MIT License, courtesy of The .NET Foundation.
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Collections.Specialized;
  8. using Avalonia.Layout.Utils;
  9. using Avalonia.Logging;
  10. namespace Avalonia.Layout
  11. {
  12. internal class ElementManager
  13. {
  14. private readonly List<ILayoutable> _realizedElements = new List<ILayoutable>();
  15. private readonly List<Rect> _realizedElementLayoutBounds = new List<Rect>();
  16. private int _firstRealizedDataIndex;
  17. private VirtualizingLayoutContext _context;
  18. private bool IsVirtualizingContext
  19. {
  20. get
  21. {
  22. if (_context != null)
  23. {
  24. var rect = _context.RealizationRect;
  25. bool hasInfiniteSize = double.IsInfinity(rect.Height) || double.IsInfinity(rect.Width);
  26. return !hasInfiniteSize;
  27. }
  28. return false;
  29. }
  30. }
  31. public void SetContext(VirtualizingLayoutContext virtualContext) => _context = virtualContext;
  32. public void OnBeginMeasure(ScrollOrientation orientation)
  33. {
  34. if (_context != null)
  35. {
  36. if (IsVirtualizingContext)
  37. {
  38. // We proactively clear elements laid out outside of the realizaton
  39. // rect so that they are available for reuse during the current
  40. // measure pass.
  41. // This is useful during fast panning scenarios in which the realization
  42. // window is constantly changing and we want to reuse elements from
  43. // the end that's opposite to the panning direction.
  44. DiscardElementsOutsideWindow(_context.RealizationRect, orientation);
  45. }
  46. else
  47. {
  48. // If we are initialized with a non-virtualizing context, make sure that
  49. // we have enough space to hold the bounds for all the elements.
  50. int count = _context.ItemCount;
  51. if (_realizedElementLayoutBounds.Count != count)
  52. {
  53. // Make sure there is enough space for the bounds.
  54. // Note: We could optimize when the count becomes smaller, but keeping
  55. // it always up to date is the simplest option for now.
  56. _realizedElementLayoutBounds.Resize(count);
  57. }
  58. }
  59. }
  60. }
  61. public int GetRealizedElementCount()
  62. {
  63. return IsVirtualizingContext ? _realizedElements.Count : _context.ItemCount;
  64. }
  65. public ILayoutable GetAt(int realizedIndex)
  66. {
  67. ILayoutable element;
  68. if (IsVirtualizingContext)
  69. {
  70. if (_realizedElements[realizedIndex] == null)
  71. {
  72. // Sentinel. Create the element now since we need it.
  73. int dataIndex = GetDataIndexFromRealizedRangeIndex(realizedIndex);
  74. Logger.TryGet(LogEventLevel.Verbose, "Repeater")?.Log(this, "Creating element for sentinal with data index {Index}", dataIndex);
  75. element = _context.GetOrCreateElementAt(
  76. dataIndex,
  77. ElementRealizationOptions.ForceCreate | ElementRealizationOptions.SuppressAutoRecycle);
  78. _realizedElements[realizedIndex] = element;
  79. }
  80. else
  81. {
  82. element = _realizedElements[realizedIndex];
  83. }
  84. }
  85. else
  86. {
  87. // realizedIndex and dataIndex are the same (everything is realized)
  88. element = _context.GetOrCreateElementAt(
  89. realizedIndex,
  90. ElementRealizationOptions.ForceCreate | ElementRealizationOptions.SuppressAutoRecycle);
  91. }
  92. return element;
  93. }
  94. public void Add(ILayoutable element, int dataIndex)
  95. {
  96. if (_realizedElements.Count == 0)
  97. {
  98. _firstRealizedDataIndex = dataIndex;
  99. }
  100. _realizedElements.Add(element);
  101. _realizedElementLayoutBounds.Add(default);
  102. }
  103. public void Insert(int realizedIndex, int dataIndex, ILayoutable element)
  104. {
  105. if (realizedIndex == 0)
  106. {
  107. _firstRealizedDataIndex = dataIndex;
  108. }
  109. _realizedElements.Insert(realizedIndex, element);
  110. // Set bounds to an invalid rect since we do not know it yet.
  111. _realizedElementLayoutBounds.Insert(realizedIndex, new Rect(-1, -1, -1, -1));
  112. }
  113. public void ClearRealizedRange(int realizedIndex, int count)
  114. {
  115. for (int i = 0; i < count; i++)
  116. {
  117. // Clear from the edges so that ItemsRepeater can optimize on maintaining
  118. // realized indices without walking through all the children every time.
  119. int index = realizedIndex == 0 ? realizedIndex + i : (realizedIndex + count - 1) - i;
  120. var elementRef = _realizedElements[index];
  121. if (elementRef != null)
  122. {
  123. _context.RecycleElement(elementRef);
  124. }
  125. }
  126. int endIndex = realizedIndex + count;
  127. _realizedElements.RemoveRange(realizedIndex, endIndex - realizedIndex);
  128. _realizedElementLayoutBounds.RemoveRange(realizedIndex, endIndex - realizedIndex);
  129. if (realizedIndex == 0)
  130. {
  131. _firstRealizedDataIndex = _realizedElements.Count == 0 ?
  132. -1 : _firstRealizedDataIndex + count;
  133. }
  134. }
  135. public void DiscardElementsOutsideWindow(bool forward, int startIndex)
  136. {
  137. // Remove layout elements that are outside the realized range.
  138. if (IsDataIndexRealized(startIndex))
  139. {
  140. int rangeIndex = GetRealizedRangeIndexFromDataIndex(startIndex);
  141. if (forward)
  142. {
  143. ClearRealizedRange(rangeIndex, GetRealizedElementCount() - rangeIndex);
  144. }
  145. else
  146. {
  147. ClearRealizedRange(0, rangeIndex + 1);
  148. }
  149. }
  150. }
  151. public void ClearRealizedRange() => ClearRealizedRange(0, GetRealizedElementCount());
  152. public Rect GetLayoutBoundsForDataIndex(int dataIndex)
  153. {
  154. int realizedIndex = GetRealizedRangeIndexFromDataIndex(dataIndex);
  155. return _realizedElementLayoutBounds[realizedIndex];
  156. }
  157. public void SetLayoutBoundsForDataIndex(int dataIndex, in Rect bounds)
  158. {
  159. int realizedIndex = GetRealizedRangeIndexFromDataIndex(dataIndex);
  160. _realizedElementLayoutBounds[realizedIndex] = bounds;
  161. }
  162. public Rect GetLayoutBoundsForRealizedIndex(int realizedIndex) => _realizedElementLayoutBounds[realizedIndex];
  163. public void SetLayoutBoundsForRealizedIndex(int realizedIndex, in Rect bounds)
  164. {
  165. _realizedElementLayoutBounds[realizedIndex] = bounds;
  166. }
  167. public bool IsDataIndexRealized(int index)
  168. {
  169. if (IsVirtualizingContext)
  170. {
  171. int realizedCount = GetRealizedElementCount();
  172. return
  173. realizedCount > 0 &&
  174. GetDataIndexFromRealizedRangeIndex(0) <= index &&
  175. GetDataIndexFromRealizedRangeIndex(realizedCount - 1) >= index;
  176. }
  177. else
  178. {
  179. // Non virtualized - everything is realized
  180. return index >= 0 && index < _context.ItemCount;
  181. }
  182. }
  183. public bool IsIndexValidInData(int currentIndex) => (uint)currentIndex < _context.ItemCount;
  184. public ILayoutable GetRealizedElement(int dataIndex)
  185. {
  186. return IsVirtualizingContext ?
  187. GetAt(GetRealizedRangeIndexFromDataIndex(dataIndex)) :
  188. _context.GetOrCreateElementAt(
  189. dataIndex,
  190. ElementRealizationOptions.ForceCreate | ElementRealizationOptions.SuppressAutoRecycle);
  191. }
  192. public void EnsureElementRealized(bool forward, int dataIndex, string layoutId)
  193. {
  194. if (IsDataIndexRealized(dataIndex) == false)
  195. {
  196. var element = _context.GetOrCreateElementAt(
  197. dataIndex,
  198. ElementRealizationOptions.ForceCreate | ElementRealizationOptions.SuppressAutoRecycle);
  199. if (forward)
  200. {
  201. Add(element, dataIndex);
  202. }
  203. else
  204. {
  205. Insert(0, dataIndex, element);
  206. }
  207. Logger.TryGet(LogEventLevel.Verbose, "Repeater")?.Log(this, "{LayoutId}: Created element for index {index}", layoutId, dataIndex);
  208. }
  209. }
  210. public bool IsWindowConnected(in Rect window, ScrollOrientation orientation, bool scrollOrientationSameAsFlow)
  211. {
  212. bool intersects = false;
  213. if (_realizedElementLayoutBounds.Count > 0)
  214. {
  215. var firstElementBounds = GetLayoutBoundsForRealizedIndex(0);
  216. var lastElementBounds = GetLayoutBoundsForRealizedIndex(GetRealizedElementCount() - 1);
  217. var effectiveOrientation = scrollOrientationSameAsFlow ?
  218. (orientation == ScrollOrientation.Vertical ? ScrollOrientation.Horizontal : ScrollOrientation.Vertical) :
  219. orientation;
  220. var windowStart = effectiveOrientation == ScrollOrientation.Vertical ? window.Y : window.X;
  221. var windowEnd = effectiveOrientation == ScrollOrientation.Vertical ? window.Y + window.Height : window.X + window.Width;
  222. var firstElementStart = effectiveOrientation == ScrollOrientation.Vertical ? firstElementBounds.Y : firstElementBounds.X;
  223. var lastElementEnd = effectiveOrientation == ScrollOrientation.Vertical ? lastElementBounds.Y + lastElementBounds.Height : lastElementBounds.X + lastElementBounds.Width;
  224. intersects =
  225. firstElementStart <= windowEnd &&
  226. lastElementEnd >= windowStart;
  227. }
  228. return intersects;
  229. }
  230. public void DataSourceChanged(object source, NotifyCollectionChangedEventArgs args)
  231. {
  232. if (_realizedElements.Count > 0)
  233. {
  234. switch (args.Action)
  235. {
  236. case NotifyCollectionChangedAction.Add:
  237. {
  238. OnItemsAdded(args.NewStartingIndex, args.NewItems.Count);
  239. }
  240. break;
  241. case NotifyCollectionChangedAction.Replace:
  242. {
  243. int oldSize = args.OldItems.Count;
  244. int newSize = args.NewItems.Count;
  245. int oldStartIndex = args.OldStartingIndex;
  246. int newStartIndex = args.NewStartingIndex;
  247. if (oldSize == newSize &&
  248. oldStartIndex == newStartIndex &&
  249. IsDataIndexRealized(oldStartIndex) &&
  250. IsDataIndexRealized(oldStartIndex + oldSize - 1))
  251. {
  252. // Straight up replace of n items within the realization window.
  253. // Removing and adding might causes us to lose the anchor causing us
  254. // to throw away all containers and start from scratch.
  255. // Instead, we can just clear those items and set the element to
  256. // null (sentinel) and let the next measure get new containers for them.
  257. var startRealizedIndex = GetRealizedRangeIndexFromDataIndex(oldStartIndex);
  258. for (int realizedIndex = startRealizedIndex; realizedIndex < startRealizedIndex + oldSize; realizedIndex++)
  259. {
  260. var elementRef = _realizedElements[realizedIndex];
  261. if (elementRef != null)
  262. {
  263. _context.RecycleElement(elementRef);
  264. _realizedElements[realizedIndex] = null;
  265. }
  266. }
  267. }
  268. else
  269. {
  270. OnItemsRemoved(oldStartIndex, oldSize);
  271. OnItemsAdded(newStartIndex, newSize);
  272. }
  273. }
  274. break;
  275. case NotifyCollectionChangedAction.Remove:
  276. {
  277. OnItemsRemoved(args.OldStartingIndex, args.OldItems.Count);
  278. }
  279. break;
  280. case NotifyCollectionChangedAction.Reset:
  281. ClearRealizedRange();
  282. break;
  283. case NotifyCollectionChangedAction.Move:
  284. throw new NotImplementedException();
  285. }
  286. }
  287. }
  288. public int GetElementDataIndex(ILayoutable suggestedAnchor)
  289. {
  290. var it = _realizedElements.IndexOf(suggestedAnchor);
  291. return it != -1 ? GetDataIndexFromRealizedRangeIndex(it) : -1;
  292. }
  293. public int GetDataIndexFromRealizedRangeIndex(int rangeIndex)
  294. {
  295. return IsVirtualizingContext ? rangeIndex + _firstRealizedDataIndex : rangeIndex;
  296. }
  297. private int GetRealizedRangeIndexFromDataIndex(int dataIndex)
  298. {
  299. return IsVirtualizingContext ? dataIndex - _firstRealizedDataIndex : dataIndex;
  300. }
  301. private void DiscardElementsOutsideWindow(in Rect window, ScrollOrientation orientation)
  302. {
  303. // The following illustration explains the cutoff indices.
  304. // We will clear all the realized elements from both ends
  305. // up to the corresponding cutoff index.
  306. // '-' means the element is outside the cutoff range.
  307. // '*' means the element is inside the cutoff range and will be cleared.
  308. //
  309. // Window:
  310. // |______________________________|
  311. // Realization range:
  312. // |*****----------------------------------*********|
  313. // | |
  314. // frontCutoffIndex backCutoffIndex
  315. //
  316. // Note that we tolerate at most one element outside of the window
  317. // because the FlowLayoutAlgorithm.Generate routine stops *after*
  318. // it laid out an element outside the realization window.
  319. // This is also convenient because it protects the anchor
  320. // during a BringIntoView operation during which the anchor may
  321. // not be in the realization window (in fact, the realization window
  322. // might be empty if the BringIntoView is issued before the first
  323. // layout pass).
  324. int realizedRangeSize = GetRealizedElementCount();
  325. int frontCutoffIndex = -1;
  326. int backCutoffIndex = realizedRangeSize;
  327. for (int i = 0;
  328. i < realizedRangeSize &&
  329. !Intersects(window, _realizedElementLayoutBounds[i], orientation);
  330. ++i)
  331. {
  332. ++frontCutoffIndex;
  333. }
  334. for (int i = realizedRangeSize - 1;
  335. i >= 0 &&
  336. !Intersects(window, _realizedElementLayoutBounds[i], orientation);
  337. --i)
  338. {
  339. --backCutoffIndex;
  340. }
  341. if (backCutoffIndex < realizedRangeSize - 1)
  342. {
  343. ClearRealizedRange(backCutoffIndex + 1, realizedRangeSize - backCutoffIndex - 1);
  344. }
  345. if (frontCutoffIndex > 0)
  346. {
  347. ClearRealizedRange(0, Math.Min(frontCutoffIndex, GetRealizedElementCount()));
  348. }
  349. }
  350. private static bool Intersects(in Rect lhs, in Rect rhs, ScrollOrientation orientation)
  351. {
  352. var lhsStart = orientation == ScrollOrientation.Vertical ? lhs.Y : lhs.X;
  353. var lhsEnd = orientation == ScrollOrientation.Vertical ? lhs.Y + lhs.Height : lhs.X + lhs.Width;
  354. var rhsStart = orientation == ScrollOrientation.Vertical ? rhs.Y : rhs.X;
  355. var rhsEnd = orientation == ScrollOrientation.Vertical ? rhs.Y + rhs.Height : rhs.X + rhs.Width;
  356. return lhsEnd >= rhsStart && lhsStart <= rhsEnd;
  357. }
  358. private void OnItemsAdded(int index, int count)
  359. {
  360. // Using the old indices here (before it was updated by the collection change)
  361. // if the insert data index is between the first and last realized data index, we need
  362. // to insert items.
  363. int lastRealizedDataIndex = _firstRealizedDataIndex + GetRealizedElementCount() - 1;
  364. int newStartingIndex = index;
  365. if (newStartingIndex >= _firstRealizedDataIndex &&
  366. newStartingIndex <= lastRealizedDataIndex)
  367. {
  368. // Inserted within the realized range
  369. int insertRangeStartIndex = newStartingIndex - _firstRealizedDataIndex;
  370. for (int i = 0; i < count; i++)
  371. {
  372. // Insert null (sentinel) here instead of an element, that way we dont
  373. // end up creating a lot of elements only to be thrown out in the next layout.
  374. int insertRangeIndex = insertRangeStartIndex + i;
  375. int dataIndex = newStartingIndex + i;
  376. // This is to keep the contiguousness of the mapping
  377. Insert(insertRangeIndex, dataIndex, null);
  378. }
  379. }
  380. else if (index <= _firstRealizedDataIndex)
  381. {
  382. // Items were inserted before the realized range.
  383. // We need to update m_firstRealizedDataIndex;
  384. _firstRealizedDataIndex += count;
  385. }
  386. }
  387. private void OnItemsRemoved(int index, int count)
  388. {
  389. int lastRealizedDataIndex = _firstRealizedDataIndex + _realizedElements.Count - 1;
  390. int startIndex = Math.Max(_firstRealizedDataIndex, index);
  391. int endIndex = Math.Min(lastRealizedDataIndex, index + count - 1);
  392. bool removeAffectsFirstRealizedDataIndex = (index <= _firstRealizedDataIndex);
  393. if (endIndex >= startIndex)
  394. {
  395. ClearRealizedRange(GetRealizedRangeIndexFromDataIndex(startIndex), endIndex - startIndex + 1);
  396. }
  397. if (removeAffectsFirstRealizedDataIndex &&
  398. _firstRealizedDataIndex != -1)
  399. {
  400. _firstRealizedDataIndex -= count;
  401. }
  402. }
  403. }
  404. }