-
Notifications
You must be signed in to change notification settings - Fork 768
/
Copy pathVirtualizingPanelLayout.managed.cs
1404 lines (1175 loc) · 44.3 KB
/
VirtualizingPanelLayout.managed.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
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#if !IS_UNIT_TESTS
#nullable enable
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using DirectUI;
using Microsoft.UI.Xaml.Controls.Primitives;
using Microsoft.UI.Xaml.Documents;
using Windows.Foundation;
using Uno.Extensions;
using Uno.UI;
using Uno.UI.Extensions;
using Uno.UI.Xaml.Controls;
using Uno.Foundation.Logging;
#if __MACOS__
using AppKit;
#elif __IOS__
using UIKit;
#endif
#if __IOS__ || __ANDROID__
using _Panel = Uno.UI.Controls.ManagedItemsStackPanel;
#else
using _Panel = Microsoft.UI.Xaml.Controls.Panel;
#endif
using static System.Math;
using static Microsoft.UI.Xaml.Controls.Primitives.GeneratorDirection;
using IndexPath = Uno.UI.IndexPath;
namespace Microsoft.UI.Xaml.Controls
{
#if __IOS__ || __ANDROID__
internal abstract partial class ManagedVirtualizingPanelLayout : DependencyObject
#else
public abstract partial class VirtualizingPanelLayout : DependencyObject
#endif
{
private _Panel? _ownerPanel;
private _Panel OwnerPanel
{
get => _ownerPanel ?? throw new InvalidOperationException($"{nameof(Initialize)}() was not called properly.");
set => _ownerPanel = value;
}
private VirtualizingPanelGenerator? _generator;
private protected VirtualizingPanelGenerator Generator
{
get => _generator ?? throw new InvalidOperationException($"{nameof(Initialize)}() was not called properly.");
private set => _generator = value;
}
private ScrollViewer? ScrollViewer { get; set; }
internal ItemsControl? ItemsControl { get; set; }
internal ItemsControl? XamlParent => ItemsControl;
/// <summary>
/// Ordered record of all currently-materialized lines.
/// </summary>
private readonly Deque<Line> _materializedLines = new Deque<Line>();
private Size _availableSize;
private Size _lastMeasuredSize;
private double _lastScrollOffset;
private bool _clearingLines;
/// <summary>
/// The current average line height based on materialized lines. Used to estimate scroll extent of unmaterialized items.
/// </summary>
private double _averageLineHeight;
/// <summary>
/// The previous item to the old first visible item, used when a lightweight layout rebuild is called.
/// </summary>
private Uno.UI.IndexPath? _dynamicSeedIndex;
/// <summary>
/// Start position of the old first group, used when a lightweight layout rebuild is called.
/// </summary>
private double? _dynamicSeedStart;
/// <summary>
/// Pending collection changes to be processed when the list is re-measured.
/// </summary>
private readonly Queue<CollectionChangedOperation> _pendingCollectionChanges = new Queue<CollectionChangedOperation>();
/// <summary>
/// Pending <see cref="ScrollIntoView(object, ScrollIntoViewAlignment)"/> request to be handled when the ScrollViewer's extent is updated.
/// </summary>
/// <remarks>
/// At MeasureOverride/ArrangeOverride the SV isn't updated yet. If we attempt handle it in there,
/// the SV will clamp the scrolling to its current content size, potentially leaving the scroll target out-of-sight should it be the last item.
/// </remarks>
private (int Index, ScrollIntoViewAlignment Alignment)? _pendingScrollIntoViewRequest;
/// <summary>
/// Pending scroll adjustment, if an item has been added/removed backward of the current visible viewport by a collection change.
/// </summary>
private double? _scrollAdjustmentForCollectionChanges;
private bool IsHorizontal => ScrollOrientation == Orientation.Horizontal;
private double AvailableBreadth => IsHorizontal
? _availableSize.Height
: _availableSize.Width;
/// <summary>
/// The current offset from the original scroll position.
/// </summary>
private double ScrollOffset => (IsHorizontal
? ScrollViewer?.HorizontalOffset
: ScrollViewer?.VerticalOffset)
?? 0;
/// <summary>
/// The size of all the scrollable content, whether visible or not.
/// </summary>
private double Extent => (IsHorizontal
? ScrollViewer?.ExtentWidth
: ScrollViewer?.ExtentHeight)
?? double.NaN;
/// <summary>
/// The size of the scroll viewport.
/// </summary>
private Size ViewportSize { get; set; }
/// <summary>
/// The extent (parallel to scroll direction) of the scroll viewport.
/// </summary>
private double ViewportExtent
{
get
{
if (ScrollViewer is null)
{
return double.MaxValue / 1000;
}
return IsHorizontal
// note: the ViewportSize from above does not reflect the actual size of viewport.
// The measure/layout value is different than the actual value we need for calculation.
// However, we need the ViewportSize as a fallback, since the former is not yet assigned during 1st layout phase.
? NotZero(ScrollViewer.ViewportWidth, ViewportSize.Width)
: NotZero(ScrollViewer.ViewportHeight, ViewportSize.Height);
double NotZero(double value, double fallback) => value != 0 ? value : fallback;
}
}
/// <summary>
/// The start of the visible viewport, relative to the start of the panel.
/// </summary>
private double ViewportStart => ScrollOffset;
/// <summary>
/// The end of the visible viewport, relative to the end of the panel.
/// </summary>
private double ViewportEnd => ScrollOffset + ViewportExtent;
internal const double ExtendedViewportScaling = 0.5;
/// <summary>
/// The additional length in pixels for which to create buffered views.
/// </summary>
private double ViewportExtension => CacheLength * ViewportExtent * ExtendedViewportScaling;
/// <summary>
/// The start of the 'extended viewport,' the area of the visible viewport plus the buffer area defined by <see cref="CacheLength"/>.
/// </summary>
private double ExtendedViewportStart
{
get
{
var unclampedStart = ViewportStart - ViewportExtension;
return Math.Max(unclampedStart, 0);
}
}
/// <summary>
/// The end of the 'extended viewport,' the area of the visible viewport plus the buffer area defined by <see cref="CacheLength"/>.
/// </summary>
private double ExtendedViewportEnd
{
get
{
return ViewportEnd + ViewportExtension;
}
}
private bool ShouldMeasuredBreadthStretch => ShouldBreadthStretch && GetBreadth(_availableSize) < double.MaxValue / 2;
// TODO: this should be adjusted when header, group headers etc are implemented
private double PositionOfFirstElement => 0;
internal void Initialize(_Panel owner)
{
OwnerPanel = owner ?? throw new ArgumentNullException(nameof(owner));
// It's necessary to subscribe to Loading not Loaded to fire this before
// the first Measure during/after loading. If during the first measure
// ScrollViewer and ItemsControl are not set, this will cause the
// DesiredSize to be zero and this causes cascading problems specifically
// with ListView. cf. https://github.com/unoplatform/kahua-private/issues/257
OwnerPanel.Loading += OnLoading;
OwnerPanel.Unloaded += OnUnloaded;
Generator = new VirtualizingPanelGenerator(this);
}
private void OnLoading(FrameworkElement frameworkElement, object args)
{
foreach (var parent in OwnerPanel.GetVisualAncestry())
{
if (parent is ScrollViewer scrollViewer && ScrollViewer == null)
{
ScrollViewer = scrollViewer;
ScrollViewer.ViewChanged += OnScrollChanged;
ScrollViewer.SizeChanged += OnScrollViewerSizeChanged;
ScrollViewer.ExtentSizeChanged += OnScrollViewerExtentSizeChanged;
}
else if (parent is ItemsControl itemsControl)
{
ItemsControl = itemsControl;
OwnerPanel.InvalidateMeasure();
break;
}
}
var hasPopupPanelParent = OwnerPanel.FindFirstParent<PopupPanel>() != null;
var hasListViewParent = OwnerPanel.FindFirstParent<ListViewBase>() != null;
IsInsidePopup = hasPopupPanelParent && !hasListViewParent;
if (this.Log().IsEnabled(LogLevel.Debug))
{
this.Log().LogDebug($"Calling {GetMethodTag()} hasPopupPanelParent={hasPopupPanelParent} hasListViewParent={hasListViewParent}");
}
if (IsInsidePopup)
{
// The items-control may not exist in the direct visual-tree,
// if it is defined within a popup/flyout, as in the case of ComboBox.
ItemsControl = OwnerPanel
.FindFirstParent<PopupPanel>()?.Popup
?.FindFirstParent<ItemsControl>();
// If measure has already happened when ItemsControl was null, it should be invalidated.
OwnerPanel.InvalidateMeasure();
}
}
private void OnUnloaded(object sender, RoutedEventArgs e)
{
if (ScrollViewer != null)
{
ScrollViewer.ViewChanged -= OnScrollChanged;
ScrollViewer.SizeChanged -= OnScrollViewerSizeChanged;
ScrollViewer.ExtentSizeChanged -= OnScrollViewerExtentSizeChanged;
}
ScrollViewer = null;
ItemsControl = null;
}
private void OnScrollChanged(object? sender, ScrollViewerViewChangedEventArgs e)
{
if (this.Log().IsEnabled(LogLevel.Debug))
{
this.Log().LogDebug($"Calling {GetMethodTag()} _lastScrollOffset={_lastScrollOffset} ScrollOffset={ScrollOffset}");
}
var delta = ScrollOffset - _lastScrollOffset;
var sign = Sign(delta);
var unappliedDelta = Abs(delta);
var fillDirection = sign > 0 ? Forward : Backward;
var isLargeScroll = Abs(delta) > ViewportExtent;
if (isLargeScroll)
{
// In this case, a majority of the materialized items are
// removed, let's clear everything and materialize from the
// new position.
if (this.Log().IsEnabled(LogLevel.Debug))
{
this.Log().LogDebug($"Large scroll Abs(delta):{Abs(delta)} AvailableBreadth:{AvailableBreadth}");
}
// Force the layout update below
unappliedDelta = 1;
// We know that the scroll is outside the available
// breath, so all lines can be recycled
ClearLines(clearContainer: false);
// Set the seed start to use the approximate position of
// the line based on the average line height.
var index = (int)(ScrollOffset / _averageLineHeight);
SetDynamicSeed(Uno.UI.IndexPath.FromRowSection(index - 1, 0), index * _averageLineHeight);
}
while (unappliedDelta > 0)
{
var scrollIncrement =
_scrollAdjustmentForCollectionChanges.HasValue ?
// If we're adjusting for collection changes, apply scroll in 'one big hit' because we should exactly reuse scrapped items this way (since items in visible viewport should not have changed)
Abs(_scrollAdjustmentForCollectionChanges.Value) :
// Apply scroll in bite-sized increments. This is crucial for good performance, since the delta may be in the 100s or 1000s of pixels, and we want to recycle unseen views at the same rate that we dequeue newly-visible views.
GetScrollConsumptionIncrement(fillDirection);
_scrollAdjustmentForCollectionChanges = null;
if (scrollIncrement == 0)
{
break;
}
unappliedDelta -= scrollIncrement;
unappliedDelta = Max(0, unappliedDelta);
UpdateLayout(extentAdjustment: sign * -unappliedDelta, isScroll: true);
#if __WASM__ || __SKIA__
(ItemsControl as ListViewBase)?.TryLoadMoreItems(LastVisibleIndex);
#endif
}
ArrangeElements(_availableSize, ViewportSize);
UpdateCompleted();
if (isLargeScroll)
{
// Request the panel to remeasure children as we've
// reused all the lines.
OwnerPanel.InvalidateMeasure();
}
_lastScrollOffset = ScrollOffset;
}
private void OnScrollViewerSizeChanged(object sender, SizeChangedEventArgs args)
{
OwnerPanel?.InvalidateMeasure();
}
private void OnScrollViewerExtentSizeChanged(object sender, SizeChangedEventArgs args)
{
if (_pendingScrollIntoViewRequest is { } request)
{
ScrollIntoViewCore(request.Index, request.Alignment);
}
}
/// <summary>
/// Get the increment to consume scroll changes, based on the size of the disappearing view.
/// </summary>
private double GetScrollConsumptionIncrement(GeneratorDirection fillDirection)
{
var incrementView = fillDirection == Forward ?
GetFirstMaterializedLine()?.FirstView :
GetLastMaterializedLine()?.LastView;
if (incrementView == null)
{
//TODO: work properly when header/footer/group header are available, and may be larger than extended viewport
return _averageLineHeight;
}
return GetActualExtent(incrementView);
}
internal Size MeasureOverride(Size availableSize)
{
if (_clearingLines)
{
return new Size(0, 0);
}
if (ItemsControl == null)
{
if (this.Log().IsEnabled(LogLevel.Debug))
{
this.Log().LogDebug("Measured without an ItemsControl: simply return size(0,0) for now...");
}
return new Size(0, 0);
}
ViewportSize = ScrollViewer?.ViewportMeasureSize ?? default;
if (this.Log().IsEnabled(LogLevel.Debug))
{
this.Log().LogDebug($"Calling {GetMethodTag()}, availableSize={availableSize}, _availableSize={_availableSize} {GetDebugInfo()}");
}
_availableSize = availableSize;
UpdateAverageLineHeight(); // Must be called before ScrapLayout(), or there won't be items to measure
ScrapLayout();
ApplyCollectionChanges();
UpdateLayout(extentAdjustment: _scrollAdjustmentForCollectionChanges, isScroll: false);
return _lastMeasuredSize = EstimatePanelSize(isMeasure: true);
}
internal Size ArrangeOverride(Size finalSize)
{
if (ItemsControl == null)
{
if (this.Log().IsEnabled(LogLevel.Debug))
{
this.Log().LogDebug("Arranged without an ItemsControl: simply return size(0,0) for now...");
}
return new Size(0, 0);
}
ViewportSize = ScrollViewer?.ViewportArrangeSize ?? default;
if (this.Log().IsEnabled(LogLevel.Debug))
{
this.Log().LogDebug($"Calling {GetMethodTag()}, finalSize={finalSize}, {GetDebugInfo()}");
}
_availableSize = finalSize;
var adjustedVisibleWindow = ViewportSize;
ArrangeElements(finalSize, adjustedVisibleWindow);
if (_generator != null && _averageLineHeight > 0)
{
var cacheLimit = (int)(ViewportExtent / _averageLineHeight) * 2;
if (this.Log().IsEnabled(LogLevel.Debug))
{
this.Log().LogDebug($"Setting cache limit {cacheLimit}");
}
_generator.CacheLimit = cacheLimit;
}
return EstimatePanelSize(isMeasure: false);
}
private void ArrangeElements(Size finalSize, Size adjustedVisibleWindow)
{
foreach (var line in _materializedLines)
{
var indexAdjustment = -1;
foreach (var item in line.Items)
{
indexAdjustment++;
var bounds = GetBoundsForElement(item.container);
var arrangedBounds = GetElementArrangeBounds(line.FirstItemFlat + indexAdjustment, bounds, adjustedVisibleWindow, finalSize);
item.container.Arrange(arrangedBounds);
}
}
}
/// <summary>
/// Update the item container layout by removing no-longer-visible views and adding visible views.
/// </summary>
/// <param name="extentAdjustment">
/// Adjustment to apply when calculating fillable area.
/// Used when a viewport change is not yet committed into the <see cref="ScrollOffset"/>.
/// </param>
private void UpdateLayout(double? extentAdjustment, bool isScroll)
{
ResetReorderingIndex();
OwnerPanel.ShouldInterceptInvalidate = true;
UnfillLayout(extentAdjustment ?? 0);
FillLayout(extentAdjustment ?? 0);
SetDynamicSeed(null, null);
CorrectForEstimationErrors();
if (this.Log().IsEnabled(LogLevel.Debug))
{
this.Log().LogDebug($"Called {GetMethodTag()}, {GetDebugInfo()} extentAdjustment={extentAdjustment}");
}
if (!isScroll)
{
UpdateCompleted();
}
OwnerPanel.ShouldInterceptInvalidate = false;
}
/// <summary>
/// Called after an update cycle is completed.
/// </summary>
private void UpdateCompleted()
{
// If we're not stretched, then added views may change the breadth of the list, so we allow measure requests to propagate
OwnerPanel.ShouldInterceptInvalidate = ShouldMeasuredBreadthStretch;
Generator.ClearScrappedViews();
Generator.UpdateVisibilities();
OwnerPanel.ShouldInterceptInvalidate = false;
}
/// <summary>
/// Fill in extended viewport with views.
/// </summary>
/// <param name="extentAdjustment">
/// Adjustment to apply when calculating fillable area.
/// Used when a viewport change is not yet committed into the <see cref="ScrollOffset"/>.
/// </param>
private void FillLayout(double extentAdjustment)
{
// Don't fill backward if we're doing a light rebuild (since we are starting from nearest previously-visible item)
if (!_dynamicSeedStart.HasValue)
{
FillBackward();
}
FillForward();
if (_dynamicSeedStart.HasValue && GetItemsEnd() <= ExtendedViewportEnd + extentAdjustment)
{
// if the FillForward didnt fully fill the current viewport,
// we may still need to a FillBackward, otherwise we risk having a leading blank space
FillBackward();
}
// Make sure that the reorder item has been rendered
if (GetAndUpdateReorderingIndex() is { } reorderIndex && _materializedLines.None(line => line.Contains(reorderIndex)))
{
AddLine(Forward, reorderIndex);
}
void FillBackward()
{
while (
GetItemsStart() is { } start && start > ExtendedViewportStart + extentAdjustment &&
GetNextUnmaterializedItem(Backward, GetFirstMaterializedIndexPath()) is { } nextItem)
{
AddLine(Backward, nextItem);
}
}
void FillForward()
{
var seed = _dynamicSeedIndex;
while (
GetItemsEnd() is var end && (end ?? 0) < ExtendedViewportEnd + extentAdjustment &&
GetNextUnmaterializedItem(Forward, seed ?? GetLastMaterializedIndexPath()) is { } nextItem)
{
AddLine(Forward, nextItem);
seed = null;
}
}
}
/// <summary>
/// Remove views that lie entirely outside extended viewport.
/// </summary>
/// <param name="extentAdjustment">
/// Adjustment to apply when calculating fillable area.
/// Used when a viewport change is not yet committed into the <see cref="ScrollOffset"/>.
/// </param>
private void UnfillLayout(double extentAdjustment)
{
UnfillBackward();
UnfillForward();
void UnfillBackward()
{
var firstMaterializedLine = GetFirstMaterializedLine();
while (firstMaterializedLine != null && GetMeasuredEnd(firstMaterializedLine.FirstView) < ExtendedViewportStart + extentAdjustment)
{
// Dematerialize lines that are entirely outside extended viewport
RecycleLine(firstMaterializedLine, clearContainer: false);
_materializedLines.RemoveFromFront();
firstMaterializedLine = GetFirstMaterializedLine();
}
}
void UnfillForward()
{
var lastMaterializedLine = GetLastMaterializedLine();
while (lastMaterializedLine != null && GetMeasuredStart(lastMaterializedLine.FirstView) > ExtendedViewportEnd + extentAdjustment)
{
// Dematerialize lines that are entirely outside extended viewport
RecycleLine(lastMaterializedLine, clearContainer: false);
_materializedLines.RemoveFromBack();
lastMaterializedLine = GetLastMaterializedLine();
}
}
}
/// <summary>
/// Recycle all views for a given line.
/// </summary>
/// <param name="clearContainer">cleanup the container when an associated item is removed</param>
private void RecycleLine(Line line, bool clearContainer)
{
for (int i = 0; i < line.Items.Length; i++)
{
Generator.RecycleViewForItem(line.Items[i].container, line.FirstItemFlat + i, clearContainer);
}
}
/// <summary>
/// Send views in line to temporary scrap.
/// </summary>
private void ScrapLine(Line line)
{
for (int i = 0; i < line.Items.Length; i++)
{
Generator.ScrapViewForItem(line.Items[i].container, line.FirstItemFlat + i);
}
}
/// <summary>
/// Item positions relative to the start of the panel are an estimate, which may be incorrect eg if unmaterialized items were added/removed
/// or had their databound heights changed. Here we try to correct it.
/// </summary>
void CorrectForEstimationErrors()
{
if (GetFirstMaterializedLine() is { } firstLine)
{
var neededCorrection = 0d;
var start = GetMeasuredStart(firstLine.FirstView);
if (firstLine.FirstItemFlat == 0)
{
neededCorrection = -start;
}
else if (start < PositionOfFirstElement)
{
// TODO: this is crude, the better approach (and in line with Windows) would be to estimate the position of the element, and use that
neededCorrection = -start;
}
// If the needed correction is non-zero, run through all our elements and apply the correction to their bounds
if (!DoubleUtil.IsZero(neededCorrection))
{
foreach (var line in _materializedLines)
{
foreach (var item in line.Items)
{
var bounds = GetBoundsForElement(item.container);
IncrementStart(ref bounds, neededCorrection);
SetBounds(item.container, bounds);
}
}
}
}
}
/// <summary>
/// If there are pending collection changes, update values and prepare the layouter accordingly.
/// </summary>
private void ApplyCollectionChanges()
{
if (_pendingCollectionChanges.Count == 0)
{
return;
}
// Call before applying scroll, because scroll is applied synchronously on some platforms
Generator.UpdateForCollectionChanges(_pendingCollectionChanges);
if (_dynamicSeedIndex is Uno.UI.IndexPath dynamicSeedIndex)
{
var updated = CollectionChangedOperation.Offset(dynamicSeedIndex, _pendingCollectionChanges);
if (updated is Uno.UI.IndexPath updatedValue)
{
SetDynamicSeed(updated, _dynamicSeedStart);
var itemOffset = updatedValue.Row - dynamicSeedIndex.Row; // TODO: This will need to change when grouping is supported
var scrollAdjustment = itemOffset * _averageLineHeight; // TODO: not appropriate for ItemsWrapGrid
ApplyScrollAdjustment(scrollAdjustment);
}
// TODO: handle the case where seed was removed
}
_pendingCollectionChanges.Clear();
}
/// <summary>
/// Update scroll offset for changes in position from collection change operation
/// </summary>
private void ApplyScrollAdjustment(double scrollAdjustment)
{
if (scrollAdjustment == 0)
{
return;
}
SetDynamicSeed(_dynamicSeedIndex, _dynamicSeedStart + scrollAdjustment);
if ((scrollAdjustment < 0 && IsScrolledToStart()) ||
(scrollAdjustment > 0 && IsScrolledToEnd())
)
{
// Don't call ChangeView() if there's no room to scroll, because if we set _scrollAdjustmentForCollectionChanges then we expect it to be
// handled in OnScrollChanged
// TODO: Handle this better, because it leads to an unwanted jump in the position of visible elements.
return;
}
// Set adjustment before calling ChangeView(), because OnScrollChanged() will be called synchronously on some platforms
_scrollAdjustmentForCollectionChanges = scrollAdjustment;
if (ScrollOrientation == Orientation.Vertical)
{
ScrollViewer?.ChangeView(null, ScrollViewer.VerticalOffset + scrollAdjustment, null, disableAnimation: true);
}
else
{
ScrollViewer?.ChangeView(ScrollViewer.HorizontalOffset + scrollAdjustment, null, null, disableAnimation: true);
}
}
/// <summary>
/// True if the scroll position is right at the start of the list.
/// </summary>
private bool IsScrolledToStart()
{
if (ScrollViewer == null)
{
return true;
}
return ScrollOrientation == Orientation.Vertical ?
ScrollViewer.VerticalOffset <= 0 :
ScrollViewer.HorizontalOffset <= 0;
}
/// <summary>
/// True if the scroll position is all the way to the end of the list.
/// </summary>
private bool IsScrolledToEnd()
{
if (ScrollViewer == null)
{
return true;
}
return ScrollOrientation == Orientation.Vertical ?
ScrollViewer.VerticalOffset >= ScrollViewer.ScrollableHeight :
ScrollViewer.HorizontalOffset >= ScrollViewer.ScrollableWidth;
}
/// <summary>
/// Estimate the 'correct' size of the panel.
/// </summary>
/// <param name="isMeasure">True if this is called from measure, false if after arrange.</param>
private Size EstimatePanelSize(bool isMeasure)
{
var extent = EstimatePanelExtent();
var ret = ScrollOrientation == Orientation.Vertical
? new Size(
isMeasure ? CalculatePanelMeasureBreadth() : CalculatePanelArrangeBreadth(),
double.IsInfinity(_availableSize.Height) ? extent : Max(extent, _availableSize.Height)
)
: new Size(
double.IsInfinity(_availableSize.Width) ? extent : Max(extent, _availableSize.Width),
isMeasure ? CalculatePanelMeasureBreadth() : CalculatePanelArrangeBreadth()
);
if (this.Log().IsEnabled(LogLevel.Debug))
{
this.Log().LogDebug($"{GetMethodTag()} => {extent} -> {ret} {ScrollOrientation} {_availableSize.Height} {double.IsInfinity(_availableSize.Height)} ShouldBreadthStretch:{ShouldBreadthStretch} XamlParent:{XamlParent} AvailableBreadth:{AvailableBreadth}");
}
return ret;
}
/// <summary>
/// Estimate the 'correct' extent of the panel, based on number and guessed size of remaining unmaterialized items.
/// </summary>
private double EstimatePanelExtent()
{
if (this.Log().IsEnabled(LogLevel.Debug))
{
this.Log().LogDebug($"{GetMethodTag()} Begin");
}
// Estimate remaining extent based on current average line height and remaining unmaterialized items
var lastIndexPath = GetLastMaterializedIndexPath();
if (lastIndexPath == null)
{
return 0;
}
var lastItem = GetFlatItemIndex(lastIndexPath.Value);
var remainingItems = (ItemsControl?.NumberOfItems - lastItem - 1) ?? 0;
UpdateAverageLineHeight();
int itemsPerLine = GetItemsPerLine();
var remainingLines = remainingItems / itemsPerLine + remainingItems % itemsPerLine;
double estimatedExtent = GetContentEnd() + remainingLines * _averageLineHeight;
if (this.Log().IsEnabled(LogLevel.Debug))
{
this.Log().LogDebug($"{GetMethodTag()}=>{estimatedExtent}, GetContentEnd()={GetContentEnd()}, remainingLines={remainingLines}, averageLineHeight={_averageLineHeight}");
}
return estimatedExtent;
}
private void UpdateAverageLineHeight() =>
_averageLineHeight = _materializedLines.Count > 0
? _materializedLines.Select(l => GetMeasuredExtent(l.FirstView)).Average()
: 0;
private double CalculatePanelMeasureBreadth() =>
#if __WASM__
GetBreadth(XamlParent?.ScrollViewer.ScrollBarSize ?? default) +
#endif
_materializedLines.Select(l => GetDesiredBreadth(l.FirstView)).MaxOrDefault();
private double CalculatePanelArrangeBreadth() => ShouldMeasuredBreadthStretch
? AvailableBreadth
: _materializedLines.Select(l => GetActualBreadth(l.FirstView)).MaxOrDefault();
internal void AddItems(int firstItem, int count, int section)
{
_pendingCollectionChanges.Enqueue(new CollectionChangedOperation(
startingIndex: Uno.UI.IndexPath.FromRowSection(firstItem, section),
range: count,
action: NotifyCollectionChangedAction.Add,
elementType: CollectionChangedOperation.Element.Item
));
LightRefresh();
}
internal void RemoveItems(int firstItem, int count, int section)
{
_pendingCollectionChanges.Enqueue(new CollectionChangedOperation(
startingIndex: Uno.UI.IndexPath.FromRowSection(firstItem, section),
range: count,
action: NotifyCollectionChangedAction.Remove,
elementType: CollectionChangedOperation.Element.Item
));
LightRefresh();
}
/// <summary>
/// Update the display of the panel without clearing caches.
/// </summary>
private void LightRefresh()
=> OwnerPanel?.InvalidateMeasure();
internal void Refresh()
{
if (this.Log().IsEnabled(LogLevel.Debug))
{
this.Log().LogDebug($"{GetMethodTag()}");
}
ClearLines(clearContainer: true);
UpdateCompleted();
Generator.ClearIdCache();
_pendingCollectionChanges.Clear();
OwnerPanel?.InvalidateMeasure();
}
private void ClearLines(bool clearContainer)
{
if (this.Log().IsEnabled(LogLevel.Debug))
{
this.Log().LogDebug($"{GetMethodTag()}");
}
_clearingLines = true;
try
{
// Recycling a line can lead to elements removal from the visual tree.
// To prevent modification while looping, we take a copy of _materializedLines
// and clear the original before starting the loop. This ensures that if a user forces
// a layout during this process (e.g., in Unloaded), we can update _materializedLines
// in MeasureOverride without issues. Even so, this causes some weird behaviour with
// pointer interaction, so we also disable measuring until ClearLines is done.
var lines = _materializedLines.ToArray();
_materializedLines.Clear();
foreach (var line in lines)
{
RecycleLine(line, clearContainer);
}
}
finally
{
_clearingLines = false;
}
}
/// <summary>
/// Sends all views to temporary scrap, in preparation for a lightweight layout rebuild.
/// </summary>
private void ScrapLayout()
{
var firstVisibleItem = GetFirstMaterializedIndexPath();
if (GetAndUpdateReorderingIndex() is { } reorderIndex && reorderIndex == firstVisibleItem)
{
firstVisibleItem = _materializedLines.SelectMany(line => line.Items).Skip(1).FirstOrDefault().index;
}
SetDynamicSeed(GetDynamicSeedIndex(firstVisibleItem), GetContentStart());
if (this.Log().IsEnabled(LogLevel.Debug))
{
this.Log().LogDebug($"{GetMethodTag()} seed index={_dynamicSeedIndex} seed start={_dynamicSeedStart}");
}
foreach (var line in _materializedLines)
{
ScrapLine(line);
}
_materializedLines.Clear();
}
/// <summary>
/// Get 'seed' index for recreating the visual state of the list after <see cref="ScrapLayout()"/>;
/// </summary>
private protected virtual Uno.UI.IndexPath? GetDynamicSeedIndex(Uno.UI.IndexPath? firstVisibleItem)
{
var lastItem = ItemsControl?.GetLastItem();
if (lastItem == null ||
(firstVisibleItem != null && firstVisibleItem.Value > lastItem.Value)
)
{
// None of the previously-visible indices are now present in the updated items source
return null;
}
return GetNextUnmaterializedItem(Backward, firstVisibleItem);
}
private void OnOrientationChanged(Orientation newValue)
{
Refresh();
}
internal Uno.UI.IndexPath GetFirstVisibleIndexPath()
{
return GetFirstMaterializedLine()?.FirstItem ?? Uno.UI.IndexPath.NotFound;
}
private Uno.UI.IndexPath GetLastVisibleIndexPath()
{
return GetLastMaterializedLine()?.LastItem ?? Uno.UI.IndexPath.NotFound;
}
internal IEnumerable<float> GetSnapPointsInner(SnapPointsAlignment alignment)
{
throw new NotImplementedException(); //TODO: snap points support
}
internal float AdjustOffsetForSnapPointsAlignment(float offset) => throw new NotImplementedException();
private void AddLine(GeneratorDirection fillDirection, Uno.UI.IndexPath nextVisibleItem)
{
var extentOffset = fillDirection == Backward ? GetContentStart() : GetContentEnd();
var line = CreateLine(fillDirection, extentOffset, AvailableBreadth, nextVisibleItem);
if (fillDirection == Backward)
{
_materializedLines.AddToFront(line);
}
else
{
_materializedLines.AddToBack(line);
}
// The layout might have decided to insert another item (pending reorder item), so make sure to add the requested item anyway.
// Note: We must ensure to add the requested item so the Get<First|Last>MaterializedLine()
// and Get<Content|Items><Start|End>() will still return a meaningful values.
if (!line.Contains(nextVisibleItem))
{
AddLine(fillDirection, nextVisibleItem);
}
}
/// <summary>
/// Create a new line.
/// </summary>
private protected abstract Line CreateLine(GeneratorDirection fillDirection, double extentOffset, double availableBreadth, Uno.UI.IndexPath nextVisibleItem);
protected abstract int GetItemsPerLine();
private protected int GetFlatItemIndex(Uno.UI.IndexPath indexPath) => ItemsControl?.GetIndexFromIndexPath(indexPath) ?? -1;
protected void AddView(FrameworkElement view, GeneratorDirection fillDirection, double extentOffset, double breadthOffset)
{
if (view.Parent == null)
{
//Freshly-created view
OwnerPanel.Children.Add(view);
}