ObservableRangeCollection.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  1. using System;
  2. using System.Collections;
  3. using System.Collections.ObjectModel;
  4. namespace InABox.Mobile
  5. {
  6. // Licensed to the .NET Foundation under one or more agreements.
  7. // The .NET Foundation licenses this file to you under the MIT license.
  8. // See the LICENSE file in the project root for more information.
  9. using System.Collections.Generic;
  10. using System.Collections.Specialized;
  11. using System.ComponentModel;
  12. using System.Diagnostics;
  13. using System.Linq;
  14. /// <summary>
  15. /// Implementation of a dynamic data collection based on generic Collection&lt;T&gt;,
  16. /// implementing INotifyCollectionChanged to notify listeners
  17. /// when items get added, removed or the whole list is refreshed.
  18. /// </summary>
  19. public class CoreObservableCollection<T> : ObservableCollection<T>
  20. {
  21. //------------------------------------------------------
  22. //
  23. // Private Fields
  24. //
  25. //------------------------------------------------------
  26. #region Private Fields
  27. [NonSerialized]
  28. private DeferredEventsCollection? _deferredEvents;
  29. #endregion Private Fields
  30. //------------------------------------------------------
  31. //
  32. // Constructors
  33. //
  34. //------------------------------------------------------
  35. #region Constructors
  36. /// <summary>
  37. /// Initializes a new instance of ObservableCollection that is empty and has default initial capacity.
  38. /// </summary>
  39. public CoreObservableCollection() { }
  40. /// <summary>
  41. /// Initializes a new instance of the ObservableCollection class that contains
  42. /// elements copied from the specified collection and has sufficient capacity
  43. /// to accommodate the number of elements copied.
  44. /// </summary>
  45. /// <param name="collection">The collection whose elements are copied to the new list.</param>
  46. /// <remarks>
  47. /// The elements are copied onto the ObservableCollection in the
  48. /// same order they are read by the enumerator of the collection.
  49. /// </remarks>
  50. /// <exception cref="ArgumentNullException"> collection is a null reference </exception>
  51. public CoreObservableCollection(IEnumerable<T> collection) : base(collection) { }
  52. /// <summary>
  53. /// Initializes a new instance of the ObservableCollection class
  54. /// that contains elements copied from the specified list
  55. /// </summary>
  56. /// <param name="list">The list whose elements are copied to the new list.</param>
  57. /// <remarks>
  58. /// The elements are copied onto the ObservableCollection in the
  59. /// same order they are read by the enumerator of the list.
  60. /// </remarks>
  61. /// <exception cref="ArgumentNullException"> list is a null reference </exception>
  62. public CoreObservableCollection(List<T> list) : base(list) { }
  63. #endregion Constructors
  64. //------------------------------------------------------
  65. //
  66. // Public Properties
  67. //
  68. //------------------------------------------------------
  69. #region Public Properties
  70. EqualityComparer<T>? _Comparer;
  71. public EqualityComparer<T> Comparer
  72. {
  73. get => _Comparer ??= EqualityComparer<T>.Default;
  74. private set => _Comparer = value;
  75. }
  76. /// <summary>
  77. /// Gets or sets a value indicating whether this collection acts as a <see cref="HashSet{T}"/>,
  78. /// disallowing duplicate items, based on <see cref="Comparer"/>.
  79. /// This might indeed consume background performance, but in the other hand,
  80. /// it will pay off in UI performance as less required UI updates are required.
  81. /// </summary>
  82. public bool AllowDuplicates { get; set; } = true;
  83. #endregion Public Properties
  84. //------------------------------------------------------
  85. //
  86. // Public Methods
  87. //
  88. //------------------------------------------------------
  89. #region Public Methods
  90. /// <summary>
  91. /// Adds the elements of the specified collection to the end of the <see cref="ObservableCollection{T}"/>.
  92. /// </summary>
  93. /// <param name="collection">
  94. /// The collection whose elements should be added to the end of the <see cref="ObservableCollection{T}"/>.
  95. /// The collection itself cannot be null, but it can contain elements that are null, if type T is a reference type.
  96. /// </param>
  97. /// <exception cref="ArgumentNullException"><paramref name="collection"/> is null.</exception>
  98. public void AddRange(IEnumerable<T> collection)
  99. {
  100. InsertRange(Count, collection);
  101. }
  102. /// <summary>
  103. /// Inserts the elements of a collection into the <see cref="ObservableCollection{T}"/> at the specified index.
  104. /// </summary>
  105. /// <param name="index">The zero-based index at which the new elements should be inserted.</param>
  106. /// <param name="collection">The collection whose elements should be inserted into the List<T>.
  107. /// The collection itself cannot be null, but it can contain elements that are null, if type T is a reference type.</param>
  108. /// <exception cref="ArgumentNullException"><paramref name="collection"/> is null.</exception>
  109. /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is not in the collection range.</exception>
  110. public void InsertRange(int index, IEnumerable<T> collection)
  111. {
  112. if (collection == null)
  113. throw new ArgumentNullException(nameof(collection));
  114. if (index < 0)
  115. throw new ArgumentOutOfRangeException(nameof(index));
  116. if (index > Count)
  117. throw new ArgumentOutOfRangeException(nameof(index));
  118. if (!AllowDuplicates)
  119. collection =
  120. collection
  121. .Distinct(Comparer)
  122. .Where(item => !Items.Contains(item, Comparer))
  123. .ToList();
  124. if (collection is ICollection<T> countable)
  125. {
  126. if (countable.Count == 0)
  127. return;
  128. }
  129. else if (!collection.Any())
  130. return;
  131. CheckReentrancy();
  132. //expand the following couple of lines when adding more constructors.
  133. var target = (List<T>)Items;
  134. target.InsertRange(index, collection);
  135. OnEssentialPropertiesChanged();
  136. if (!(collection is IList list))
  137. list = new List<T>(collection);
  138. OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, list, index));
  139. }
  140. /// <summary>
  141. /// Removes the first occurence of each item in the specified collection from the <see cref="ObservableCollection{T}"/>.
  142. /// </summary>
  143. /// <param name="collection">The items to remove.</param>
  144. /// <exception cref="ArgumentNullException"><paramref name="collection"/> is null.</exception>
  145. public void RemoveRange(IEnumerable<T> collection)
  146. {
  147. if (collection == null)
  148. throw new ArgumentNullException(nameof(collection));
  149. if (Count == 0)
  150. return;
  151. else if (collection is ICollection<T> countable)
  152. {
  153. if (countable.Count == 0)
  154. return;
  155. else if (countable.Count == 1)
  156. using (IEnumerator<T> enumerator = countable.GetEnumerator())
  157. {
  158. enumerator.MoveNext();
  159. Remove(enumerator.Current);
  160. return;
  161. }
  162. }
  163. else if (!collection.Any())
  164. return;
  165. CheckReentrancy();
  166. var clusters = new Dictionary<int, List<T>>();
  167. var lastIndex = -1;
  168. List<T>? lastCluster = null;
  169. foreach (T item in collection)
  170. {
  171. var index = IndexOf(item);
  172. if (index < 0)
  173. continue;
  174. Items.RemoveAt(index);
  175. if (lastIndex == index && lastCluster != null)
  176. lastCluster.Add(item);
  177. else
  178. clusters[lastIndex = index] = lastCluster = new List<T> { item };
  179. }
  180. OnEssentialPropertiesChanged();
  181. if (Count == 0)
  182. OnCollectionReset();
  183. else
  184. foreach (KeyValuePair<int, List<T>> cluster in clusters)
  185. OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, cluster.Value, cluster.Key));
  186. }
  187. /// <summary>
  188. /// Iterates over the collection and removes all items that satisfy the specified match.
  189. /// </summary>
  190. /// <remarks>The complexity is O(n).</remarks>
  191. /// <param name="match"></param>
  192. /// <returns>Returns the number of elements that where </returns>
  193. /// <exception cref="ArgumentNullException"><paramref name="match"/> is null.</exception>
  194. public int RemoveAll(Predicate<T> match)
  195. {
  196. return RemoveAll(0, Count, match);
  197. }
  198. /// <summary>
  199. /// Iterates over the specified range within the collection and removes all items that satisfy the specified match.
  200. /// </summary>
  201. /// <remarks>The complexity is O(n).</remarks>
  202. /// <param name="index">The index of where to start performing the search.</param>
  203. /// <param name="count">The number of items to iterate on.</param>
  204. /// <param name="match"></param>
  205. /// <returns>Returns the number of elements that where </returns>
  206. /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is out of range.</exception>
  207. /// <exception cref="ArgumentOutOfRangeException"><paramref name="count"/> is out of range.</exception>
  208. /// <exception cref="ArgumentNullException"><paramref name="match"/> is null.</exception>
  209. public int RemoveAll(int index, int count, Predicate<T> match)
  210. {
  211. if (index < 0)
  212. throw new ArgumentOutOfRangeException(nameof(index));
  213. if (count < 0)
  214. throw new ArgumentOutOfRangeException(nameof(count));
  215. if (index + count > Count)
  216. throw new ArgumentOutOfRangeException(nameof(index));
  217. if (match == null)
  218. throw new ArgumentNullException(nameof(match));
  219. if (Count == 0)
  220. return 0;
  221. List<T>? cluster = null;
  222. var clusterIndex = -1;
  223. var removedCount = 0;
  224. using (BlockReentrancy())
  225. using (DeferEvents())
  226. {
  227. for (var i = 0; i < count; i++, index++)
  228. {
  229. T item = Items[index];
  230. if (match(item))
  231. {
  232. Items.RemoveAt(index);
  233. removedCount++;
  234. if (clusterIndex == index)
  235. {
  236. Debug.Assert(cluster != null);
  237. cluster!.Add(item);
  238. }
  239. else
  240. {
  241. cluster = new List<T> { item };
  242. clusterIndex = index;
  243. }
  244. index--;
  245. }
  246. else if (clusterIndex > -1)
  247. {
  248. OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, cluster, clusterIndex));
  249. clusterIndex = -1;
  250. cluster = null;
  251. }
  252. }
  253. if (clusterIndex > -1)
  254. OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, cluster, clusterIndex));
  255. }
  256. if (removedCount > 0)
  257. OnEssentialPropertiesChanged();
  258. return removedCount;
  259. }
  260. /// <summary>
  261. /// Removes a range of elements from the <see cref="ObservableCollection{T}"/>>.
  262. /// </summary>
  263. /// <param name="index">The zero-based starting index of the range of elements to remove.</param>
  264. /// <param name="count">The number of elements to remove.</param>
  265. /// <exception cref="ArgumentOutOfRangeException">The specified range is exceeding the collection.</exception>
  266. public void RemoveRange(int index, int count)
  267. {
  268. if (index < 0)
  269. throw new ArgumentOutOfRangeException(nameof(index));
  270. if (count < 0)
  271. throw new ArgumentOutOfRangeException(nameof(count));
  272. if (index + count > Count)
  273. throw new ArgumentOutOfRangeException(nameof(index));
  274. if (count == 0)
  275. return;
  276. if (count == 1)
  277. {
  278. RemoveItem(index);
  279. return;
  280. }
  281. //Items will always be List<T>, see constructors
  282. var items = (List<T>)Items;
  283. List<T> removedItems = items.GetRange(index, count);
  284. CheckReentrancy();
  285. items.RemoveRange(index, count);
  286. OnEssentialPropertiesChanged();
  287. if (Count == 0)
  288. OnCollectionReset();
  289. else
  290. OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, removedItems, index));
  291. }
  292. /// <summary>
  293. /// Clears the current collection and replaces it with the specified collection,
  294. /// using <see cref="Comparer"/>.
  295. /// </summary>
  296. /// <param name="collection">The items to fill the collection with, after clearing it.</param>
  297. /// <exception cref="ArgumentNullException"><paramref name="collection"/> is null.</exception>
  298. public void ReplaceRange(IEnumerable<T> collection)
  299. {
  300. ReplaceRange(0, Count, collection);
  301. }
  302. /// <summary>
  303. /// Removes the specified range and inserts the specified collection in its position, leaving equal items in equal positions intact.
  304. /// </summary>
  305. /// <param name="index">The index of where to start the replacement.</param>
  306. /// <param name="count">The number of items to be replaced.</param>
  307. /// <param name="collection">The collection to insert in that location.</param>
  308. /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is out of range.</exception>
  309. /// <exception cref="ArgumentOutOfRangeException"><paramref name="count"/> is out of range.</exception>
  310. /// <exception cref="ArgumentNullException"><paramref name="collection"/> is null.</exception>
  311. /// <exception cref="ArgumentNullException"><paramref name="comparer"/> is null.</exception>
  312. public void ReplaceRange(int index, int count, IEnumerable<T> collection)
  313. {
  314. if (index < 0)
  315. throw new ArgumentOutOfRangeException(nameof(index));
  316. if (count < 0)
  317. throw new ArgumentOutOfRangeException(nameof(count));
  318. if (index + count > Count)
  319. throw new ArgumentOutOfRangeException(nameof(index));
  320. if (collection == null)
  321. throw new ArgumentNullException(nameof(collection));
  322. if (!AllowDuplicates)
  323. collection =
  324. collection
  325. .Distinct(Comparer)
  326. .ToList();
  327. if (collection is ICollection<T> countable)
  328. {
  329. if (countable.Count == 0)
  330. {
  331. RemoveRange(index, count);
  332. return;
  333. }
  334. }
  335. else if (!collection.Any())
  336. {
  337. RemoveRange(index, count);
  338. return;
  339. }
  340. if (index + count == 0)
  341. {
  342. InsertRange(0, collection);
  343. return;
  344. }
  345. if (!(collection is IList<T> list))
  346. list = new List<T>(collection);
  347. using (BlockReentrancy())
  348. using (DeferEvents())
  349. {
  350. var rangeCount = index + count;
  351. var addedCount = list.Count;
  352. var changesMade = false;
  353. List<T>?
  354. newCluster = null,
  355. oldCluster = null;
  356. int i = index;
  357. for (; i < rangeCount && i - index < addedCount; i++)
  358. {
  359. //parallel position
  360. T old = this[i], @new = list[i - index];
  361. if (Comparer.Equals(old, @new))
  362. {
  363. OnRangeReplaced(i, newCluster!, oldCluster!);
  364. continue;
  365. }
  366. else
  367. {
  368. Items[i] = @new;
  369. if (newCluster == null)
  370. {
  371. Debug.Assert(oldCluster == null);
  372. newCluster = new List<T> { @new };
  373. oldCluster = new List<T> { old };
  374. }
  375. else
  376. {
  377. newCluster.Add(@new);
  378. oldCluster!.Add(old);
  379. }
  380. changesMade = true;
  381. }
  382. }
  383. OnRangeReplaced(i, newCluster!, oldCluster!);
  384. //exceeding position
  385. if (count != addedCount)
  386. {
  387. var items = (List<T>)Items;
  388. if (count > addedCount)
  389. {
  390. var removedCount = rangeCount - addedCount;
  391. T[] removed = new T[removedCount];
  392. items.CopyTo(i, removed, 0, removed.Length);
  393. items.RemoveRange(i, removedCount);
  394. OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, removed, i));
  395. }
  396. else
  397. {
  398. var k = i - index;
  399. T[] added = new T[addedCount - k];
  400. for (int j = k; j < addedCount; j++)
  401. {
  402. T @new = list[j];
  403. added[j - k] = @new;
  404. }
  405. items.InsertRange(i, added);
  406. OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, added, i));
  407. }
  408. OnEssentialPropertiesChanged();
  409. }
  410. else if (changesMade)
  411. {
  412. OnIndexerPropertyChanged();
  413. }
  414. }
  415. }
  416. #endregion Public Methods
  417. //------------------------------------------------------
  418. //
  419. // Protected Methods
  420. //
  421. //------------------------------------------------------
  422. #region Protected Methods
  423. /// <summary>
  424. /// Called by base class Collection&lt;T&gt; when the list is being cleared;
  425. /// raises a CollectionChanged event to any listeners.
  426. /// </summary>
  427. protected override void ClearItems()
  428. {
  429. if (Count == 0)
  430. return;
  431. CheckReentrancy();
  432. base.ClearItems();
  433. OnEssentialPropertiesChanged();
  434. OnCollectionReset();
  435. }
  436. /// <inheritdoc/>
  437. protected override void InsertItem(int index, T item)
  438. {
  439. if (!AllowDuplicates && Items.Contains(item))
  440. return;
  441. base.InsertItem(index, item);
  442. }
  443. /// <inheritdoc/>
  444. protected override void SetItem(int index, T item)
  445. {
  446. if (AllowDuplicates)
  447. {
  448. if (Comparer.Equals(this[index], item))
  449. return;
  450. }
  451. else
  452. if (Items.Contains(item, Comparer))
  453. return;
  454. CheckReentrancy();
  455. T oldItem = this[index];
  456. base.SetItem(index, item);
  457. OnIndexerPropertyChanged();
  458. OnCollectionChanged(NotifyCollectionChangedAction.Replace, oldItem!, item!, index);
  459. }
  460. /// <summary>
  461. /// Raise CollectionChanged event to any listeners.
  462. /// Properties/methods modifying this ObservableCollection will raise
  463. /// a collection changed event through this virtual method.
  464. /// </summary>
  465. /// <remarks>
  466. /// When overriding this method, either call its base implementation
  467. /// or call <see cref="BlockReentrancy"/> to guard against reentrant collection changes.
  468. /// </remarks>
  469. protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
  470. {
  471. if (_deferredEvents != null)
  472. {
  473. _deferredEvents.Add(e);
  474. return;
  475. }
  476. base.OnCollectionChanged(e);
  477. }
  478. protected virtual IDisposable DeferEvents() => new DeferredEventsCollection(this);
  479. #endregion Protected Methods
  480. //------------------------------------------------------
  481. //
  482. // Private Methods
  483. //
  484. //------------------------------------------------------
  485. #region Private Methods
  486. /// <summary>
  487. /// Helper to raise Count property and the Indexer property.
  488. /// </summary>
  489. void OnEssentialPropertiesChanged()
  490. {
  491. OnPropertyChanged(EventArgsCache.CountPropertyChanged);
  492. OnIndexerPropertyChanged();
  493. }
  494. /// <summary>
  495. /// /// Helper to raise a PropertyChanged event for the Indexer property
  496. /// /// </summary>
  497. void OnIndexerPropertyChanged() =>
  498. OnPropertyChanged(EventArgsCache.IndexerPropertyChanged);
  499. /// <summary>
  500. /// Helper to raise CollectionChanged event to any listeners
  501. /// </summary>
  502. void OnCollectionChanged(NotifyCollectionChangedAction action, object oldItem, object newItem, int index) =>
  503. OnCollectionChanged(new NotifyCollectionChangedEventArgs(action, newItem, oldItem, index));
  504. /// <summary>
  505. /// Helper to raise CollectionChanged event with action == Reset to any listeners
  506. /// </summary>
  507. void OnCollectionReset() =>
  508. OnCollectionChanged(EventArgsCache.ResetCollectionChanged);
  509. /// <summary>
  510. /// Helper to raise event for clustered action and clear cluster.
  511. /// </summary>
  512. /// <param name="followingItemIndex">The index of the item following the replacement block.</param>
  513. /// <param name="newCluster"></param>
  514. /// <param name="oldCluster"></param>
  515. //TODO should have really been a local method inside ReplaceRange(int index, int count, IEnumerable<T> collection, IEqualityComparer<T> comparer),
  516. //move when supported language version updated.
  517. void OnRangeReplaced(int followingItemIndex, ICollection<T> newCluster, ICollection<T> oldCluster)
  518. {
  519. if (oldCluster == null || oldCluster.Count == 0)
  520. {
  521. Debug.Assert(newCluster == null || newCluster.Count == 0);
  522. return;
  523. }
  524. OnCollectionChanged(
  525. new NotifyCollectionChangedEventArgs(
  526. NotifyCollectionChangedAction.Replace,
  527. new List<T>(newCluster),
  528. new List<T>(oldCluster),
  529. followingItemIndex - oldCluster.Count));
  530. oldCluster.Clear();
  531. newCluster.Clear();
  532. }
  533. #endregion Private Methods
  534. //------------------------------------------------------
  535. //
  536. // Private Types
  537. //
  538. //------------------------------------------------------
  539. #region Private Types
  540. sealed class DeferredEventsCollection : List<NotifyCollectionChangedEventArgs>, IDisposable
  541. {
  542. readonly CoreObservableCollection<T> _collection;
  543. public DeferredEventsCollection(CoreObservableCollection<T> collection)
  544. {
  545. Debug.Assert(collection != null);
  546. Debug.Assert(collection._deferredEvents == null);
  547. _collection = collection;
  548. _collection._deferredEvents = this;
  549. }
  550. public void Dispose()
  551. {
  552. _collection._deferredEvents = null;
  553. foreach (var args in this)
  554. _collection.OnCollectionChanged(args);
  555. }
  556. }
  557. #endregion Private Types
  558. }
  559. /// <remarks>
  560. /// To be kept outside <see cref="ObservableCollection{T}"/>, since otherwise, a new instance will be created for each generic type used.
  561. /// </remarks>
  562. internal static class EventArgsCache
  563. {
  564. internal static readonly PropertyChangedEventArgs CountPropertyChanged = new PropertyChangedEventArgs("Count");
  565. internal static readonly PropertyChangedEventArgs IndexerPropertyChanged = new PropertyChangedEventArgs("Item[]");
  566. internal static readonly NotifyCollectionChangedEventArgs ResetCollectionChanged = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset);
  567. }
  568. }