using System.Collections.Specialized; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Input; using System.Windows.Media; namespace Titano.Ui.Visuals; /// /// Items host that wraps fixed-size items into rows and scrolls vertically by pixels (BRIEF §12.2: Library grid, /// 60 fps over 500k items). Only the rows in view plus one row above and below have containers; containers are /// recycled when the owner's is Recycling. Index ↔ offset /// mapping is O(1) (). Arrow keys, PageUp/PageDown and Home/End move focus and selection /// in grid order (Ctrl moves focus only, Shift extends an Extended selection). Requires a ScrollViewer with /// CanContentScroll="True"; grouping is not supported. /// public sealed class VirtualizingWrapPanel : VirtualizingPanel, IScrollInfo { public static readonly DependencyProperty ItemWidthProperty = DependencyProperty.Register( nameof(ItemWidth), typeof(double), typeof(VirtualizingWrapPanel), new FrameworkPropertyMetadata(236.0, FrameworkPropertyMetadataOptions.AffectsMeasure), IsPositive); public static readonly DependencyProperty ItemHeightProperty = DependencyProperty.Register( nameof(ItemHeight), typeof(double), typeof(VirtualizingWrapPanel), new FrameworkPropertyMetadata(208.0, FrameworkPropertyMetadataOptions.AffectsMeasure), IsPositive); public static readonly DependencyProperty SpacingProperty = DependencyProperty.Register( nameof(Spacing), typeof(double), typeof(VirtualizingWrapPanel), new FrameworkPropertyMetadata(16.0, FrameworkPropertyMetadataOptions.AffectsMeasure), IsNonNegative); public static readonly DependencyProperty JustifyProperty = DependencyProperty.Register( nameof(Justify), typeof(bool), typeof(VirtualizingWrapPanel), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.AffectsMeasure)); public static readonly DependencyProperty PaddingProperty = DependencyProperty.Register( nameof(Padding), typeof(Thickness), typeof(VirtualizingWrapPanel), new FrameworkPropertyMetadata(default(Thickness), FrameworkPropertyMetadataOptions.AffectsMeasure)); /// Rows realized beyond each edge of the viewport so the next row is ready before it scrolls in. private const int CacheRows = 1; private WrapLayout _layout; private Thickness _padding; private Size _viewport; private Size _extent; private double _offset; private int _realizedFirst; private int _realizedLast = -1; private bool _generationDirty = true; private int _anchor = -1; private int _rangeAnchor = -1; private int _rangeEnd = -1; /// Slot width of one item container (DESIGN §4: cards are 236 px). public double ItemWidth { get => (double)GetValue(ItemWidthProperty); set => SetValue(ItemWidthProperty, value); } /// Slot height of one item container. public double ItemHeight { get => (double)GetValue(ItemHeightProperty); set => SetValue(ItemHeightProperty, value); } /// Gap between columns and between rows. public double Spacing { get => (double)GetValue(SpacingProperty); set => SetValue(SpacingProperty, value); } /// Spread leftover width over the column gaps so the grid spans the full width. public bool Justify { get => (bool)GetValue(JustifyProperty); set => SetValue(JustifyProperty, value); } /// Space around the grid that scrolls with the items (unlike a ScrollViewer padding, which clips them). public Thickness Padding { get => (Thickness)GetValue(PaddingProperty); set => SetValue(PaddingProperty, value); } public bool CanHorizontallyScroll { get; set; } public bool CanVerticallyScroll { get; set; } public double ExtentWidth => _extent.Width; public double ExtentHeight => _extent.Height; public double ViewportWidth => _viewport.Width; public double ViewportHeight => _viewport.Height; public double HorizontalOffset => 0; public double VerticalOffset => _offset; public ScrollViewer? ScrollOwner { get; set; } /// Scroll distance of one line: a quarter row, at least 16 px. private double LineSize => Math.Max(16, _layout.RowPitch / 4); public void LineUp() => SetVerticalOffset(_offset - LineSize); public void LineDown() => SetVerticalOffset(_offset + LineSize); public void PageUp() => SetVerticalOffset(_offset - _viewport.Height); public void PageDown() => SetVerticalOffset(_offset + _viewport.Height); public void MouseWheelUp() => SetVerticalOffset(_offset - WheelDistance()); public void MouseWheelDown() => SetVerticalOffset(_offset + WheelDistance()); public void LineLeft() { } public void LineRight() { } public void PageLeft() { } public void PageRight() { } public void MouseWheelLeft() { } public void MouseWheelRight() { } /// Only vertical scrolling exists: rows always fit the width. public void SetHorizontalOffset(double offset) { } public void SetVerticalOffset(double offset) { offset = ClampOffset(offset); if (offset == _offset) return; _offset = offset; ScrollOwner?.InvalidateScrollInfo(); InvalidateMeasure(); } public Rect MakeVisible(Visual visual, Rect rectangle) { if (rectangle.IsEmpty || visual is null || ReferenceEquals(visual, this) || !IsAncestorOf(visual)) return Rect.Empty; var bounds = visual.TransformToAncestor(this).TransformBounds(rectangle); var top = bounds.Top + _offset; SetVerticalOffset(WrapLayout.OffsetToReveal(top, bounds.Height, _offset, _viewport.Height)); bounds.Y = top - _offset; return bounds; } protected override void BringIndexIntoView(int index) { var owner = ItemsControl.GetItemsOwner(this); if (owner is null || index < 0 || index >= owner.Items.Count) return; if (_layout.Columns == 0) UpdateLayout(); if (_layout.Columns == 0) return; SetVerticalOffset(WrapLayout.OffsetToReveal(_padding.Top + _layout.TopOf(index), _layout.ItemHeight, _offset, _viewport.Height)); UpdateLayout(); } protected override Size MeasureOverride(Size availableSize) { var owner = ItemsControl.GetItemsOwner(this); var count = owner?.Items.Count ?? 0; var previous = _layout; var previousTop = _padding.Top; _padding = Padding; var horizontal = _padding.Left + _padding.Right; var vertical = _padding.Top + _padding.Bottom; _layout = new WrapLayout(count, Math.Max(0, availableSize.Width - horizontal), ItemWidth, ItemHeight, Spacing, Justify); KeepTopItemOnReflow(previous, previousTop); var extent = new Size(_layout.ExtentWidth + horizontal, _layout.ExtentHeight + vertical); var viewportHeight = double.IsInfinity(availableSize.Height) ? extent.Height : availableSize.Height; var viewportWidth = double.IsInfinity(availableSize.Width) ? extent.Width : availableSize.Width; UpdateScrollInfo(new Size(viewportWidth, viewportHeight), new Size(Math.Max(viewportWidth, extent.Width), extent.Height)); if (owner is not null) { var (first, last) = _layout.VisibleRange(_offset - _padding.Top, viewportHeight, CacheRows); if (_generationDirty || first != _realizedFirst || last != _realizedLast) { CleanUp(owner, first, last); Realize(first, last); _realizedFirst = first; _realizedLast = last; _generationDirty = false; } var slot = new Size(ItemWidth, ItemHeight); var children = InternalChildren; for (var i = 0; i < children.Count; i++) children[i].Measure(slot); } return new Size(viewportWidth, viewportHeight); } protected override Size ArrangeOverride(Size finalSize) { var generator = ItemContainerGenerator; var children = InternalChildren; if (generator is null) return finalSize; for (var i = 0; i < children.Count; i++) { var index = generator.IndexFromGeneratorPosition(new GeneratorPosition(i, 0)); if (index < 0) continue; children[i].Arrange(new Rect(_padding.Left + _layout.LeftOf(index), _padding.Top + _layout.TopOf(index) - _offset, ItemWidth, ItemHeight)); } return finalSize; } protected override void OnItemsChanged(object sender, ItemsChangedEventArgs args) { base.OnItemsChanged(sender, args); switch (args.Action) { case NotifyCollectionChangedAction.Remove: case NotifyCollectionChangedAction.Replace: RemoveChildRange(args.Position, args.ItemUICount); break; case NotifyCollectionChangedAction.Move: RemoveChildRange(args.OldPosition, args.ItemUICount); break; } _generationDirty = true; _anchor = _rangeAnchor = _rangeEnd = -1; InvalidateMeasure(); } protected override void OnClearChildren() { base.OnClearChildren(); _generationDirty = true; _realizedFirst = 0; _realizedLast = -1; } /// Wheel scrolling proportional to the delta, so precision touchpads scroll smoothly. protected override void OnMouseWheel(MouseWheelEventArgs e) { base.OnMouseWheel(e); if (e.Handled || ScrollOwner is null) return; var before = _offset; SetVerticalOffset(_offset - e.Delta / (double)Mouse.MouseWheelDeltaForOneLine * WheelDistance()); e.Handled = _offset != before; } protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (e.Handled || (Keyboard.Modifiers & ModifierKeys.Alt) != 0) return; var step = StepFor(e.Key); var owner = ItemsControl.GetItemsOwner(this); if (step is null || owner is null || _layout.ItemCount == 0) return; var current = FocusedIndex(owner); if (current < 0) return; e.Handled = true; var target = _layout.Navigate(current, step.Value, _layout.PageRows(_viewport.Height)); if (target != current) NavigateTo(owner, current, target); } private static bool IsPositive(object value) => value is double d && double.IsFinite(d) && d > 0; private static bool IsNonNegative(object value) => value is double d && double.IsFinite(d) && d >= 0; private double WheelDistance() { var lines = SystemParameters.WheelScrollLines; return lines < 0 ? _viewport.Height : lines * LineSize; } /// When the column count changes (resize), keeps the first visible item at the same height in the viewport. private void KeepTopItemOnReflow(WrapLayout previous, double previousTop) { if (previous.Columns == _layout.Columns || previous.ItemCount == 0 || _layout.ItemCount == 0) return; var (top, _) = previous.VisibleRange(_offset - previousTop, Math.Max(1, _viewport.Height)); if (top < 0 || top >= _layout.ItemCount) return; var delta = _offset - (previousTop + previous.TopOf(top)); _offset = _padding.Top + _layout.TopOf(top) + delta; } private double ClampOffset(double offset) => double.IsNaN(offset) ? 0 : Math.Clamp(offset, 0, Math.Max(0, _extent.Height - _viewport.Height)); private void UpdateScrollInfo(Size viewport, Size extent) { var changed = viewport != _viewport || extent != _extent; _viewport = viewport; _extent = extent; var clamped = ClampOffset(_offset); if (clamped != _offset) { _offset = clamped; changed = true; } if (changed) ScrollOwner?.InvalidateScrollInfo(); } /// Recycles (or removes) containers outside [first, last]; a container holding keyboard focus is kept. private void CleanUp(ItemsControl owner, int first, int last) { var generator = ItemContainerGenerator; if (generator is null) return; var recycling = GetVirtualizationMode(owner) == VirtualizationMode.Recycling; var children = InternalChildren; for (var i = children.Count - 1; i >= 0; i--) { var position = new GeneratorPosition(i, 0); var index = generator.IndexFromGeneratorPosition(position); if ((index >= first && index <= last) || children[i].IsKeyboardFocusWithin) continue; if (recycling) ((IRecyclingItemContainerGenerator)generator).Recycle(position, 1); else generator.Remove(position, 1); RemoveInternalChildRange(i, 1); } } /// Generates containers for [first, last], inserting them so children stay in item order. private void Realize(int first, int last) { var generator = ItemContainerGenerator; if (generator is null || last < first) return; var start = generator.GeneratorPositionFromIndex(first); var childIndex = start.Offset == 0 ? start.Index : start.Index + 1; using (generator.StartAt(start, GeneratorDirection.Forward, true)) { for (var i = first; i <= last; i++, childIndex++) { if (generator.GenerateNext(out var newlyRealized) is not UIElement child) break; if (!newlyRealized) continue; if (childIndex >= InternalChildren.Count) AddInternalChild(child); else InsertInternalChild(childIndex, child); generator.PrepareItemContainer(child); } } } private void RemoveChildRange(GeneratorPosition position, int uiCount) { if (uiCount <= 0) return; var index = position.Offset > 0 ? position.Index + 1 : position.Index; var children = InternalChildren; if (index < children.Count) RemoveInternalChildRange(index, Math.Min(uiCount, children.Count - index)); } private WrapStep? StepFor(Key key) { var rtl = FlowDirection == FlowDirection.RightToLeft; return key switch { Key.Left => rtl ? WrapStep.Right : WrapStep.Left, Key.Right => rtl ? WrapStep.Left : WrapStep.Right, Key.Up => WrapStep.Up, Key.Down => WrapStep.Down, Key.PageUp => WrapStep.PageUp, Key.PageDown => WrapStep.PageDown, Key.Home => WrapStep.First, Key.End => WrapStep.Last, _ => null, }; } private static int FocusedIndex(ItemsControl owner) { if (Keyboard.FocusedElement is not DependencyObject focused) return -1; var container = owner.ContainerFromElement(focused); return container is null ? -1 : owner.ItemContainerGenerator.IndexFromContainer(container); } private void NavigateTo(ItemsControl owner, int from, int to) { BringIndexIntoView(to); if (owner.ItemContainerGenerator.ContainerFromIndex(to) is not UIElement container) return; container.Focus(); if (owner is not Selector selector) return; var modifiers = Keyboard.Modifiers; var mode = owner is ListBox listBox ? listBox.SelectionMode : SelectionMode.Single; if (mode == SelectionMode.Multiple || (mode == SelectionMode.Extended && (modifiers & ModifierKeys.Control) != 0)) return; if (mode == SelectionMode.Extended && (modifiers & ModifierKeys.Shift) != 0) { SelectRange((ListBox)owner, from, to); return; } selector.SelectedIndex = to; _anchor = to; _rangeAnchor = _rangeEnd = -1; } /// Selects anchor…, touching only the items that enter or leave the previous range. private void SelectRange(ListBox listBox, int from, int to) { var items = listBox.Items; var anchor = _anchor >= 0 && _anchor < items.Count && listBox.SelectedItems.Contains(items[_anchor]) ? _anchor : from; _anchor = anchor; var newLow = Math.Min(anchor, to); var newHigh = Math.Max(anchor, to); if (_rangeAnchor != anchor || _rangeEnd < 0) { listBox.SelectedItems.Clear(); for (var i = newLow; i <= newHigh; i++) listBox.SelectedItems.Add(items[i]); } else { var oldLow = Math.Min(anchor, _rangeEnd); var oldHigh = Math.Max(anchor, _rangeEnd); for (var i = oldLow; i <= oldHigh; i++) if (i < newLow || i > newHigh) listBox.SelectedItems.Remove(items[i]); for (var i = newLow; i <= newHigh; i++) if (i < oldLow || i > oldHigh) listBox.SelectedItems.Add(items[i]); } _rangeAnchor = anchor; _rangeEnd = to; } }