/
ListViewBaseSource.iOS.cs
982 lines (857 loc) · 31.2 KB
/
ListViewBaseSource.iOS.cs
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
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Uno.Extensions;
using Uno.UI.Views.Controls;
using Windows.UI.Xaml.Data;
using Uno.UI.Converters;
using Uno.Client;
using System.Threading.Tasks;
using Uno.Diagnostics.Eventing;
using Uno.UI.Controls;
using Windows.UI.Core;
using System.Globalization;
using Uno.Disposables;
using Uno.Extensions.Specialized;
using Windows.Foundation;
using Windows.UI.Xaml.Controls.Primitives;
using Uno.UI;
using Uno.Logging;
using Uno.UI.Extensions;
using Microsoft.Extensions.Logging;
#if XAMARIN_IOS_UNIFIED
using Foundation;
using UIKit;
using CoreGraphics;
#elif XAMARIN_IOS
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using MonoTouch.CoreGraphics;
using CGRect = System.Drawing.RectangleF;
using nfloat = System.Single;
using CGPoint = System.Drawing.PointF;
using nint = System.Int32;
using CGSize = System.Drawing.SizeF;
#endif
namespace Windows.UI.Xaml.Controls
{
[Bindable]
public partial class ListViewBaseSource : UICollectionViewSource
{
/// <summary>
/// Key used to represent a null DataTemplate in _templateCache and _templateCells dictionaries (because null is a not a valid key)
/// </summary>
private readonly static DataTemplate _nullDataTemplateKey = new DataTemplate(() => null);
private readonly static IEventProvider _trace = Tracing.Get(TraceProvider.Id);
private Dictionary<ListViewBaseInternalContainer, List<Action>> _onRecycled = new Dictionary<ListViewBaseInternalContainer, List<Action>>();
/// <summary>
/// We include one extra section to ensure Header and Footer can display even when we have no sections (ie an empty grouped source).
/// </summary>
internal const int SupplementarySections = 1;
/// <summary>
/// Visual element which stops layout requests from propagating up. Used for measuring templates.
/// </summary>
private BlockLayout BlockLayout { get; } = new BlockLayout();
public static class TraceProvider
{
public readonly static Guid Id = Guid.Parse("{EE64E62E-67BD-496A-A8B1-4A142642B3A3}");
public const int ListViewBaseSource_GetCellStart = 1;
public const int ListViewBaseSource_GetCellStop = 2;
}
#region Members
private DataTemplateSelector _currentSelector;
private Dictionary<DataTemplate, CGSize> _templateCache = new Dictionary<DataTemplate, CGSize>(DataTemplate.FrameworkTemplateEqualityComparer.Default);
private Dictionary<DataTemplate, NSString> _templateCells = new Dictionary<DataTemplate, NSString>(DataTemplate.FrameworkTemplateEqualityComparer.Default);
/// <summary>
/// The furthest item in the source which has already been materialized. Items up to this point can safely be retrieved.
/// </summary>
private NSIndexPath _lastMaterializedItem = NSIndexPath.FromRowSection(0, 0);
/// <summary>
/// Is the UICollectionView currently undergoing animated scrolling, either user-initiated or programmatic.
/// </summary>
private bool _isInAnimatedScroll;
#endregion
public ListViewBaseSource()
{
}
#region Properties
private WeakReference<NativeListViewBase> _owner;
public NativeListViewBase Owner
{
get { return _owner?.GetTarget(); }
set { _owner = new WeakReference<NativeListViewBase>(value); }
}
#endregion
public ListViewBaseSource(NativeListViewBase owner)
{
Owner = owner;
}
#region Overrides
public override nint NumberOfSections(UICollectionView collectionView)
{
var itemsSections = Owner.XamlParent.IsGrouping ?
Owner.XamlParent.NumberOfDisplayGroups :
1;
return itemsSections + SupplementarySections;
}
public override nint GetItemsCount(UICollectionView collectionView, nint section)
{
int count;
if (Owner.XamlParent.IsGrouping)
{
count = GetGroupedItemsCount(section);
}
else
{
count = GetUngroupedItemsCount(section);
}
if (this.Log().IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug))
{
this.Log().Debug($"Count requested for section {section}, returning {count}");
}
return count;
}
private int GetUngroupedItemsCount(nint section)
{
int count;
if (section == 0)
{
count = Owner.XamlParent.NumberOfItems;
}
else
{
// Extra section added to accommodate header+footer, contains no items.
count = 0;
}
return count;
}
private int GetGroupedItemsCount(nint section)
{
if ((int)section >= Owner.XamlParent.NumberOfDisplayGroups)
{
// Header+footer section which is empty
return 0;
}
return Owner.XamlParent.GetDisplayGroupCount((int)section);
}
public override void CellDisplayingEnded(UICollectionView collectionView, UICollectionViewCell cell, NSIndexPath indexPath)
{
var key = cell as ListViewBaseInternalContainer;
if (_onRecycled.TryGetValue(key, out var actions))
{
foreach (var a in actions) { a(); }
_onRecycled.Remove(key);
}
if (this.Log().IsEnabled(LogLevel.Debug))
{
this.Log().LogDebug($"CellDisplayingEnded for cell at {indexPath}");
}
}
/// <summary>
/// Queues an action to be executed when the provided viewHolder is being recycled.
/// </summary>
internal void RegisterForRecycled(ListViewBaseInternalContainer container, Action action)
{
if (!_onRecycled.TryGetValue(container, out var actions))
{
_onRecycled[container] = actions = new List<Action>();
}
actions.Add(action);
}
public override UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath)
{
using (
_trace.WriteEventActivity(
TraceProvider.ListViewBaseSource_GetCellStart,
TraceProvider.ListViewBaseSource_GetCellStop
)
)
{
// Marks this item to be materialized, so its actual measured size
// is used during the calculation of the layout.
// This is required for paged lists, so that the layout calculation
// does not eagerly get all the items of the ItemsSource.
UpdateLastMaterializedItem(indexPath);
var index = Owner?.XamlParent?.GetIndexFromIndexPath(Uno.UI.IndexPath.FromNSIndexPath(indexPath)) ?? -1;
var identifier = GetReusableCellIdentifier(indexPath);
var listView = (NativeListViewBase)collectionView;
var cell = (ListViewBaseInternalContainer)collectionView.DequeueReusableCell(identifier, indexPath);
using (cell.InterceptSetNeedsLayout())
{
var selectorItem = cell.Content as SelectorItem;
if (selectorItem == null ||
// If it's not a generated container then it must be an item that returned true for IsItemItsOwnContainerOverride (eg an
// explicitly-defined ListViewItem), and shouldn't be recycled for a different item.
!selectorItem.IsGeneratedContainer)
{
cell.Owner = Owner;
selectorItem = Owner?.XamlParent?.GetContainerForIndex(index) as SelectorItem;
cell.Content = selectorItem;
if (this.Log().IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug))
{
this.Log().Debug($"Creating new view at indexPath={indexPath}.");
}
FrameworkElement.InitializePhaseBinding(selectorItem);
// Ensure the item has a parent, since it's added to the native collection view
// which does not automatically sets the parent DependencyObject.
selectorItem.SetParentOverride(Owner?.XamlParent?.InternalItemsPanelRoot);
}
else if (this.Log().IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug))
{
this.Log().Debug($"Reusing view at indexPath={indexPath}, previously bound to {selectorItem.DataContext}.");
}
Owner?.XamlParent?.PrepareContainerForIndex(selectorItem, index);
// Normally this happens when the SelectorItem.Content is set, but there's an edge case where after a refresh, a
// container can be dequeued which happens to have had exactly the same DataContext as the new item.
cell.ClearMeasuredSize();
}
Owner?.XamlParent?.TryLoadMoreItems(index);
return cell;
}
}
/// <summary>
/// Update record of the furthest item materialized.
/// </summary>
/// <param name="newItem">Item currently being materialized.</param>
/// <returns>True if the value has changed and the layout would change.</returns>
internal bool UpdateLastMaterializedItem(NSIndexPath newItem)
{
if (newItem.Compare(_lastMaterializedItem) > 0)
{
_lastMaterializedItem = newItem;
return Owner.ItemTemplateSelector != null; ;
}
else
{
return false;
}
}
/// <summary>
/// Is item in the range of already-materialized items?
/// </summary>
private bool IsMaterialized(NSIndexPath itemPath) => itemPath.Compare(_lastMaterializedItem) <= 0;
// Consider group header to be materialized if first item in group is materialized
private bool IsMaterialized(int section) => section <= _lastMaterializedItem.Section;
public override void WillDisplayCell(UICollectionView collectionView, UICollectionViewCell cell, NSIndexPath indexPath)
{
var index = Owner?.XamlParent?.GetIndexFromIndexPath(Uno.UI.IndexPath.FromNSIndexPath(indexPath)) ?? -1;
var container = cell as ListViewBaseInternalContainer;
var selectorItem = container?.Content as SelectorItem;
//Update IsSelected and multi-select state immediately before display, in case either was modified after cell was prefetched but before it became visible
if (selectorItem != null)
{
selectorItem.IsSelected = Owner?.XamlParent?.IsSelected(index) ?? false;
Owner?.XamlParent?.ApplyMultiSelectState(selectorItem);
}
FrameworkElement.RegisterPhaseBinding(container.Content, a => RegisterForRecycled(container, a));
if (this.Log().IsEnabled(LogLevel.Debug))
{
this.Log().LogDebug($"WillDisplayCell for cell at {indexPath}");
}
}
public override UICollectionReusableView GetViewForSupplementaryElement(
UICollectionView collectionView,
NSString elementKind,
NSIndexPath indexPath)
{
var listView = (NativeListViewBase)collectionView;
if (elementKind == NativeListViewBase.ListViewHeaderElementKind)
{
return GetBindableSupplementaryView(
collectionView: collectionView,
elementKind: NativeListViewBase.ListViewHeaderElementKindNS,
indexPath: indexPath,
reuseIdentifier: NativeListViewBase.ListViewHeaderReuseIdentifierNS,
context: listView.Header,
template: listView.HeaderTemplate,
style: null
);
}
else if (elementKind == NativeListViewBase.ListViewFooterElementKind)
{
return GetBindableSupplementaryView(
collectionView: collectionView,
elementKind: NativeListViewBase.ListViewFooterElementKindNS,
indexPath: indexPath,
reuseIdentifier: NativeListViewBase.ListViewFooterReuseIdentifierNS,
context: listView.Footer,
template: listView.FooterTemplate,
style: null
);
}
else if (elementKind == NativeListViewBase.ListViewSectionHeaderElementKind)
{
// Ensure correct template can be retrieved
UpdateLastMaterializedItem(indexPath);
return GetBindableSupplementaryView(
collectionView: collectionView,
elementKind: NativeListViewBase.ListViewSectionHeaderElementKindNS,
indexPath: indexPath,
reuseIdentifier: NativeListViewBase.ListViewSectionHeaderReuseIdentifierNS,
//ICollectionViewGroup.Group is used as context for sectionHeader
context: listView.XamlParent.GetGroupAtDisplaySection(indexPath.Section).Group,
template: GetTemplateForGroupHeader(indexPath.Section),
style: listView.GroupStyle?.HeaderContainerStyle
);
}
else
{
throw new NotSupportedException("Unsupported element kind: {0}".InvariantCultureFormat(elementKind));
}
}
private UICollectionReusableView GetBindableSupplementaryView(
UICollectionView collectionView,
NSString elementKind,
NSIndexPath indexPath,
NSString reuseIdentifier,
object context,
DataTemplate template,
Style style)
{
var supplementaryView = (ListViewBaseInternalContainer)collectionView.DequeueReusableSupplementaryView(
elementKind,
reuseIdentifier,
indexPath);
using (supplementaryView.InterceptSetNeedsLayout())
{
if (supplementaryView.Content == null)
{
supplementaryView.Owner = Owner;
var content = CreateContainerForElementKind(elementKind);
content.HorizontalContentAlignment = HorizontalAlignment.Stretch;
content.VerticalContentAlignment = VerticalAlignment.Stretch;
supplementaryView.Content = content
.Binding("Content", "");
}
supplementaryView.Content.ContentTemplate = template;
supplementaryView.Content.DataContext = context;
if (style != null)
{
supplementaryView.Content.Style = style;
}
}
return supplementaryView;
}
internal void SetIsAnimatedScrolling() => _isInAnimatedScroll = true;
#if !MACCATALYST // Fix on .NET 6 Preview 6 https://github.com/unoplatform/uno/issues/5873
public override void Scrolled(UIScrollView scrollView)
{
InvokeOnScroll();
}
// Called when user starts dragging
public override void DraggingStarted(UIScrollView scrollView)
{
_isInAnimatedScroll = true;
}
// Called when user stops dragging (lifts finger)
public override void DraggingEnded(UIScrollView scrollView, bool willDecelerate)
{
if (!willDecelerate)
{
//No fling, send final scroll event
OnAnimatedScrollEnded();
}
}
// Called when a user-initiated fling comes to a stop
public override void DecelerationEnded(UIScrollView scrollView)
{
OnAnimatedScrollEnded();
}
// Called at the end of a programmatic animated scroll
public override void ScrollAnimationEnded(UIScrollView scrollView)
{
OnAnimatedScrollEnded();
}
public override void DidZoom(UIScrollView scrollView)
{
// Note: untested, more may be needed to support zooming. On ScrollContentPresenter we set ViewForZoomingInScrollView (not
// obvious what it would be in the case of a list).
Owner.XamlParent?.ScrollViewer?.OnZoomInternal((float)Owner.ZoomScale);
}
#endif
private void OnAnimatedScrollEnded()
{
_isInAnimatedScroll = false;
InvokeOnScroll();
}
private void InvokeOnScroll()
{
var shouldReportNegativeOffsets = Owner.XamlParent?.ScrollViewer?.ShouldReportNegativeOffsets ?? false;
// iOS can return, eg, negative values for offset, whereas Windows never will, even for 'elastic' scrolling
var clampedOffset = shouldReportNegativeOffsets ?
Owner.ContentOffset :
Owner.ContentOffset.Clamp(CGPoint.Empty, Owner.UpperScrollLimit);
Owner.XamlParent?.ScrollViewer?.OnScrollInternal(clampedOffset.X, clampedOffset.Y, isIntermediate: _isInAnimatedScroll);
}
#if !MACCATALYST // Fix on .NET 6 Preview 6 https://github.com/unoplatform/uno/issues/5873
public override void WillEndDragging(UIScrollView scrollView, CGPoint velocity, ref CGPoint targetContentOffset)
{
// If snap points are enabled, override the target offset with the calculated snap point.
var snapTo = Owner?.NativeLayout?.GetSnapTo(velocity, targetContentOffset);
if (snapTo.HasValue)
{
targetContentOffset = snapTo.Value;
}
}
#endif
#endregion
internal void ReloadData()
{
_lastMaterializedItem = NSIndexPath.FromRowSection(0, 0);
}
/// <summary>
/// Get item container corresponding to an element kind (header, footer, list item, etc)
/// </summary>
private ContentControl CreateContainerForElementKind(NSString elementKind)
{
if (elementKind == NativeListViewBase.ListViewSectionHeaderElementKindNS)
{
return Owner?.XamlParent?.GetGroupHeaderContainer(null);
}
else if (elementKind == NativeListViewBase.ListViewItemElementKindNS)
{
return Owner?.XamlParent?.GetContainerForIndex(-1) as ContentControl;
}
else
{
//Used for header and footer
return ContentControl.CreateItemContainer();
}
}
internal CGSize GetHeaderSize(Size availableSize)
{
return Owner.HeaderTemplate != null ? GetTemplateSize(Owner.HeaderTemplate, NativeListViewBase.ListViewHeaderElementKindNS, availableSize) : CGSize.Empty;
}
internal CGSize GetFooterSize(Size availableSize)
{
return Owner.FooterTemplate != null ? GetTemplateSize(Owner.FooterTemplate, NativeListViewBase.ListViewFooterElementKindNS, availableSize) : CGSize.Empty;
}
internal CGSize GetSectionHeaderSize(int section, Size availableSize)
{
var template = GetTemplateForGroupHeader(section);
return template.SelectOrDefault(ht => GetTemplateSize(ht, NativeListViewBase.ListViewSectionHeaderElementKindNS, availableSize), CGSize.Empty);
}
internal CGSize GetItemSize(UICollectionView collectionView, NSIndexPath indexPath, Size availableSize)
{
DataTemplate itemTemplate = GetTemplateForItem(indexPath);
if (_currentSelector != Owner.ItemTemplateSelector)
{
// If the templateSelector has changed, clear the cache
_currentSelector = Owner.ItemTemplateSelector;
_templateCache.Clear();
_templateCells.Clear();
}
var size = GetTemplateSize(itemTemplate, NativeListViewBase.ListViewItemElementKindNS, availableSize);
if (size == CGSize.Empty)
{
// The size of the template is usually empty for items that have not been displayed yet when using ItemTemplateSelector.
// The reason why we can't measure the template is because we do not resolve it,
// as it would require enumerating through all items of a possibly virtualized ItemsSource.
// To ensure a first display (after which they will be properly measured), we need them to have a non-empty size.
size = new CGSize(44, 44); // 44 is the default MinHeight/MinWidth of ListViewItem/GridViewItem on UWP.
}
return size;
}
private DataTemplate GetTemplateForItem(NSIndexPath indexPath)
{
if (IsMaterialized(indexPath))
{
return Owner?.XamlParent?.ResolveItemTemplate(Owner.XamlParent.GetDisplayItemFromIndexPath(indexPath.ToIndexPath()));
}
else
{
// Ignore ItemTemplateSelector since we do not know what the item is
return Owner?.XamlParent?.ItemTemplate;
}
}
private DataTemplate GetTemplateForGroupHeader(int section)
{
var groupStyle = Owner.GroupStyle;
if (IsMaterialized(section))
{
return DataTemplateHelper.ResolveTemplate(
groupStyle?.HeaderTemplate,
groupStyle?.HeaderTemplateSelector,
Owner.XamlParent.GetGroupAtDisplaySection(section).Group,
Owner);
}
else
{
return groupStyle?.HeaderTemplate;
}
}
/// <summary>
/// Gets the actual item template size, using a non-databound materialized
/// view of the template.
/// </summary>
/// <param name="dataTemplate">A data template</param>
/// <returns>The actual size of the template</returns>
private CGSize GetTemplateSize(DataTemplate dataTemplate, NSString elementKind, Size availableSize)
{
CGSize size;
// Cache the sizes to avoid creating new templates every time.
if (!_templateCache.TryGetValue(dataTemplate ?? _nullDataTemplateKey, out size))
{
var container = CreateContainerForElementKind(elementKind);
// Force a null DataContext so the parent's value does not flow
// through when temporarily adding the container to Owner.XamlParent
container.SetValue(FrameworkElement.DataContextProperty, null);
Style style = null;
if (elementKind == NativeListViewBase.ListViewItemElementKind)
{
style = Owner.ItemContainerStyle;
}
else if (elementKind == NativeListViewBase.ListViewSectionHeaderElementKind)
{
style = Owner.GroupStyle?.HeaderContainerStyle;
}
if (style != null)
{
container.Style = style;
}
if (!container.IsContainerFromTemplateRoot)
{
container.ContentTemplate = dataTemplate;
}
try
{
// Attach templated container to visual tree while measuring. This works around the bug that default Style is not
// applied until view is loaded.
Owner.XamlParent.AddSubview(BlockLayout);
BlockLayout.AddSubview(container);
// Measure with PositiveInfinity rather than MaxValue, since some views handle this better.
size = Owner.NativeLayout.Layouter.MeasureChild(container, availableSize);
if ((size.Height > nfloat.MaxValue / 2 || size.Width > nfloat.MaxValue / 2) &&
this.Log().IsEnabled(LogLevel.Warning)
)
{
this.Log().LogWarning($"Infinite item size reported, this can crash {nameof(UICollectionView)}.");
}
}
finally
{
Owner.XamlParent.RemoveChild(BlockLayout);
BlockLayout.RemoveChild(container);
// Reset the DataContext for reuse.
container.ClearValue(FrameworkElement.DataContextProperty);
}
_templateCache[dataTemplate ?? _nullDataTemplateKey] = size;
}
return size;
}
/// <summary>
/// Determine the identifier to use for the dequeuing.
/// This avoid for already materialized items with a specific template
/// to switch to a different template, and have to re-create the content
/// template.
/// </summary>
private NSString GetReusableCellIdentifier(NSIndexPath indexPath)
{
NSString identifier;
var template = GetTemplateForItem(indexPath);
if (!_templateCells.TryGetValue(template ?? _nullDataTemplateKey, out identifier))
{
identifier = new NSString(_templateCells.Count.ToString(CultureInfo.InvariantCulture));
_templateCells[template ?? _nullDataTemplateKey] = identifier;
Owner.RegisterClassForCell(typeof(ListViewBaseInternalContainer), identifier);
}
return identifier;
}
}
/// <summary>
/// A hidden root item that allows the reuse of ContentControl features.
/// </summary>
internal class ListViewBaseInternalContainer : UICollectionViewCell
{
/// <summary>
/// Native constructor, do not use explicitly.
/// </summary>
/// <remarks>
/// Used by the Xamarin Runtime to materialize native
/// objects that may have been collected in the managed world.
/// </remarks>
public ListViewBaseInternalContainer(IntPtr handle) : base(handle) { }
public ListViewBaseInternalContainer()
{
}
private CGSize _lastUsedSize;
private CGSize? _measuredContentSize;
private readonly SerialDisposable _contentChangedDisposable = new SerialDisposable();
private bool _needsLayout = true;
private bool _interceptSetNeedsLayout = false;
private WeakReference<NativeListViewBase> _ownerRef;
public NativeListViewBase Owner
{
get { return _ownerRef?.GetTarget(); }
set
{
if (value != _ownerRef?.GetTarget())
{
_ownerRef = new WeakReference<NativeListViewBase>(value);
}
}
}
private Orientation ScrollOrientation => Owner.NativeLayout.ScrollOrientation;
private bool SupportsDynamicItemSizes => Owner.NativeLayout.SupportsDynamicItemSizes;
private ILayouter Layouter => Owner.NativeLayout.Layouter;
protected override void Dispose(bool disposing)
{
if (!disposing)
{
GC.ReRegisterForFinalize(this);
CoreDispatcher.Main.RunIdleAsync(_ => Dispose());
}
else
{
// We need to explicitly remove the content before being disposed
// otherwise, the children will try to reference ContentView which
// will have been disposed.
foreach (var v in ContentView.Subviews)
{
v.RemoveFromSuperview();
}
base.Dispose(disposing);
}
}
public ContentControl Content
{
get
{
return /* Cache the content ?*/ContentView?.Subviews.FirstOrDefault() as ContentControl;
}
set
{
using (InterceptSetNeedsLayout())
{
if (ContentView.Subviews.Any())
{
ContentView.Subviews[0].RemoveFromSuperview();
}
value.Frame = ContentView.Bounds;
value.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight;
ContentView.AddSubview(value);
ClearMeasuredSize();
_contentChangedDisposable.Disposable = value?.RegisterDisposablePropertyChangedCallback(ContentControl.ContentProperty, (_, __) => _measuredContentSize = null);
}
}
}
public override CGRect Frame
{
get => base.Frame;
set
{
base.Frame = value;
UpdateContentViewFrame();
}
}
public override CGRect Bounds
{
get => base.Bounds;
set
{
if (_measuredContentSize.HasValue)
{
// At some points, eg during a collection change, iOS seems to apply an outdated size even after we've updated the
// LayoutAttributes. Keep the good size.
SetExtent(ref value, _measuredContentSize.Value);
}
base.Bounds = value;
UpdateContentViewFrame();
}
}
/// <summary>
/// Set the ContentView's size to match the InternalContainer, this is necessary for touches to buttons inside the template to
/// propagate properly.
/// </summary>
private void UpdateContentViewFrame()
{
if (ContentView != null)
{
ContentView.Frame = Bounds;
}
}
/// <summary>
/// Clear the cell's measured size, this allows the static template size to be updated with the correct databound size.
/// </summary>
internal void ClearMeasuredSize() => _measuredContentSize = null;
public override UICollectionViewLayoutAttributes PreferredLayoutAttributesFittingAttributes(UICollectionViewLayoutAttributes layoutAttributes)
{
if (!(((object)layoutAttributes) is UICollectionViewLayoutAttributes))
{
// This case happens for a yet unknown GC issue, where the layoutAttribute instance passed the current
// method maps to another object. The repro steps are not clear, and it may be related to ListView/GridView
// data reload.
this.Log().Error("ApplyLayoutAttributes has been called with an invalid instance. See bug #XXX for more details.");
return null;
}
if (Content == null)
{
this.Log().Error("Empty ListViewBaseInternalContainer content.");
return null;
}
try
{
var size = layoutAttributes.Frame.Size;
if (_measuredContentSize == null || size != _lastUsedSize)
{
_lastUsedSize = size;
var availableSize = AdjustAvailableSize(layoutAttributes.Frame.Size.ToFoundationSize());
if (Window != null || Owner.XamlParent.Window == null)
{
using (InterceptSetNeedsLayout())
{
_measuredContentSize = Layouter.MeasureChild(Content, availableSize);
}
}
else
{
try
{
//Attach temporarily, because some Uno control (eg ItemsControl) are only measured correctly after MovedToWindow has been called
InterceptSetNeedsLayout();
Owner.XamlParent.AddSubview(this);
_measuredContentSize = Layouter.MeasureChild(Content, availableSize);
}
finally
{
Owner.XamlParent.RemoveChild(this);
AllowSetNeedsLayout();
}
}
if (SupportsDynamicItemSizes ||
layoutAttributes.RepresentedElementKind == NativeListViewBase.ListViewSectionHeaderElementKind ||
layoutAttributes.RepresentedElementKind == NativeListViewBase.ListViewHeaderElementKind ||
layoutAttributes.RepresentedElementKind == NativeListViewBase.ListViewFooterElementKind
)
{
//Fetch layout for this item from collection view, since it may have been updated by an earlier item
var cachedAttributes = layoutAttributes.RepresentedElementKind == null ?
Owner.NativeLayout.LayoutAttributesForItem(layoutAttributes.IndexPath) :
Owner.NativeLayout.LayoutAttributesForSupplementaryView((NSString)layoutAttributes.RepresentedElementKind, layoutAttributes.IndexPath);
// cachedAttributes may be null if we have modified the collection with DeleteItems
var frame = cachedAttributes?.Frame ?? layoutAttributes.Frame;
SetExtent(ref frame, _measuredContentSize.Value);
var sizesAreDifferent = frame.Size != layoutAttributes.Frame.Size;
if (sizesAreDifferent)
{
if (this.Log().IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug))
{
this.Log().Debug($"Adjusting layout attributes for item at {layoutAttributes.IndexPath}({layoutAttributes.RepresentedElementKind}), Content={Content?.Content}. Previous frame={layoutAttributes.Frame}, new frame={frame}.");
}
Owner.NativeLayout.HasDynamicElementSizes = true;
this.Frame = frame;
SetNeedsLayout();
//If we don't do a lightweight refresh here, in some circumstances (grouping enabled?) the UICollectionView seems
//to use stale layoutAttributes for deciding if items should be visible, leading to them popping out of view mid-viewport.
Owner?.NativeLayout?.RefreshLayout();
}
layoutAttributes.Frame = frame;
if (sizesAreDifferent)
{
Owner.NativeLayout.UpdateLayoutAttributesForElement(layoutAttributes);
}
if (layoutAttributes.RepresentedElementKind != null)
{
//The UICollectionView seems to call PreferredLayoutAttributesFittingAttributes for supplementary views last. Therefore
//we need to relayout all visible items to make sure item views are offset to account for headers and group headers.
Owner.NativeLayout.RefreshLayout();
}
}
}
}
catch (Exception e)
{
this.Log().Error($"Adjusting layout attributes for {layoutAttributes?.IndexPath?.ToString() ?? "[null]"} failed", e);
}
if (this.Log().IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug))
{
this.Log().Debug($"Returning layout attributes for item at {layoutAttributes.IndexPath}({layoutAttributes.RepresentedElementKind}), Content={Content?.Content}, with frame {layoutAttributes.Frame}");
}
if (layoutAttributes.Frame != this.Frame)
{
if (this.Log().IsEnabled(LogLevel.Debug))
{
this.Log().Debug($"Overwriting Frame: Item={layoutAttributes.IndexPath}: layoutAttributes.Frame={layoutAttributes.Frame}, this.Frame={this.Frame}");
}
// For some reason the item's Frame can be left stuck in the wrong value in certain cases where it is changed repeatedly in
// response to sequential collection changes.
Frame = layoutAttributes.Frame;
}
return layoutAttributes;
}
public void SetSuperviewNeedsLayout()
{
if (!_needsLayout && !_interceptSetNeedsLayout)
{
_needsLayout = true;
Owner?.NativeLayout?.RefreshLayout();
ClearMeasuredSize();
SetNeedsLayout();
}
}
public override void LayoutSubviews()
{
_needsLayout = false;
var size = Bounds.Size;
if (Content != null)
{
Layouter.ArrangeChild(Content, new Rect(0, 0, (float)size.Width, (float)size.Height));
}
}
/// <summary>
/// Instruct the <see cref="ListViewBaseInternalContainer"/> not to propagate layout requests to its parent list, eg because the
/// item is in the process of being prepared by the list.
/// </summary>
internal IDisposable InterceptSetNeedsLayout()
{
_interceptSetNeedsLayout = true;
return Disposable.Create(AllowSetNeedsLayout);
}
/// <summary>
/// Tell the container to resume propagating layout requests.
/// </summary>
private void AllowSetNeedsLayout() => _interceptSetNeedsLayout = false;
/// <summary>
/// Set available size to be infinite in the scroll direction.
/// </summary>
private Size AdjustAvailableSize(Size availableSize)
{
if (ScrollOrientation == Orientation.Vertical)
{
availableSize.Height = double.PositiveInfinity;
}
else
{
availableSize.Width = double.PositiveInfinity;
}
return availableSize;
}
/// <summary>
/// Set the frame's extent in the direction of scrolling.
/// </summary>
private void SetExtent(ref CGRect frame, CGSize targetSize)
{
if (ScrollOrientation == Orientation.Vertical)
{
frame.Height = targetSize.Height;
}
else
{
frame.Width = targetSize.Width;
}
}
}
internal partial class BlockLayout : Border
{
public override void SetNeedsLayout()
{
//Block
}
public override void SetSuperviewNeedsLayout()
{
//Block
}
}
}