Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 712 lines (579 sloc) 23.277 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;

namespace VirtualCollection.VirtualCollection
{
    /// <summary>
    /// Implements a collection that loads its items by pages only when requested
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <remarks>The trick to ensuring that the silverlight datagrid doesn't attempt to enumerate all
    /// items from its DataSource in one shot is to implement both IList and ICollectionView.</remarks>
    public class VirtualCollection<T> : IList<VirtualItem<T>>, IList, ICollectionView, INotifyPropertyChanged,
                                        IEnquireAboutItemVisibility where T : class
    {
        private const int IndividualItemNotificationLimit = 100;
        private const int MaxConcurrentPageRequests = 4;

        public event NotifyCollectionChangedEventHandler CollectionChanged;

        public event PropertyChangedEventHandler PropertyChanged;
        public event EventHandler<QueryItemVisibilityEventArgs> QueryItemVisibility;
        public event EventHandler<ItemsRealizedEventArgs> ItemsRealized;
        public event CurrentChangingEventHandler CurrentChanging;
        public event EventHandler CurrentChanged;
        private readonly IVirtualCollectionSource<T> _source;
        private readonly int _pageSize;
        private readonly IEqualityComparer<T> _equalityComparer;

        private uint _state; // used to ensure that data-requests are not stale

        private readonly SparseList<VirtualItem<T>> _virtualItems;
        private readonly HashSet<int> _fetchedPages = new HashSet<int>();
        private readonly HashSet<int> _requestedPages = new HashSet<int>();

        private readonly MostRecentUsedList<int> _mostRecentlyRequestedPages;
        private int _itemCount;
        private readonly TaskScheduler _synchronizationContextScheduler;
        private bool _isRefreshDeferred;
        private int _currentItem;

        private int _inProcessPageRequests;
        private Stack<PageRequest> _pendingPageRequests = new Stack<PageRequest>();

        private readonly SortDescriptionCollection _sortDescriptions = new SortDescriptionCollection();

        public VirtualCollection(IVirtualCollectionSource<T> source, int pageSize, int cachedPages)
            : this(source, pageSize, cachedPages, EqualityComparer<T>.Default)
        {

        }

        public VirtualCollection(IVirtualCollectionSource<T> source, int pageSize, int cachedPages,
                                 IEqualityComparer<T> equalityComparer)
        {
            if (pageSize < 1)
                throw new ArgumentException("pageSize must be bigger than 0");

            if (equalityComparer == null)
                throw new ArgumentNullException("equalityComparer");

            _source = source;
            _source.CollectionChanged += HandleSourceCollectionChanged;
            _source.CountChanged += HandleCountChanged;
            _pageSize = pageSize;
            _equalityComparer = equalityComparer;
            _virtualItems = CreateItemsCache(pageSize);
            _currentItem = -1;
            _synchronizationContextScheduler = TaskScheduler.FromCurrentSynchronizationContext();
            _mostRecentlyRequestedPages = new MostRecentUsedList<int>(cachedPages);
            _mostRecentlyRequestedPages.ItemEvicted += HandlePageEvicted;

            (_sortDescriptions as INotifyCollectionChanged).CollectionChanged += HandleSortDescriptionsChanged;
        }



        public IVirtualCollectionSource<T> Source
        {
            get { return _source; }
        }
        public CultureInfo Culture { get; set; }

        public IEnumerable SourceCollection
        {
            get { return this; }
        }

        public Predicate<object> Filter
        {
            get { throw new NotImplementedException(); }
            set { throw new NotImplementedException(); }
        }

        public bool CanFilter
        {
            get { return false; }
        }

        public SortDescriptionCollection SortDescriptions
        {
            get { return _sortDescriptions; }
        }

        public bool CanSort
        {
            get { return true; }
        }

        public bool CanGroup
        {
            get { return false; }
        }

        public ObservableCollection<GroupDescription> GroupDescriptions
        {
            get { throw new NotImplementedException(); }
        }

        public ReadOnlyObservableCollection<object> Groups
        {
            get { throw new NotImplementedException(); }
        }

        public bool IsEmpty
        {
            get { return _itemCount == 0; }
        }

        public object CurrentItem
        {
            get { return 0 < CurrentPosition && CurrentPosition < _itemCount ? this[CurrentPosition] : null; }
        }

        public int CurrentPosition
        {
            get { return _currentItem; }
            private set
            {
                _currentItem = value;
                OnCurrentChanged(EventArgs.Empty);
            }
        }
        public bool IsCurrentAfterLast
        {
            get { return CurrentPosition >= _itemCount; }
        }

        public bool IsCurrentBeforeFirst
        {
            get { return CurrentPosition < 0; }
        }
        public int Count
        {
            get { return _itemCount; }
        }

        object ICollection.SyncRoot
        {
            get { throw new NotImplementedException(); }
        }

        public bool IsSynchronized
        {
            get { return false; }
        }

        public bool IsReadOnly
        {
            get { return true; }
        }

        bool IList.IsFixedSize
        {
            get { return false; }
        }

        protected uint State
        {
            get { return _state; }
        }

        public void RealizeItemRequested(int index)
        {
            var page = index / _pageSize;
            BeginGetPage(page);
        }

        public void Refresh()
        {
            Refresh(RefreshMode.PermitStaleDataWhilstRefreshing);
        }

        public void Refresh(RefreshMode mode)
        {
            if (!_isRefreshDeferred)
                _source.Refresh(mode);
        }

        private void HandlePageEvicted(object sender, ItemEvictedEventArgs<int> e)
        {
            _requestedPages.Remove(e.Item);
            _fetchedPages.Remove(e.Item);
            _virtualItems.RemoveRange(e.Item * _pageSize, _pageSize);
        }

        private SparseList<VirtualItem<T>> CreateItemsCache(int fetchPageSize)
        {
            // we don't want the sparse list to have pages that are too small,
            // because that will harm performance by fragmenting the list across memory,
            // but too big, and we'll be wasting lots of space
            const int TargetSparseListPageSize = 100;

            var pageSize = fetchPageSize;

            if (pageSize < TargetSparseListPageSize)
            {
                // make pageSize the smallest multiple of fetchPageSize that is bigger than TargetSparseListPageSize
                pageSize = (int)Math.Ceiling((double)TargetSparseListPageSize / pageSize) * pageSize;
            }

            return new SparseList<VirtualItem<T>>(pageSize);
        }

        private void HandleSortDescriptionsChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            Refresh();
        }

        private void HandleCountChanged(object sender, EventArgs e)
        {
            Task.Factory.StartNew(UpdateCount, CancellationToken.None, TaskCreationOptions.None,
                                  _synchronizationContextScheduler);
        }

        private void HandleSourceCollectionChanged(object sender, VirtualCollectionSourceChangedEventArgs e)
        {
            if (e.ChangeType == ChangeType.Refresh)
            {
                Task.Factory.StartNew(UpdateData, CancellationToken.None,
                                      TaskCreationOptions.None, _synchronizationContextScheduler);
            }
            else if (e.ChangeType == ChangeType.Reset)
            {
                Task.Factory.StartNew(Reset, CancellationToken.None,
                                      TaskCreationOptions.None, _synchronizationContextScheduler);
            }
        }

        private void MarkExistingItemsAsStale()
        {
            foreach (var page in _fetchedPages)
            {
                var startIndex = page * _pageSize;
                var endIndex = (page + 1) * _pageSize;

                for (int i = startIndex; i < endIndex; i++)
                {
                    if (_virtualItems[i] != null)
                        _virtualItems[i].IsStale = true;
                }
            }
        }

        private void BeginGetPage(int page)
        {
            if (IsPageAlreadyRequested(page))
                return;

            _mostRecentlyRequestedPages.Add(page);
            _requestedPages.Add(page);

            _pendingPageRequests.Push(new PageRequest(page, State));

            ProcessPageRequests();
        }

        private void ProcessPageRequests()
        {
            while (_inProcessPageRequests < MaxConcurrentPageRequests && _pendingPageRequests.Count > 0)
            {
                var request = _pendingPageRequests.Pop();

                // if we encounter a requested posted for an early collection state,
                // we can ignore it, and all that came before it
                if (State != request.StateWhenRequested)
                {
                    _pendingPageRequests.Clear();
                    break;
                }

                // check that the page is still requested (the user might have scrolled, causing the
                // page to be ejected from the cache
                if (!_requestedPages.Contains(request.Page))
                    break;

                _inProcessPageRequests++;

                _source.GetPageAsync(request.Page * _pageSize, _pageSize, _sortDescriptions).ContinueWith(
                    t =>
                    {
                        if (!t.IsFaulted)
                            UpdatePage(request.Page, t.Result, request.StateWhenRequested);
                        else
                            MarkPageAsError(request.Page, request.StateWhenRequested);

                        // fire off any further requests
                        _inProcessPageRequests--;
                        ProcessPageRequests();
                    },
                    _synchronizationContextScheduler);
            }
        }

        private void MarkPageAsError(int page, uint stateWhenRequestInitiated)
        {
            if (stateWhenRequestInitiated != State)
                return;

            var stillRelevant = _requestedPages.Remove(page);
            if (!stillRelevant)
                return;

            var startIndex = page * _pageSize;

            for (int i = 0; i < _pageSize; i++)
            {
                var index = startIndex + i;
                var virtualItem = _virtualItems[index];
                if (virtualItem != null)
                    virtualItem.ErrorFetchingValue();
            }
        }

        private bool IsPageAlreadyRequested(int page)
        {
            return _fetchedPages.Contains(page) || _requestedPages.Contains(page);
        }

        private void UpdatePage(int page, IList<T> results, uint stateWhenRequested)
        {
            if (stateWhenRequested != State)
            {
                // this request may contain out-of-date data, so ignore it
                return;
            }

            bool stillRelevant = _requestedPages.Remove(page);
            if (!stillRelevant)
                return;

            _fetchedPages.Add(page);

            var startIndex = page * _pageSize;

            // guard against rogue collection sources returning too many results
            var count = Math.Min(results.Count, _pageSize);

            for (int i = 0; i < count; i++)
            {
                var index = startIndex + i;
                var virtualItem = _virtualItems[index] ?? (_virtualItems[index] = new VirtualItem<T>(this, index));
                if (virtualItem.Item == null || results[i] == null || !_equalityComparer.Equals(virtualItem.Item, results[i]))
                    virtualItem.SupplyValue(results[i]);
            }

            if (count > 0)
                OnItemsRealized(new ItemsRealizedEventArgs(startIndex, count));
        }

        protected void UpdateData()
        {
            IncrementState();

            MarkExistingItemsAsStale();

            _fetchedPages.Clear();
            _requestedPages.Clear();

            UpdateCount();

            var queryItemVisibilityArgs = new QueryItemVisibilityEventArgs();
            OnQueryItemVisibility(queryItemVisibilityArgs);

            if (queryItemVisibilityArgs.FirstVisibleIndex.HasValue)
            {
                var firstVisiblePage = queryItemVisibilityArgs.FirstVisibleIndex.Value / _pageSize;
                var lastVisiblePage = queryItemVisibilityArgs.LastVisibleIndex.Value / _pageSize;

                int numberOfVisiblePages = lastVisiblePage - firstVisiblePage + 1;
                EnsurePageCacheSize(numberOfVisiblePages);

                for (int i = firstVisiblePage; i <= lastVisiblePage; i++)
                {
                    BeginGetPage(i);
                }
            }
            else
            {
                // in this case we have no way of knowing which items are currently visible,
                // so we signal a collection reset, and wait to see which pages are requested by the UI
                OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
            }
        }

        private void IncrementState()
        {
            _state++;
        }

        private void EnsurePageCacheSize(int numberOfPages)
        {
            if (_mostRecentlyRequestedPages.Size < numberOfPages)
                _mostRecentlyRequestedPages.Size = numberOfPages;
        }

        private void Reset()
        {
            IncrementState();

            foreach (var page in _fetchedPages)
            {
                var startIndex = page * _pageSize;
                var endIndex = (page + 1) * _pageSize;

                for (int i = startIndex; i < endIndex; i++)
                {
                    if (_virtualItems[i] != null)
                        _virtualItems[i].ClearValue();
                }
            }

            _fetchedPages.Clear();
            _requestedPages.Clear();

            UpdateCount(0);
            UpdateCount();
        }

        private void UpdateCount()
        {
            if (_source.Count.HasValue)
            {
                UpdateCount(_source.Count.Value);
            }
            else
            {
                // if the Count is null, that indicates that
                // the VirtualCollectionSource needs us to fetch a page before it will know how many elements there are
                BeginGetPage(0);
            }
        }

        private void UpdateCount(int count)
        {
            if (_itemCount == count)
                return;

            var wasCurrentBeyondLast = IsCurrentAfterLast;

            var originalItemCount = _itemCount;
            var delta = count - originalItemCount;
            _itemCount = count;

            if (IsCurrentAfterLast && !wasCurrentBeyondLast)
                UpdateCurrentPosition(_itemCount - 1, allowCancel: false);

            OnPropertyChanged(new PropertyChangedEventArgs("Count"));

            if (Math.Abs(delta) > IndividualItemNotificationLimit || _itemCount == 0)
                OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
            else if (delta > 0)
            {
                for (int i = 0; i < delta; i++)
                {
                    OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, null,
                                                                             originalItemCount + i));
                }
            }
            else if (delta < 0)
            {
                for (int i = 1; i <= Math.Abs(delta); i++)
                {
                    OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove,
                                                                             _virtualItems[originalItemCount - i],
                                                                             originalItemCount - i));
                }
            }
        }

        public int IndexOf(VirtualItem<T> item)
        {
            return item.Index;
        }

        public bool Contains(object item)
        {
            return item is VirtualItem<T> && Contains(item as VirtualItem<T>);
        }

        object IList.this[int index]
        {
            get { return this[index]; }
            set { throw new NotImplementedException(); }
        }

        public VirtualItem<T> this[int index]
        {
            get
            {
                if (index >= Count)
                {
                    throw new ArgumentOutOfRangeException("index");
                }

                RealizeItemRequested(index);
                return _virtualItems[index] ?? (_virtualItems[index] = new VirtualItem<T>(this, index));
            }
            set { throw new NotImplementedException(); }
        }

        public IDisposable DeferRefresh()
        {
            _isRefreshDeferred = true;

            return new Disposer(() =>
            {
                _isRefreshDeferred = false;
                Refresh();
            });
        }

        public bool MoveCurrentToFirst()
        {
            return UpdateCurrentPosition(0);
        }

        public bool MoveCurrentToLast()
        {
            return UpdateCurrentPosition(_itemCount - 1);
        }

        public bool MoveCurrentToNext()
        {
            return UpdateCurrentPosition(CurrentPosition + 1);
        }

        public bool MoveCurrentToPrevious()
        {
            return UpdateCurrentPosition(CurrentPosition - 1);
        }

        public bool MoveCurrentTo(object item)
        {
            return MoveCurrentToPosition(((IList)this).IndexOf(item));
        }

        public bool MoveCurrentToPosition(int position)
        {
            return UpdateCurrentPosition(position);
        }

        private bool UpdateCurrentPosition(int newCurrentPosition, bool allowCancel = true)
        {
            var changingEventArgs = new CurrentChangingEventArgs(allowCancel);

            OnCurrentChanging(changingEventArgs);

            if (!changingEventArgs.Cancel)
            {
                CurrentPosition = newCurrentPosition;
            }

            return !IsCurrentBeforeFirst && !IsCurrentAfterLast;
        }

        protected void OnCurrentChanging(CurrentChangingEventArgs e)
        {
            var handler = CurrentChanging;
            if (handler != null) handler(this, e);
        }


        protected void OnCurrentChanged(EventArgs e)
        {
            var handler = CurrentChanged;
            if (handler != null) handler(this, e);
        }

        protected void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
        {
            var handler = CollectionChanged;
            if (handler != null) handler(this, e);
        }

        protected void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            var handler = PropertyChanged;
            if (handler != null) handler(this, e);
        }

        protected void OnItemsRealized(ItemsRealizedEventArgs e)
        {
            var handler = ItemsRealized;
            if (handler != null) handler(this, e);
        }

        protected void OnQueryItemVisibility(QueryItemVisibilityEventArgs e)
        {
            var handler = QueryItemVisibility;
            if (handler != null) handler(this, e);
        }

        public IEnumerator<VirtualItem<T>> GetEnumerator()
        {
            for (var i = 0; i < _itemCount; i++)
            {
                yield return this[i];
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public bool Contains(VirtualItem<T> item)
        {
            return item.Parent == this;
        }

        public void CopyTo(VirtualItem<T>[] array, int arrayIndex)
        {
            throw new NotImplementedException();
        }

        void ICollection.CopyTo(Array array, int index)
        {
            throw new NotImplementedException();
        }

        public void Add(VirtualItem<T> item)
        {
            throw new NotImplementedException();
        }

        int IList.Add(object value)
        {
            throw new NotImplementedException();
        }

        bool IList.Contains(object value)
        {
            return value is VirtualItem<T> && Contains(value as VirtualItem<T>);
        }

        public void Clear()
        {
            throw new NotImplementedException();
        }

        int IList.IndexOf(object value)
        {
            var virtualItem = value as VirtualItem<T>;
            return virtualItem == null ? -1 : virtualItem.Index;
        }

        void IList.Insert(int index, object value)
        {
            throw new NotImplementedException();
        }

        void IList.Remove(object value)
        {
            throw new NotImplementedException();
        }

        public bool Remove(VirtualItem<T> item)
        {
            throw new NotImplementedException();
        }

        public void Insert(int index, VirtualItem<T> item)
        {
            throw new NotImplementedException();
        }

        public void RemoveAt(int index)
        {
            throw new NotImplementedException();
        }

        private struct PageRequest
        {
            public readonly int Page;
            public readonly uint StateWhenRequested;

            public PageRequest(int page, uint state)
            {
                Page = page;
                StateWhenRequested = state;
            }
        }
    }
}
Something went wrong with that request. Please try again.