summaryrefslogtreecommitdiff
path: root/Xamarin.Forms.Core/ListProxy.cs
blob: c2f5c9d89554aef11e6c5d4402de928191ce1784 (plain)
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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using Xamarin.Forms.Internals;

namespace Xamarin.Forms
{
	internal sealed class ListProxy : IReadOnlyList<object>, IListProxy, INotifyCollectionChanged
	{
		readonly ICollection _collection;
		readonly IList _list;
		readonly int _windowSize;

		IEnumerator _enumerator;
		int _enumeratorIndex;

		bool _finished;
		HashSet<int> _indexesCounted;

		Dictionary<int, object> _items;
		int _version;

		int _windowIndex;

		internal ListProxy(IEnumerable enumerable, int windowSize = int.MaxValue)
		{
			_windowSize = windowSize;

			ProxiedEnumerable = enumerable;
			_collection = enumerable as ICollection;

			if (_collection == null && enumerable is IReadOnlyCollection<object>)
				_collection = new ReadOnlyListAdapter((IReadOnlyCollection<object>)enumerable);

			_list = enumerable as IList;
			if (_list == null && enumerable is IReadOnlyList<object>)
				_list = new ReadOnlyListAdapter((IReadOnlyList<object>)enumerable);

			var changed = enumerable as INotifyCollectionChanged;
			if (changed != null)
				new WeakNotifyProxy(this, changed);
		}

		public IEnumerable ProxiedEnumerable { get; }

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

		public IEnumerator<object> GetEnumerator()
		{
			return new ProxyEnumerator(this);
		}

		/// <summary>
		///     Gets whether or not the current window contains the <paramref name="item" />.
		/// </summary>
		/// <param name="item">The item to search for.</param>
		/// <returns><c>true</c> if the item was found in a list or the current window, <c>false</c> otherwise.</returns>
		public bool Contains(object item)
		{
			if (_list != null)
				return _list.Contains(item);

			EnsureWindowCreated();

			if (_items != null)
				return _items.Values.Contains(item);

			return false;
		}

		/// <summary>
		///     Gets the index for the <paramref name="item" /> if in a list or the current window.
		/// </summary>
		/// <param name="item">The item to search for.</param>
		/// <returns>The index of the item if in a list or the current window, -1 otherwise.</returns>
		public int IndexOf(object item)
		{
			if (_list != null)
				return _list.IndexOf(item);

			EnsureWindowCreated();

			if (_items != null)
			{
				foreach (KeyValuePair<int, object> kvp in _items)
				{
					if (Equals(kvp.Value, item))
						return kvp.Key;
				}
			}

			return -1;
		}

		public event NotifyCollectionChangedEventHandler CollectionChanged;

		public int Count
		{
			get
			{
				if (_collection != null)
					return _collection.Count;

				EnsureWindowCreated();

				if (_indexesCounted != null)
					return _indexesCounted.Count;

				return 0;
			}
		}

		public object this[int index]
		{
			get
			{
				object value;
				if (!TryGetValue(index, out value))
					throw new ArgumentOutOfRangeException("index");

				return value;
			}
		}

		public void Clear()
		{
			_version++;
			_finished = false;
			_windowIndex = 0;
			_enumeratorIndex = 0;

			if (_enumerator != null)
			{
				var dispose = _enumerator as IDisposable;
				if (dispose != null)
					dispose.Dispose();

				_enumerator = null;
			}

			if (_items != null)
				_items.Clear();
			if (_indexesCounted != null)
				_indexesCounted.Clear();

			OnCountChanged();
			OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
		}

		public event EventHandler CountChanged;

		void ClearRange(int index, int clearCount)
		{
			if (_items == null)
				return;

			for (int i = index; i < index + clearCount; i++)
				_items.Remove(i);
		}

		bool CountIndex(int index)
		{
			if (_collection != null)
				return false;

			// A collection is used in case TryGetValue is called out of order.
			if (_indexesCounted == null)
				_indexesCounted = new HashSet<int>();

			if (_indexesCounted.Contains(index))
				return false;

			_indexesCounted.Add(index);
			return true;
		}

		void EnsureWindowCreated()
		{
			if (_items != null && _items.Count > 0)
				return;

			object value;
			TryGetValue(0, out value);
		}

		void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
		{
			Action action;
			if (_list == null)
			{
				action = Clear;
			}
			else
			{
				action = () =>
				{
					_version++;
					OnCollectionChanged(e);
				};
			}

			CollectionSynchronizationContext sync;
			if (BindingBase.TryGetSynchronizedCollection(ProxiedEnumerable, out sync))
			{
				sync.Callback(ProxiedEnumerable, sync.Context, () =>
				{
					e = e.WithCount(Count);
					Device.BeginInvokeOnMainThread(action);
				}, false);
			}
			else
			{
				e = e.WithCount(Count);
				if (Device.IsInvokeRequired)
					Device.BeginInvokeOnMainThread(action);
				else
					action();
			}
		}

		void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
		{
			NotifyCollectionChangedEventHandler changed = CollectionChanged;
			if (changed != null)
				changed(this, e);
		}

		void OnCountChanged()
		{
			EventHandler changed = CountChanged;
			if (changed != null)
				changed(this, EventArgs.Empty);
		}

		bool TryGetValue(int index, out object value)
		{
			value = null;

			CollectionSynchronizationContext syncContext;
			BindingBase.TryGetSynchronizedCollection(ProxiedEnumerable, out syncContext);

			if (_list != null)
			{
				object indexedValue = null;
				var inRange = false;
				Action getFromList = () =>
				{
					if (index >= _list.Count)
						return;

					indexedValue = _list[index];
					inRange = true;
				};

				if (syncContext != null)
					syncContext.Callback(ProxiedEnumerable, syncContext.Context, getFromList, false);
				else
					getFromList();

				value = indexedValue;
				return inRange;
			}

			if (_collection != null && index >= _collection.Count)
				return false;
			if (_items != null)
			{
				bool found = _items.TryGetValue(index, out value);
				if (found || _finished)
					return found;
			}

			if (index >= _windowIndex + _windowSize)
			{
				int newIndex = index - _windowSize / 2;
				ClearRange(_windowIndex, newIndex - _windowIndex);
				_windowIndex = newIndex;
			}
			else if (index < _windowIndex)
			{
				int clearIndex = _windowIndex;
				int clearSize = _windowSize;
				if (clearIndex <= index + clearSize)
				{
					int diff = index + clearSize - clearIndex;
					clearIndex += diff + 1;
					clearSize -= diff;
				}

				ClearRange(clearIndex, clearSize);
				_windowIndex = 0;

				var dispose = _enumerator as IDisposable;
				if (dispose != null)
					dispose.Dispose();

				_enumerator = null;
				_enumeratorIndex = 0;
			}

			if (_enumerator == null)
				_enumerator = ProxiedEnumerable.GetEnumerator();
			if (_items == null)
				_items = new Dictionary<int, object>();

			var countChanged = false;
			int end = _windowIndex + _windowSize;

			for (; _enumeratorIndex < end; _enumeratorIndex++)
			{
				var moved = false;
				Action move = () =>
				{
					try
					{
						moved = _enumerator.MoveNext();
					}
					catch (InvalidOperationException ioex)
					{
						throw new InvalidOperationException("You must call UpdateNonNotifyingList() after updating a list that does not implement INotifyCollectionChanged", ioex);
					}

					if (!moved)
					{
						var dispose = _enumerator as IDisposable;
						if (dispose != null)
							dispose.Dispose();

						_enumerator = null;
						_enumeratorIndex = 0;
						_finished = true;
					}
				};

				if (syncContext == null)
					move();
				else
					syncContext.Callback(ProxiedEnumerable, syncContext.Context, move, false);

				if (!moved)
					break;

				if (CountIndex(_enumeratorIndex))
					countChanged = true;

				if (_enumeratorIndex >= _windowIndex)
					_items.Add(_enumeratorIndex, _enumerator.Current);
			}

			if (countChanged)
				OnCountChanged();

			return _items.TryGetValue(index, out value);
		}

		class WeakNotifyProxy
		{
			readonly WeakReference<INotifyCollectionChanged> _weakCollection;
			readonly WeakReference<ListProxy> _weakProxy;

			public WeakNotifyProxy(ListProxy proxy, INotifyCollectionChanged incc)
			{
				incc.CollectionChanged += OnCollectionChanged;

				_weakProxy = new WeakReference<ListProxy>(proxy);
				_weakCollection = new WeakReference<INotifyCollectionChanged>(incc);
			}

			void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
			{
				ListProxy proxy;
				if (!_weakProxy.TryGetTarget(out proxy))
				{
					INotifyCollectionChanged collection;
					if (_weakCollection.TryGetTarget(out collection))
						collection.CollectionChanged -= OnCollectionChanged;

					return;
				}

				proxy.OnCollectionChanged(sender, e);
			}
		}

		class ProxyEnumerator : IEnumerator<object>
		{
			readonly ListProxy _proxy;
			readonly int _version;

			int _index;

			public ProxyEnumerator(ListProxy proxy)
			{
				_proxy = proxy;
				_version = proxy._version;
			}

			public void Dispose()
			{
			}

			public bool MoveNext()
			{
				if (_proxy._version != _version)
					throw new InvalidOperationException();

				object value;
				bool next = _proxy.TryGetValue(_index++, out value);
				if (next)
					Current = value;

				return next;
			}

			public void Reset()
			{
				_index = 0;
				Current = null;
			}

			public object Current { get; private set; }
		}

		#region IList

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

		bool IList.IsReadOnly
		{
			get { return true; }
		}

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

		bool ICollection.IsSynchronized
		{
			get { return false; }
		}

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

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

		int IList.Add(object item)
		{
			throw new NotSupportedException();
		}

		void IList.Remove(object item)
		{
			throw new NotSupportedException();
		}

		void IList.Insert(int index, object item)
		{
			throw new NotSupportedException();
		}

		void IList.RemoveAt(int index)
		{
			throw new NotSupportedException();
		}

		void IList.Clear()
		{
			throw new NotSupportedException();
		}

		#endregion
	}
}