1 /* Copyright (c) 2021 Samsung Electronics Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
7 * http://www.apache.org/licenses/LICENSE-2.0
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
17 using Tizen.NUI.BaseComponents;
18 using System.Collections.Generic;
19 using System.ComponentModel;
20 using System.Diagnostics;
21 using System.Runtime.InteropServices;
22 using Tizen.NUI.Accessibility;
24 namespace Tizen.NUI.Components
27 /// ScrollEventArgs is a class to record scroll event arguments which will sent to user.
29 /// <since_tizen> 8 </since_tizen>
30 [global::System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1001: Types that own disposable fields should be disposable.", Justification = "Scroll event is temporarily used for notifying scroll position update, so position will not be disposed during the event processing.")]
31 public class ScrollEventArgs : EventArgs
33 // Position class is derived class of Disposable class and they will be implicitly disposed by DisposeQueue,
34 // so that there will be no memory leak.
35 private Position position;
36 private Position scrollPosition;
39 /// Default constructor.
41 /// <param name="position">Current container position</param>
42 /// <since_tizen> 8 </since_tizen>
43 public ScrollEventArgs(Position position)
45 this.position = position;
46 this.scrollPosition = new Position(-position);
50 /// Current position of ContentContainer.
52 /// <since_tizen> 8 </since_tizen>
53 public Position Position
61 /// Current scroll position of scrollableBase pan.
62 /// This is the position in the opposite direction to the current position of ContentContainer.
64 [EditorBrowsable(EditorBrowsableState.Never)]
65 public Position ScrollPosition
69 return scrollPosition;
75 /// ScrollOutofBoundEventArgs is to record scroll out-of-bound event arguments which will be sent to user.
77 [EditorBrowsable(EditorBrowsableState.Never)]
78 public class ScrollOutOfBoundEventArgs : EventArgs
81 /// The direction to be touched.
83 [EditorBrowsable(EditorBrowsableState.Never)]
89 [EditorBrowsable(EditorBrowsableState.Never)]
95 [EditorBrowsable(EditorBrowsableState.Never)]
101 [EditorBrowsable(EditorBrowsableState.Never)]
107 [EditorBrowsable(EditorBrowsableState.Never)]
114 /// <param name="direction">Current pan direction</param>
115 /// <param name="displacement">Current total displacement</param>
116 [EditorBrowsable(EditorBrowsableState.Never)]
117 public ScrollOutOfBoundEventArgs(Direction direction, float displacement)
119 PanDirection = direction;
120 Displacement = displacement;
124 /// Current pan direction of ContentContainer.
126 [EditorBrowsable(EditorBrowsableState.Never)]
127 public Direction PanDirection
133 /// Current total displacement of ContentContainer.
134 /// if its value is greater than 0, it is at the top/left;
135 /// if less than 0, it is at the bottom/right.
137 [EditorBrowsable(EditorBrowsableState.Never)]
138 public float Displacement
145 /// This class provides a View that can scroll a single View with a layout. This View can be a nest of Views.
147 /// <since_tizen> 8 </since_tizen>
148 public partial class ScrollableBase : Control
150 static bool LayoutDebugScrollableBase = false; // Debug flag
151 static bool focusDebugScrollableBase = false; // Debug flag
152 private Direction mScrollingDirection = Direction.Vertical;
153 private bool mScrollEnabled = true;
154 private int mScrollDuration = 125;
155 private int mPageWidth = 0;
156 private float mPageFlickThreshold = 0.4f;
157 private float mScrollingEventThreshold = 0.001f;
158 private bool fadeScrollbar = true;
160 private class ScrollableBaseCustomLayout : AbsoluteLayout
162 protected override void OnMeasure(MeasureSpecification widthMeasureSpec, MeasureSpecification heightMeasureSpec)
164 MeasuredSize.StateType childWidthState = MeasuredSize.StateType.MeasuredSizeOK;
165 MeasuredSize.StateType childHeightState = MeasuredSize.StateType.MeasuredSizeOK;
167 Direction scrollingDirection = Direction.Vertical;
168 ScrollableBase scrollableBase = this.Owner as ScrollableBase;
169 if (scrollableBase != null)
171 scrollingDirection = scrollableBase.ScrollingDirection;
174 float totalWidth = 0.0f;
175 float totalHeight = 0.0f;
177 // measure child, should be a single scrolling child
178 foreach (LayoutItem childLayout in LayoutChildren)
180 if (childLayout != null && childLayout.Owner.Name == "ContentContainer")
183 // Use an Unspecified MeasureSpecification mode so scrolling child is not restricted to it's parents size in Height (for vertical scrolling)
184 // or Width for horizontal scrolling
185 if (scrollingDirection == Direction.Vertical)
187 MeasureSpecification unrestrictedMeasureSpec = new MeasureSpecification(heightMeasureSpec.Size, MeasureSpecification.ModeType.Unspecified);
188 MeasureChildWithMargins(childLayout, widthMeasureSpec, new LayoutLength(0), unrestrictedMeasureSpec, new LayoutLength(0)); // Height unrestricted by parent
192 MeasureSpecification unrestrictedMeasureSpec = new MeasureSpecification(widthMeasureSpec.Size, MeasureSpecification.ModeType.Unspecified);
193 MeasureChildWithMargins(childLayout, unrestrictedMeasureSpec, new LayoutLength(0), heightMeasureSpec, new LayoutLength(0)); // Width unrestricted by parent
196 totalWidth = (childLayout.MeasuredWidth.Size + (childLayout.Padding.Start + childLayout.Padding.End)).AsDecimal();
197 totalHeight = (childLayout.MeasuredHeight.Size + (childLayout.Padding.Top + childLayout.Padding.Bottom)).AsDecimal();
199 if (childLayout.MeasuredWidth.State == MeasuredSize.StateType.MeasuredSizeTooSmall)
201 childWidthState = MeasuredSize.StateType.MeasuredSizeTooSmall;
203 if (childLayout.MeasuredHeight.State == MeasuredSize.StateType.MeasuredSizeTooSmall)
205 childHeightState = MeasuredSize.StateType.MeasuredSizeTooSmall;
210 MeasuredSize widthSizeAndState = ResolveSizeAndState(new LayoutLength(totalWidth), widthMeasureSpec, MeasuredSize.StateType.MeasuredSizeOK);
211 MeasuredSize heightSizeAndState = ResolveSizeAndState(new LayoutLength(totalHeight), heightMeasureSpec, MeasuredSize.StateType.MeasuredSizeOK);
212 totalWidth = widthSizeAndState.Size.AsDecimal();
213 totalHeight = heightSizeAndState.Size.AsDecimal();
215 // Ensure layout respects it's given minimum size
216 totalWidth = Math.Max(totalWidth, SuggestedMinimumWidth.AsDecimal());
217 totalHeight = Math.Max(totalHeight, SuggestedMinimumHeight.AsDecimal());
219 widthSizeAndState.State = childWidthState;
220 heightSizeAndState.State = childHeightState;
222 SetMeasuredDimensions(ResolveSizeAndState(new LayoutLength(totalWidth), widthMeasureSpec, childWidthState),
223 ResolveSizeAndState(new LayoutLength(totalHeight), heightMeasureSpec, childHeightState));
225 // Size of ScrollableBase is changed. Change Page width too.
226 if (scrollableBase != null)
228 scrollableBase.mPageWidth = (int)MeasuredWidth.Size.AsRoundedValue();
229 scrollableBase.OnScrollingChildRelayout(null, null);
232 } // ScrollableBaseCustomLayout
235 /// The direction axis to scroll.
237 /// <since_tizen> 8 </since_tizen>
238 public enum Direction
243 /// <since_tizen> 8 </since_tizen>
249 /// <since_tizen> 8 </since_tizen>
254 /// Scrolling direction mode.
255 /// Default is Vertical scrolling.
257 /// <since_tizen> 8 </since_tizen>
258 public Direction ScrollingDirection
262 return (Direction)GetValue(ScrollingDirectionProperty);
266 SetValue(ScrollingDirectionProperty, value);
267 NotifyPropertyChanged();
270 private Direction InternalScrollingDirection
274 return mScrollingDirection;
278 if (value != mScrollingDirection)
280 //Reset scroll position and stop scroll animation
283 mScrollingDirection = value;
284 mPanGestureDetector.ClearAngles();
285 mPanGestureDetector.AddDirection(value == Direction.Horizontal ?
286 PanGestureDetector.DirectionHorizontal : PanGestureDetector.DirectionVertical);
288 ContentContainer.WidthSpecification = ScrollingDirection == Direction.Vertical ? LayoutParamPolicies.MatchParent : LayoutParamPolicies.WrapContent;
289 ContentContainer.HeightSpecification = ScrollingDirection == Direction.Vertical ? LayoutParamPolicies.WrapContent : LayoutParamPolicies.MatchParent;
296 /// Enable or disable scrolling.
298 /// <since_tizen> 8 </since_tizen>
299 public bool ScrollEnabled
303 return (bool)GetValue(ScrollEnabledProperty);
307 SetValue(ScrollEnabledProperty, value);
308 NotifyPropertyChanged();
311 private bool InternalScrollEnabled
315 return mScrollEnabled;
319 if (value != mScrollEnabled)
321 mScrollEnabled = value;
324 mPanGestureDetector.Detected += OnPanGestureDetected;
328 mPanGestureDetector.Detected -= OnPanGestureDetected;
335 /// Gets scrollable status.
337 [EditorBrowsable(EditorBrowsableState.Never)]
338 protected override bool AccessibilityIsScrollable()
344 /// Pages mode, enables moving to the next or return to current page depending on pan displacement.
345 /// Default is false.
347 /// <since_tizen> 8 </since_tizen>
348 public bool SnapToPage
352 return (bool)GetValue(SnapToPageProperty);
356 SetValue(SnapToPageProperty, value);
357 NotifyPropertyChanged();
360 private bool InternalSnapToPage { set; get; } = false;
363 /// Get current page.
364 /// Working property with SnapToPage property.
366 /// <since_tizen> 8 </since_tizen>
367 public int CurrentPage { get; private set; } = 0;
370 /// Duration of scroll animation.
371 /// Default value is 125ms.
373 /// <since_tizen> 8 </since_tizen>
374 public int ScrollDuration
378 return (int)GetValue(ScrollDurationProperty);
382 SetValue(ScrollDurationProperty, value);
383 NotifyPropertyChanged();
386 private int InternalScrollDuration
390 mScrollDuration = value >= 0 ? value : mScrollDuration;
394 return mScrollDuration;
399 /// Scroll Available area.
401 /// <since_tizen> 8 </since_tizen>
402 public Vector2 ScrollAvailableArea
406 return GetValue(ScrollAvailableAreaProperty) as Vector2;
410 SetValue(ScrollAvailableAreaProperty, value);
411 NotifyPropertyChanged();
414 private Vector2 InternalScrollAvailableArea { set; get; }
417 /// An event emitted when user starts dragging ScrollableBase, user can subscribe or unsubscribe to this event handler.<br />
419 /// <since_tizen> 8 </since_tizen>
420 public event EventHandler<ScrollEventArgs> ScrollDragStarted;
423 /// An event emitted when user stops dragging ScrollableBase, user can subscribe or unsubscribe to this event handler.<br />
425 /// <since_tizen> 8 </since_tizen>
426 public event EventHandler<ScrollEventArgs> ScrollDragEnded;
429 /// An event emitted when the scrolling slide animation starts, user can subscribe or unsubscribe to this event handler.<br />
431 /// <since_tizen> 8 </since_tizen>
432 public event EventHandler<ScrollEventArgs> ScrollAnimationStarted;
435 /// An event emitted when the scrolling slide animation ends, user can subscribe or unsubscribe to this event handler.<br />
437 /// <since_tizen> 8 </since_tizen>
438 public event EventHandler<ScrollEventArgs> ScrollAnimationEnded;
441 /// An event emitted when scrolling, user can subscribe or unsubscribe to this event handler.<br />
443 /// <since_tizen> 8 </since_tizen>
444 public event EventHandler<ScrollEventArgs> Scrolling;
447 /// An event emitted when scrolling out of bound, user can subscribe or unsubscribe to this event handler.<br />
449 [EditorBrowsable(EditorBrowsableState.Never)]
450 public event EventHandler<ScrollOutOfBoundEventArgs> ScrollOutOfBound;
453 /// Scrollbar for ScrollableBase.
455 /// <since_tizen> 8 </since_tizen>
456 public ScrollbarBase Scrollbar
460 return GetValue(ScrollbarProperty) as ScrollbarBase;
464 SetValue(ScrollbarProperty, value);
465 NotifyPropertyChanged();
468 private ScrollbarBase InternalScrollbar
478 base.Remove(scrollBar);
482 if (scrollBar != null)
484 scrollBar.Name = "ScrollBar";
502 /// Always hide Scrollbar.
504 /// <since_tizen> 8 </since_tizen>
505 public bool HideScrollbar
509 return (bool)GetValue(HideScrollbarProperty);
513 SetValue(HideScrollbarProperty, value);
514 NotifyPropertyChanged();
517 private bool InternalHideScrollbar
521 return hideScrollbar;
525 hideScrollbar = value;
538 scrollBar.Opacity = 1.0f;
547 /// The boolean flag for automatic fading Scrollbar.
548 /// Scrollbar will be faded out when scroll stay in certain position longer than the threshold.
549 /// Scrollbar will be faded in scroll position changes.
551 [EditorBrowsable(EditorBrowsableState.Never)]
552 public bool FadeScrollbar
554 get => (bool)GetValue(FadeScrollbarProperty);
555 set => SetValue(FadeScrollbarProperty, value);
558 private bool InternalFadeScrollbar
562 return fadeScrollbar;
566 fadeScrollbar = value;
568 if (scrollBar != null && !hideScrollbar)
576 scrollBar.Opacity = 1.0f;
577 // Removing fadeout timer and animation.
585 /// Container which has content of ScrollableBase.
587 /// <since_tizen> 8 </since_tizen>
588 public View ContentContainer { get; private set; }
591 /// Set the layout on this View. Replaces any existing Layout.
593 /// <since_tizen> 8 </since_tizen>
594 public new LayoutItem Layout
598 return GetValue(LayoutProperty) as LayoutItem;
602 SetValue(LayoutProperty, value);
603 NotifyPropertyChanged();
606 private LayoutItem InternalLayout
610 return ContentContainer.Layout;
614 ContentContainer.Layout = value;
619 /// List of children of Container.
621 /// <since_tizen> 8 </since_tizen>
622 public new List<View> Children
626 return ContentContainer.Children;
631 /// Deceleration rate of scrolling by finger.
632 /// Rate should be bigger than 0 and smaller than 1.
633 /// Default value is 0.998f;
635 /// <since_tizen> 8 </since_tizen>
636 public float DecelerationRate
640 return (float)GetValue(DecelerationRateProperty);
644 SetValue(DecelerationRateProperty, value);
645 NotifyPropertyChanged();
648 private float InternalDecelerationRate
652 return decelerationRate;
656 decelerationRate = (value < 1 && value > 0) ? value : decelerationRate;
657 logValueOfDeceleration = (float)Math.Log(value);
662 /// Threshold not to go infinite at the end of scrolling animation.
664 [EditorBrowsable(EditorBrowsableState.Never)]
665 public float DecelerationThreshold
669 return (float)GetValue(DecelerationThresholdProperty);
673 SetValue(DecelerationThresholdProperty, value);
674 NotifyPropertyChanged();
677 private float InternalDecelerationThreshold { get; set; } = 0.1f;
680 /// Scrolling event will be thrown when this amount of scroll position is changed.
681 /// If this threshold becomes smaller, the tracking detail increases but the scrolling range that can be tracked becomes smaller.
682 /// If large sized ContentContainer is required, please use larger threshold value.
683 /// Default ScrollingEventThreshold value is 0.001f.
685 [EditorBrowsable(EditorBrowsableState.Never)]
686 public float ScrollingEventThreshold
690 return (float)GetValue(ScrollingEventThresholdProperty);
694 SetValue(ScrollingEventThresholdProperty, value);
695 NotifyPropertyChanged();
698 private float InternalScrollingEventThreshold
702 return mScrollingEventThreshold;
706 if (mScrollingEventThreshold != value && value > 0)
708 ContentContainer.RemovePropertyNotification(propertyNotification);
709 propertyNotification = ContentContainer.AddPropertyNotification("position", PropertyCondition.Step(value));
710 propertyNotification.Notified += OnPropertyChanged;
711 mScrollingEventThreshold = value;
717 /// Page will be changed when velocity of panning is over threshold.
718 /// The unit of threshold is pixel per millisecond.
720 /// <since_tizen> 8 </since_tizen>
721 public float PageFlickThreshold
725 return (float)GetValue(PageFlickThresholdProperty);
729 SetValue(PageFlickThresholdProperty, value);
730 NotifyPropertyChanged();
733 private float InternalPageFlickThreshold
737 return mPageFlickThreshold;
741 mPageFlickThreshold = value >= 0f ? value : mPageFlickThreshold;
746 /// Padding for the ScrollableBase
748 [EditorBrowsable(EditorBrowsableState.Never)]
749 public new Extents Padding
753 return GetValue(PaddingProperty) as Extents;
757 SetValue(PaddingProperty, value);
758 NotifyPropertyChanged();
761 private Extents InternalPadding
765 return ContentContainer.Padding;
769 ContentContainer.Padding = value;
774 /// Alphafunction for scroll animation.
776 [EditorBrowsable(EditorBrowsableState.Never)]
777 public AlphaFunction ScrollAlphaFunction
781 return GetValue(ScrollAlphaFunctionProperty) as AlphaFunction;
785 SetValue(ScrollAlphaFunctionProperty, value);
786 NotifyPropertyChanged();
789 private AlphaFunction InternalScrollAlphaFunction { get; set; } = new AlphaFunction(AlphaFunction.BuiltinFunctions.Linear);
791 private bool hideScrollbar = true;
792 private float maxScrollDistance;
793 private float childTargetPosition = 0.0f;
794 private PanGestureDetector mPanGestureDetector;
795 private ScrollbarBase scrollBar;
796 private bool scrolling = false;
797 private float ratioOfScreenWidthToCompleteScroll = 0.5f;
798 private float totalDisplacementForPan = 0.0f;
799 private Size previousContainerSize = new Size();
800 private Size previousSize = new Size();
801 private PropertyNotification propertyNotification;
802 private float noticeAnimationEndBeforePosition = 0.0f;
803 private bool readyToNotice = false;
806 /// Notice before animation is finished.
808 [EditorBrowsable(EditorBrowsableState.Never)]
809 // Let's consider more whether this needs to be set as protected.
810 public float NoticeAnimationEndBeforePosition
814 return (float)GetValue(NoticeAnimationEndBeforePositionProperty);
818 SetValue(NoticeAnimationEndBeforePositionProperty, value);
819 NotifyPropertyChanged();
822 private float InternalNoticeAnimationEndBeforePosition
824 get => noticeAnimationEndBeforePosition;
825 set => noticeAnimationEndBeforePosition = value;
829 /// Step scroll move distance.
830 /// Key focus originally moves focusable objects, but in ScrollableBase,
831 /// if focusable object is too far or un-exist and ScrollableBase is focusable,
832 /// it can scroll move itself by key input.
833 /// this value decide how long distance will it moves in one step.
834 /// if any value is not set, step will be moved quater size of ScrollableBase length.
836 [EditorBrowsable(EditorBrowsableState.Never)]
837 public float StepScrollDistance
841 return (float)GetValue(StepScrollDistanceProperty);
845 SetValue(StepScrollDistanceProperty, value);
846 NotifyPropertyChanged();
849 private float stepScrollDistance = 0f;
852 // Let's consider more whether this needs to be set as protected.
853 private float finalTargetPosition;
855 private Animation scrollAnimation;
856 // Declare user alpha function delegate
857 [UnmanagedFunctionPointer(CallingConvention.StdCall)]
858 private delegate float UserAlphaFunctionDelegate(float progress);
859 private UserAlphaFunctionDelegate customScrollAlphaFunction;
860 private float velocityOfLastPan = 0.0f;
861 private float panAnimationDuration = 0.0f;
862 private float panAnimationDelta = 0.0f;
863 private float logValueOfDeceleration = 0.0f;
864 private float decelerationRate = 0.0f;
866 private View topOverShootingShadowView;
867 private View bottomOverShootingShadowView;
868 private View leftOverShootingShadowView;
869 private View rightOverShootingShadowView;
870 private const int overShootingShadowScaleHeightLimit = 64 * 3;
871 private const int overShootingShadowAnimationDuration = 300;
872 private Animation overShootingShadowAnimation;
873 private bool isOverShootingShadowShown = false;
874 private float startShowShadowDisplacement;
877 /// Default Constructor
879 /// <since_tizen> 8 </since_tizen>
880 public ScrollableBase() : base()
882 DecelerationRate = 0.998f;
884 base.Layout = new ScrollableBaseCustomLayout();
885 mPanGestureDetector = new PanGestureDetector();
886 mPanGestureDetector.Attach(this);
887 mPanGestureDetector.AddDirection(PanGestureDetector.DirectionVertical);
888 if (mPanGestureDetector.GetMaximumTouchesRequired() < 2) mPanGestureDetector.SetMaximumTouchesRequired(2);
889 mPanGestureDetector.Detected += OnPanGestureDetected;
891 ClippingMode = ClippingModeType.ClipToBoundingBox;
893 //Default Scrolling child
894 ContentContainer = new View()
896 Name = "ContentContainer",
897 WidthSpecification = ScrollingDirection == Direction.Vertical ? LayoutParamPolicies.MatchParent : LayoutParamPolicies.WrapContent,
898 HeightSpecification = ScrollingDirection == Direction.Vertical ? LayoutParamPolicies.WrapContent : LayoutParamPolicies.MatchParent,
900 // Check if children's sizes change to update Scrollbar
901 ContentContainer.Relayout += OnScrollingChildRelayout;
902 propertyNotification = ContentContainer.AddPropertyNotification("position", PropertyCondition.Step(mScrollingEventThreshold));
903 propertyNotification.Notified += OnPropertyChanged;
904 base.Add(ContentContainer);
905 // Check if ScrollableBase's size changes to update Scrollbar
906 base.Relayout += OnScrollingChildRelayout;
908 Scrollbar = new Scrollbar();
910 //Show vertical shadow on the top (or bottom) of the scrollable when panning down (or up).
911 topOverShootingShadowView = new View
913 BackgroundImage = FrameworkInformation.ResourcePath + "nui_component_default_scroll_over_shooting_top.png",
916 PositionUsesPivotPoint = true,
917 ParentOrigin = NUI.ParentOrigin.TopCenter,
918 PivotPoint = NUI.PivotPoint.TopCenter,
920 bottomOverShootingShadowView = new View
922 BackgroundImage = FrameworkInformation.ResourcePath + "nui_component_default_scroll_over_shooting_bottom.png",
925 PositionUsesPivotPoint = true,
926 ParentOrigin = NUI.ParentOrigin.BottomCenter,
927 PivotPoint = NUI.PivotPoint.BottomCenter,
929 //Show horizontal shadow on the left (or right) of the scrollable when panning down (or up).
930 leftOverShootingShadowView = new View
932 BackgroundImage = FrameworkInformation.ResourcePath + "nui_component_default_scroll_over_shooting_left.png",
935 PositionUsesPivotPoint = true,
936 ParentOrigin = NUI.ParentOrigin.CenterLeft,
937 PivotPoint = NUI.PivotPoint.CenterLeft,
939 rightOverShootingShadowView = new View
941 BackgroundImage = FrameworkInformation.ResourcePath + "nui_component_default_scroll_over_shooting_right.png",
944 PositionUsesPivotPoint = true,
945 ParentOrigin = NUI.ParentOrigin.CenterRight,
946 PivotPoint = NUI.PivotPoint.CenterRight,
949 AccessibilityManager.Instance.SetAccessibilityAttribute(this, AccessibilityManager.AccessibilityAttribute.Trait, "ScrollableBase");
951 SetKeyboardNavigationSupport(true);
954 private bool OnInterruptTouchingChildTouched(object source, View.TouchEventArgs args)
956 if (args.Touch.GetState(0) == PointStateType.Down)
958 if (scrolling && !SnapToPage)
966 private void OnPropertyChanged(object source, PropertyNotification.NotifyEventArgs args)
972 /// Called after a child has been added to the owning view.
974 /// <param name="view">The child which has been added.</param>
975 /// <since_tizen> 8 </since_tizen>
976 public override void Add(View view)
978 ContentContainer.Add(view);
982 /// Called after a child has been removed from the owning view.
984 /// <param name="view">The child which has been removed.</param>
985 /// <since_tizen> 8 </since_tizen>
986 public override void Remove(View view)
988 if (SnapToPage && CurrentPage == Children.IndexOf(view) && CurrentPage == Children.Count - 1 && Children.Count > 1)
990 // Target View is current page and also last child.
991 // CurrentPage should be changed to previous page.
992 ScrollToIndex(CurrentPage - 1);
995 ContentContainer.Remove(view);
998 private void OnScrollingChildRelayout(object source, EventArgs args)
1000 // Size is changed. Calculate maxScrollDistance.
1001 bool isSizeChanged = previousContainerSize.Width != ContentContainer.Size.Width || previousContainerSize.Height != ContentContainer.Size.Height ||
1002 previousSize.Width != Size.Width || previousSize.Height != Size.Height;
1006 maxScrollDistance = CalculateMaximumScrollDistance();
1007 if (!ReviseContainerPositionIfNeed())
1013 previousContainerSize = new Size(ContentContainer.Size);
1014 previousSize = new Size(Size);
1017 private bool ReviseContainerPositionIfNeed()
1019 bool isHorizontal = ScrollingDirection == Direction.Horizontal;
1020 float currentPosition = isHorizontal ? ContentContainer.CurrentPosition.X : ContentContainer.CurrentPosition.Y;
1022 if (Math.Abs(currentPosition) > maxScrollDistance)
1025 var targetPosition = BoundScrollPosition(-maxScrollDistance);
1026 if (isHorizontal) ContentContainer.PositionX = targetPosition;
1027 else ContentContainer.PositionY = targetPosition;
1035 /// The composition of a Scrollbar can vary depending on how you use ScrollableBase.
1036 /// Set the composition that will go into the ScrollableBase according to your ScrollableBase.
1038 /// <since_tizen> 8 </since_tizen>
1039 [EditorBrowsable(EditorBrowsableState.Never)]
1040 protected virtual void SetScrollbar()
1044 bool isHorizontal = ScrollingDirection == Direction.Horizontal;
1045 float contentLength = isHorizontal ? ContentContainer.Size.Width : ContentContainer.Size.Height;
1046 float viewportLength = isHorizontal ? Size.Width : Size.Height;
1047 float currentPosition = isHorizontal ? ContentContainer.CurrentPosition.X : ContentContainer.CurrentPosition.Y;
1048 Scrollbar.Initialize(contentLength, viewportLength, -currentPosition, isHorizontal);
1052 /// Update scrollbar position and size.
1053 [EditorBrowsable(EditorBrowsableState.Never)]
1054 protected virtual void UpdateScrollbar()
1058 bool isHorizontal = ScrollingDirection == Direction.Horizontal;
1059 float contentLength = isHorizontal ? ContentContainer.Size.Width : ContentContainer.Size.Height;
1060 float viewportLength = isHorizontal ? Size.Width : Size.Height;
1061 float currentPosition = isHorizontal ? ContentContainer.CurrentPosition.X : ContentContainer.CurrentPosition.Y;
1062 Scrollbar.Update(contentLength, viewportLength, -currentPosition);
1064 if (!hideScrollbar && fadeScrollbar)
1066 Scrollbar.FadeOut();
1072 /// Scrolls to the item at the specified index.
1074 /// <param name="index">Index of item.</param>
1075 /// <since_tizen> 8 </since_tizen>
1076 public void ScrollToIndex(int index)
1078 if (ContentContainer.ChildCount - 1 < index || index < 0)
1085 CurrentPage = index;
1088 float targetPosition = Math.Min(ScrollingDirection == Direction.Vertical ? Children[index].Position.Y : Children[index].Position.X, maxScrollDistance);
1089 AnimateChildTo(ScrollDuration, -targetPosition);
1092 internal void ScrollToChild(View child, bool anim = false)
1094 if (null == FindDescendantByID(child.ID)) return;
1096 bool isHorizontal = (ScrollingDirection == Direction.Horizontal);
1098 float viewScreenPosition = (isHorizontal? ScreenPosition.X : ScreenPosition.Y);
1099 float childScreenPosition = (isHorizontal? child.ScreenPosition.X : child.ScreenPosition.Y);
1100 float scrollPosition = (isHorizontal? ScrollPosition.X : ScrollPosition.Y);
1101 float viewSize = (isHorizontal? SizeWidth : SizeHeight);
1102 float childSize = (isHorizontal? child.SizeWidth : child.SizeHeight);
1104 if (viewScreenPosition > childScreenPosition ||
1105 viewScreenPosition + viewSize < childScreenPosition + childSize)
1106 {// if object is outside
1107 float targetPosition;
1108 float dist = viewScreenPosition - childScreenPosition;
1110 {// if object is upper side
1111 targetPosition = scrollPosition - dist;
1114 {// if object is down side
1115 targetPosition = scrollPosition - dist + childSize - viewSize;
1117 ScrollTo(targetPosition, anim);
1121 private void OnScrollDragStarted()
1123 ScrollEventArgs eventArgs = new ScrollEventArgs(ContentContainer.CurrentPosition);
1124 ScrollDragStarted?.Invoke(this, eventArgs);
1126 if (!hideScrollbar && fadeScrollbar)
1128 scrollBar?.FadeIn();
1132 private void OnScrollDragEnded()
1134 ScrollEventArgs eventArgs = new ScrollEventArgs(ContentContainer.CurrentPosition);
1135 ScrollDragEnded?.Invoke(this, eventArgs);
1137 if (!hideScrollbar && fadeScrollbar)
1139 scrollBar?.FadeOut();
1143 private void OnScrollAnimationStarted()
1145 ScrollEventArgs eventArgs = new ScrollEventArgs(ContentContainer.CurrentPosition);
1146 ScrollAnimationStarted?.Invoke(this, eventArgs);
1148 if (!hideScrollbar && fadeScrollbar)
1150 scrollBar?.FadeIn();
1154 private void OnScrollAnimationEnded()
1157 this.InterceptTouchEvent -= OnInterruptTouchingChildTouched;
1159 ScrollEventArgs eventArgs = new ScrollEventArgs(ContentContainer.CurrentPosition);
1160 ScrollAnimationEnded?.Invoke(this, eventArgs);
1162 if (!hideScrollbar && fadeScrollbar)
1164 scrollBar?.FadeOut();
1168 private void OnScroll()
1170 ScrollEventArgs eventArgs = new ScrollEventArgs(ContentContainer.CurrentPosition);
1171 Scrolling?.Invoke(this, eventArgs);
1173 bool isHorizontal = ScrollingDirection == Direction.Horizontal;
1174 float contentLength = isHorizontal ? ContentContainer.Size.Width : ContentContainer.Size.Height;
1175 float currentPosition = isHorizontal ? ContentContainer.CurrentPosition.X : ContentContainer.CurrentPosition.Y;
1177 scrollBar?.Update(contentLength, Math.Abs(currentPosition));
1178 CheckPreReachedTargetPosition();
1181 private void CheckPreReachedTargetPosition()
1183 // Check whether we reached pre-reached target position
1184 if (readyToNotice &&
1185 ContentContainer.CurrentPosition.Y <= finalTargetPosition + NoticeAnimationEndBeforePosition &&
1186 ContentContainer.CurrentPosition.Y >= finalTargetPosition - NoticeAnimationEndBeforePosition)
1189 readyToNotice = false;
1190 OnPreReachedTargetPosition(finalTargetPosition);
1195 /// This helps developer who wants to know before scroll is reaching target position.
1197 /// <param name="targetPosition">Index of item.</param>
1198 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
1199 [EditorBrowsable(EditorBrowsableState.Never)]
1200 protected virtual void OnPreReachedTargetPosition(float targetPosition)
1205 private void StopScroll()
1207 if (scrollAnimation != null)
1209 if (scrollAnimation.State == Animation.States.Playing)
1211 Debug.WriteLineIf(LayoutDebugScrollableBase, "StopScroll Animation Playing");
1212 scrollAnimation.Stop(Animation.EndActions.Cancel);
1213 OnScrollAnimationEnded();
1215 scrollAnimation.Clear();
1219 private void AnimateChildTo(int duration, float axisPosition)
1221 Debug.WriteLineIf(LayoutDebugScrollableBase, "AnimationTo Animation Duration:" + duration + " Destination:" + axisPosition);
1222 finalTargetPosition = axisPosition;
1224 StopScroll(); // Will replace previous animation so will stop existing one.
1226 if (scrollAnimation == null)
1228 scrollAnimation = new Animation();
1229 scrollAnimation.Finished += ScrollAnimationFinished;
1232 scrollAnimation.Duration = duration;
1233 scrollAnimation.DefaultAlphaFunction = new AlphaFunction(AlphaFunction.BuiltinFunctions.EaseOutSquare);
1234 scrollAnimation.AnimateTo(ContentContainer, (ScrollingDirection == Direction.Horizontal) ? "PositionX" : "PositionY", axisPosition, ScrollAlphaFunction);
1236 OnScrollAnimationStarted();
1237 scrollAnimation.Play();
1241 /// Scroll to specific position with or without animation.
1243 /// <param name="position">Destination.</param>
1244 /// <param name="animate">Scroll with or without animation</param>
1245 /// <since_tizen> 8 </since_tizen>
1246 public void ScrollTo(float position, bool animate)
1249 float currentPositionX = ContentContainer.CurrentPosition.X != 0 ? ContentContainer.CurrentPosition.X : ContentContainer.Position.X;
1250 float currentPositionY = ContentContainer.CurrentPosition.Y != 0 ? ContentContainer.CurrentPosition.Y : ContentContainer.Position.Y;
1251 float delta = ScrollingDirection == Direction.Horizontal ? currentPositionX : currentPositionY;
1252 // The argument position is the new pan position. So the new position of ScrollableBase becomes (-position).
1253 // To move ScrollableBase's position to (-position), it moves by (-position - currentPosition).
1254 delta = -position - delta;
1256 ScrollBy(delta, animate);
1259 private float BoundScrollPosition(float targetPosition)
1261 if (ScrollAvailableArea != null)
1263 float minScrollPosition = ScrollAvailableArea.X;
1264 float maxScrollPosition = ScrollAvailableArea.Y;
1266 targetPosition = Math.Min(-minScrollPosition, targetPosition);
1267 targetPosition = Math.Max(-maxScrollPosition, targetPosition);
1271 targetPosition = Math.Min(0, targetPosition);
1272 targetPosition = Math.Max(-maxScrollDistance, targetPosition);
1275 return targetPosition;
1278 private void ScrollBy(float displacement, bool animate)
1280 if (GetChildCount() == 0 || maxScrollDistance < 0)
1285 float childCurrentPosition = (ScrollingDirection == Direction.Horizontal) ? ContentContainer.PositionX : ContentContainer.PositionY;
1287 Debug.WriteLineIf(LayoutDebugScrollableBase, "ScrollBy childCurrentPosition:" + childCurrentPosition +
1288 " displacement:" + displacement,
1289 " maxScrollDistance:" + maxScrollDistance);
1291 childTargetPosition = childCurrentPosition + displacement; // child current position + gesture displacement
1293 Debug.WriteLineIf(LayoutDebugScrollableBase, "ScrollBy currentAxisPosition:" + childCurrentPosition + "childTargetPosition:" + childTargetPosition);
1297 // Calculate scroll animation duration
1298 float scrollDistance = Math.Abs(displacement);
1299 readyToNotice = true;
1301 AnimateChildTo(ScrollDuration, BoundScrollPosition(AdjustTargetPositionOfScrollAnimation(BoundScrollPosition(childTargetPosition))));
1306 finalTargetPosition = BoundScrollPosition(childTargetPosition);
1308 // Set position of scrolling child without an animation
1309 if (ScrollingDirection == Direction.Horizontal)
1311 ContentContainer.PositionX = finalTargetPosition;
1315 ContentContainer.PositionY = finalTargetPosition;
1321 /// you can override it to clean-up your own resources.
1323 /// <param name="type">DisposeTypes</param>
1324 /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API.
1325 [EditorBrowsable(EditorBrowsableState.Never)]
1326 protected override void Dispose(DisposeTypes type)
1333 if (type == DisposeTypes.Explicit)
1335 StopOverShootingShadowAnimation();
1338 if (mPanGestureDetector != null)
1340 mPanGestureDetector.Detected -= OnPanGestureDetected;
1341 mPanGestureDetector.Dispose();
1342 mPanGestureDetector = null;
1345 propertyNotification.Dispose();
1350 private float CalculateMaximumScrollDistance()
1352 float scrollingChildLength = 0;
1353 float scrollerLength = 0;
1354 if (ScrollingDirection == Direction.Horizontal)
1356 Debug.WriteLineIf(LayoutDebugScrollableBase, "Horizontal");
1358 scrollingChildLength = ContentContainer.Size.Width;
1359 scrollerLength = Size.Width;
1363 Debug.WriteLineIf(LayoutDebugScrollableBase, "Vertical");
1364 scrollingChildLength = ContentContainer.Size.Height;
1365 scrollerLength = Size.Height;
1368 Debug.WriteLineIf(LayoutDebugScrollableBase, "ScrollBy maxScrollDistance:" + (scrollingChildLength - scrollerLength) +
1369 " parent length:" + scrollerLength +
1370 " scrolling child length:" + scrollingChildLength);
1372 return Math.Max(scrollingChildLength - scrollerLength, 0);
1375 private void PageSnap(float velocity)
1379 Debug.WriteLineIf(LayoutDebugScrollableBase, "PageSnap with pan candidate totalDisplacement:" + totalDisplacementForPan +
1380 " currentPage[" + CurrentPage + "]");
1382 //Increment current page if total displacement enough to warrant a page change.
1383 if (Math.Abs(totalDisplacementForPan) > (mPageWidth * ratioOfScreenWidthToCompleteScroll))
1385 if (totalDisplacementForPan < 0)
1387 CurrentPage = Math.Min(Math.Max(Children.Count - 1, 0), ++CurrentPage);
1391 CurrentPage = Math.Max(0, --CurrentPage);
1394 else if (Math.Abs(velocity) > PageFlickThreshold)
1398 CurrentPage = Math.Min(Math.Max(Children.Count - 1, 0), ++CurrentPage);
1402 CurrentPage = Math.Max(0, --CurrentPage);
1406 // Animate to new page or reposition to current page
1407 if (ScrollingDirection == Direction.Horizontal)
1408 destination = -(Children[CurrentPage].Position.X + Children[CurrentPage].CurrentSize.Width / 2 - CurrentSize.Width / 2); // set to middle of current page
1410 destination = -(Children[CurrentPage].Position.Y + Children[CurrentPage].CurrentSize.Height / 2 - CurrentSize.Height / 2);
1412 AnimateChildTo(ScrollDuration, destination);
1416 /// Enable/Disable overshooting effect. default is disabled.
1418 [EditorBrowsable(EditorBrowsableState.Never)]
1419 public bool EnableOverShootingEffect
1423 return (bool)GetValue(EnableOverShootingEffectProperty);
1427 SetValue(EnableOverShootingEffectProperty, value);
1428 NotifyPropertyChanged();
1431 private bool InternalEnableOverShootingEffect { get; set; } = false;
1433 private void AttachOverShootingShadowView()
1435 if (!EnableOverShootingEffect)
1438 // stop animation if necessary.
1439 StopOverShootingShadowAnimation();
1441 if (ScrollingDirection == Direction.Horizontal)
1443 base.Add(leftOverShootingShadowView);
1444 base.Add(rightOverShootingShadowView);
1446 leftOverShootingShadowView.Size = new Size(0.0f, SizeHeight);
1447 leftOverShootingShadowView.Opacity = 1.0f;
1448 leftOverShootingShadowView.RaiseToTop();
1450 rightOverShootingShadowView.Size = new Size(0.0f, SizeHeight);
1451 rightOverShootingShadowView.Opacity = 1.0f;
1452 rightOverShootingShadowView.RaiseToTop();
1456 base.Add(topOverShootingShadowView);
1457 base.Add(bottomOverShootingShadowView);
1459 topOverShootingShadowView.Size = new Size(SizeWidth, 0.0f);
1460 topOverShootingShadowView.Opacity = 1.0f;
1461 topOverShootingShadowView.RaiseToTop();
1463 bottomOverShootingShadowView.Size = new Size(SizeWidth, 0.0f);
1464 bottomOverShootingShadowView.Opacity = 1.0f;
1465 bottomOverShootingShadowView.RaiseToTop();
1468 // at the beginning, height or width of overshooting shadow is 0, so it is invisible.
1469 isOverShootingShadowShown = false;
1472 private void DragOverShootingShadow(float totalPanDisplacement, float panDisplacement)
1474 if (!EnableOverShootingEffect)
1477 if (totalPanDisplacement > 0) // downwards
1479 // check if reaching at the top / left.
1480 if ((int)finalTargetPosition != 0)
1482 isOverShootingShadowShown = false;
1486 // save start displacement, and re-calculate displacement.
1487 if (!isOverShootingShadowShown)
1489 startShowShadowDisplacement = totalPanDisplacement;
1491 isOverShootingShadowShown = true;
1493 float newDisplacement = (int)totalPanDisplacement < (int)startShowShadowDisplacement ? 0 : totalPanDisplacement - startShowShadowDisplacement;
1495 if (ScrollingDirection == Direction.Horizontal)
1497 // scale limit of height is 60%.
1498 float heightScale = newDisplacement / overShootingShadowScaleHeightLimit;
1499 leftOverShootingShadowView.SizeHeight = heightScale > 0.6f ? SizeHeight * 0.4f : SizeHeight * (1.0f - heightScale);
1501 // scale limit of width is 300%.
1502 leftOverShootingShadowView.SizeWidth = newDisplacement > overShootingShadowScaleHeightLimit ? overShootingShadowScaleHeightLimit : newDisplacement;
1505 ScrollOutOfBoundEventArgs.Direction scrollDirection = panDisplacement > 0 ?
1506 ScrollOutOfBoundEventArgs.Direction.Right : ScrollOutOfBoundEventArgs.Direction.Left;
1507 OnScrollOutOfBound(scrollDirection, totalPanDisplacement);
1511 // scale limit of width is 60%.
1512 float widthScale = newDisplacement / overShootingShadowScaleHeightLimit;
1513 topOverShootingShadowView.SizeWidth = widthScale > 0.6f ? SizeWidth * 0.4f : SizeWidth * (1.0f - widthScale);
1515 // scale limit of height is 300%.
1516 topOverShootingShadowView.SizeHeight = newDisplacement > overShootingShadowScaleHeightLimit ? overShootingShadowScaleHeightLimit : newDisplacement;
1519 ScrollOutOfBoundEventArgs.Direction scrollDirection = panDisplacement > 0 ?
1520 ScrollOutOfBoundEventArgs.Direction.Down : ScrollOutOfBoundEventArgs.Direction.Up;
1521 OnScrollOutOfBound(scrollDirection, totalPanDisplacement);
1524 else if (totalPanDisplacement < 0) // upwards
1526 // check if reaching at the bottom.
1527 if (-(int)finalTargetPosition != (int)maxScrollDistance)
1529 isOverShootingShadowShown = false;
1533 // save start displacement, and re-calculate displacement.
1534 if (!isOverShootingShadowShown)
1536 startShowShadowDisplacement = totalPanDisplacement;
1538 isOverShootingShadowShown = true;
1540 float newDisplacement = (int)startShowShadowDisplacement < (int)totalPanDisplacement ? 0 : startShowShadowDisplacement - totalPanDisplacement;
1542 if (ScrollingDirection == Direction.Horizontal)
1544 // scale limit of height is 60%.
1545 float heightScale = newDisplacement / overShootingShadowScaleHeightLimit;
1546 rightOverShootingShadowView.SizeHeight = heightScale > 0.6f ? SizeHeight * 0.4f : SizeHeight * (1.0f - heightScale);
1548 // scale limit of width is 300%.
1549 rightOverShootingShadowView.SizeWidth = newDisplacement > overShootingShadowScaleHeightLimit ? overShootingShadowScaleHeightLimit : newDisplacement;
1552 ScrollOutOfBoundEventArgs.Direction scrollDirection = panDisplacement > 0 ?
1553 ScrollOutOfBoundEventArgs.Direction.Right : ScrollOutOfBoundEventArgs.Direction.Left;
1554 OnScrollOutOfBound(scrollDirection, totalPanDisplacement);
1558 // scale limit of width is 60%.
1559 float widthScale = newDisplacement / overShootingShadowScaleHeightLimit;
1560 bottomOverShootingShadowView.SizeWidth = widthScale > 0.6f ? SizeWidth * 0.4f : SizeWidth * (1.0f - widthScale);
1562 // scale limit of height is 300%.
1563 bottomOverShootingShadowView.SizeHeight = newDisplacement > overShootingShadowScaleHeightLimit ? overShootingShadowScaleHeightLimit : newDisplacement;
1566 ScrollOutOfBoundEventArgs.Direction scrollDirection = panDisplacement > 0 ?
1567 ScrollOutOfBoundEventArgs.Direction.Down : ScrollOutOfBoundEventArgs.Direction.Up;
1568 OnScrollOutOfBound(scrollDirection, totalPanDisplacement);
1573 // if total displacement is 0, shadow would become invisible.
1574 isOverShootingShadowShown = false;
1578 private void PlayOverShootingShadowAnimation()
1580 if (!EnableOverShootingEffect)
1583 // stop animation if necessary.
1584 StopOverShootingShadowAnimation();
1586 if (overShootingShadowAnimation == null)
1588 overShootingShadowAnimation = new Animation(overShootingShadowAnimationDuration);
1589 overShootingShadowAnimation.Finished += OnOverShootingShadowAnimationFinished;
1592 if (ScrollingDirection == Direction.Horizontal)
1594 View targetView = totalDisplacementForPan < 0 ? rightOverShootingShadowView : leftOverShootingShadowView;
1595 overShootingShadowAnimation.AnimateTo(targetView, "SizeHeight", SizeHeight);
1596 overShootingShadowAnimation.AnimateTo(targetView, "SizeWidth", 0.0f);
1597 overShootingShadowAnimation.AnimateTo(targetView, "Opacity", 0.0f);
1601 View targetView = totalDisplacementForPan < 0 ? bottomOverShootingShadowView : topOverShootingShadowView;
1602 overShootingShadowAnimation.AnimateTo(targetView, "SizeWidth", SizeWidth);
1603 overShootingShadowAnimation.AnimateTo(targetView, "SizeHeight", 0.0f);
1604 overShootingShadowAnimation.AnimateTo(targetView, "Opacity", 0.0f);
1606 overShootingShadowAnimation.Play();
1609 private void StopOverShootingShadowAnimation()
1611 if (overShootingShadowAnimation == null || overShootingShadowAnimation.State != Animation.States.Playing)
1614 overShootingShadowAnimation.Stop(Animation.EndActions.Cancel);
1615 OnOverShootingShadowAnimationFinished(null, null);
1616 overShootingShadowAnimation.Clear();
1619 private void OnOverShootingShadowAnimationFinished(object sender, EventArgs e)
1621 if (ScrollingDirection == Direction.Horizontal)
1623 base.Remove(leftOverShootingShadowView);
1624 base.Remove(rightOverShootingShadowView);
1626 leftOverShootingShadowView.Size = new Size(0.0f, SizeHeight);
1627 rightOverShootingShadowView.Size = new Size(0.0f, SizeHeight);
1631 base.Remove(topOverShootingShadowView);
1632 base.Remove(bottomOverShootingShadowView);
1634 topOverShootingShadowView.Size = new Size(SizeWidth, 0.0f);
1635 bottomOverShootingShadowView.Size = new Size(SizeWidth, 0.0f);
1638 // after animation finished, height/width & opacity of vertical shadow both are 0, so it is invisible.
1639 isOverShootingShadowShown = false;
1642 private void OnScrollOutOfBound(ScrollOutOfBoundEventArgs.Direction direction, float displacement)
1644 ScrollOutOfBoundEventArgs args = new ScrollOutOfBoundEventArgs(direction, displacement);
1645 ScrollOutOfBound?.Invoke(this, args);
1648 private void OnPanGestureDetected(object source, PanGestureDetector.DetectedEventArgs e)
1650 e.Handled = OnPanGesture(e.PanGesture);
1653 private bool OnPanGesture(PanGesture panGesture)
1655 bool handled = true;
1656 if (SnapToPage && scrollAnimation != null && scrollAnimation.State == Animation.States.Playing)
1660 if (panGesture.State == Gesture.StateType.Started)
1662 readyToNotice = false;
1663 AttachOverShootingShadowView();
1664 Debug.WriteLineIf(LayoutDebugScrollableBase, "Gesture Start");
1665 if (scrolling && !SnapToPage)
1669 totalDisplacementForPan = 0.0f;
1671 // check if gesture need to propagation
1672 var checkDisplacement = (ScrollingDirection == Direction.Horizontal) ? panGesture.Displacement.X : panGesture.Displacement.Y;
1673 var checkChildCurrentPosition = (ScrollingDirection == Direction.Horizontal) ? ContentContainer.PositionX : ContentContainer.PositionY;
1674 var checkChildTargetPosition = checkChildCurrentPosition + checkDisplacement;
1675 var checkFinalTargetPosition = BoundScrollPosition(checkChildTargetPosition);
1676 handled = !((int)checkFinalTargetPosition == 0 || -(int)checkFinalTargetPosition == (int)maxScrollDistance);
1677 // If you propagate a gesture event, return;
1683 //Interrupt touching when panning is started
1684 this.InterceptTouchEvent += OnInterruptTouchingChildTouched;
1685 OnScrollDragStarted();
1687 else if (panGesture.State == Gesture.StateType.Continuing)
1689 if (ScrollingDirection == Direction.Horizontal)
1691 // if vertical shadow is shown, does not scroll.
1692 if (!isOverShootingShadowShown)
1694 ScrollBy(panGesture.Displacement.X, false);
1696 totalDisplacementForPan += panGesture.Displacement.X;
1697 DragOverShootingShadow(totalDisplacementForPan, panGesture.Displacement.X);
1701 // if vertical shadow is shown, does not scroll.
1702 if (!isOverShootingShadowShown)
1704 ScrollBy(panGesture.Displacement.Y, false);
1706 totalDisplacementForPan += panGesture.Displacement.Y;
1707 DragOverShootingShadow(totalDisplacementForPan, panGesture.Displacement.Y);
1709 Debug.WriteLineIf(LayoutDebugScrollableBase, "OnPanGestureDetected Continue totalDisplacementForPan:" + totalDisplacementForPan);
1712 else if (panGesture.State == Gesture.StateType.Finished || panGesture.State == Gesture.StateType.Cancelled)
1714 PlayOverShootingShadowAnimation();
1715 OnScrollDragEnded();
1716 StopScroll(); // Will replace previous animation so will stop existing one.
1718 if (scrollAnimation == null)
1720 scrollAnimation = new Animation();
1721 scrollAnimation.Finished += ScrollAnimationFinished;
1724 float panVelocity = (ScrollingDirection == Direction.Horizontal) ? panGesture.Velocity.X : panGesture.Velocity.Y;
1728 PageSnap(panVelocity);
1732 if (panVelocity == 0)
1734 float currentScrollPosition = (ScrollingDirection == Direction.Horizontal ? ContentContainer.CurrentPosition.X : ContentContainer.CurrentPosition.Y);
1735 scrollAnimation.DefaultAlphaFunction = new AlphaFunction(AlphaFunction.BuiltinFunctions.Linear);
1736 scrollAnimation.Duration = 0;
1737 scrollAnimation.AnimateTo(ContentContainer, (ScrollingDirection == Direction.Horizontal) ? "PositionX" : "PositionY", currentScrollPosition);
1738 scrollAnimation.Play();
1742 Decelerating(panVelocity, scrollAnimation);
1746 totalDisplacementForPan = 0;
1748 readyToNotice = true;
1749 OnScrollAnimationStarted();
1754 internal void BaseRemove(View view)
1759 internal override bool OnAccessibilityPan(PanGesture gestures)
1761 if (SnapToPage && scrollAnimation != null && scrollAnimation.State == Animation.States.Playing)
1766 OnPanGesture(gestures);
1770 private float CustomScrollAlphaFunction(float progress)
1772 if (panAnimationDelta == 0)
1778 // Parameter "progress" is normalized value. We need to multiply target duration to calculate distance.
1779 // Can get real distance using equation of deceleration (check Decelerating function)
1780 // After get real distance, normalize it
1781 float realDuration = progress * panAnimationDuration;
1782 float realDistance = velocityOfLastPan * ((float)Math.Pow(decelerationRate, realDuration) - 1) / logValueOfDeceleration;
1783 float result = Math.Min(realDistance / Math.Abs(panAnimationDelta), 1.0f);
1785 // This is hot-fix for if the velocity has very small value, result is not updated even progress done.
1786 if (progress > 0.99) result = 1.0f;
1793 /// you can override it to custom your decelerating
1795 /// <param name="velocity">Velocity of current pan.</param>
1796 /// <param name="animation">Scroll animation.</param>
1797 [EditorBrowsable(EditorBrowsableState.Never)]
1798 protected virtual void Decelerating(float velocity, Animation animation)
1800 if (animation == null) throw new ArgumentNullException(nameof(animation));
1801 // Decelerating using deceleration equation ===========
1803 // V : velocity (pixel per millisecond)
1804 // V0 : initial velocity
1805 // d : deceleration rate,
1807 // X : final position after decelerating
1808 // log : natural logarithm
1810 // V(t) = V0 * d pow t;
1811 // X(t) = V0 * (d pow t - 1) / log d; <-- Integrate the velocity function
1812 // X(∞) = V0 * d / (1 - d); <-- Result using infinite T can be final position because T is tending to infinity.
1814 // Because of final T is tending to infinity, we should use threshold value to finish.
1815 // Final T = log(-threshold * log d / |V0| ) / log d;
1817 velocityOfLastPan = Math.Abs(velocity);
1819 float currentScrollPosition = -(ScrollingDirection == Direction.Horizontal ? ContentContainer.CurrentPosition.X : ContentContainer.CurrentPosition.Y);
1820 panAnimationDelta = (velocityOfLastPan * decelerationRate) / (1 - decelerationRate);
1821 panAnimationDelta = velocity > 0 ? -panAnimationDelta : panAnimationDelta;
1823 float destination = -(panAnimationDelta + currentScrollPosition);
1824 float adjustDestination = AdjustTargetPositionOfScrollAnimation(destination);
1825 float maxPosition = ScrollAvailableArea != null ? ScrollAvailableArea.Y : maxScrollDistance;
1826 float minPosition = ScrollAvailableArea != null ? ScrollAvailableArea.X : 0;
1828 if (destination < -maxPosition || destination > minPosition)
1830 panAnimationDelta = velocity > 0 ? (currentScrollPosition - minPosition) : (maxPosition - currentScrollPosition);
1831 destination = velocity > 0 ? minPosition : -maxPosition;
1833 if (panAnimationDelta == 0)
1835 panAnimationDuration = 0.0f;
1839 panAnimationDuration = (float)Math.Log((panAnimationDelta * logValueOfDeceleration / velocityOfLastPan + 1), decelerationRate);
1842 Debug.WriteLineIf(LayoutDebugScrollableBase, "\n" +
1843 "OverRange======================= \n" +
1844 "[decelerationRate] " + decelerationRate + "\n" +
1845 "[logValueOfDeceleration] " + logValueOfDeceleration + "\n" +
1846 "[Velocity] " + velocityOfLastPan + "\n" +
1847 "[CurrentPosition] " + currentScrollPosition + "\n" +
1848 "[CandidateDelta] " + panAnimationDelta + "\n" +
1849 "[Destination] " + destination + "\n" +
1850 "[Duration] " + panAnimationDuration + "\n" +
1851 "================================ \n"
1856 panAnimationDuration = (float)Math.Log(-DecelerationThreshold * logValueOfDeceleration / velocityOfLastPan) / logValueOfDeceleration;
1858 if (adjustDestination != destination)
1860 destination = adjustDestination;
1861 panAnimationDelta = destination + currentScrollPosition;
1862 velocityOfLastPan = Math.Abs(panAnimationDelta * logValueOfDeceleration / ((float)Math.Pow(decelerationRate, panAnimationDuration) - 1));
1863 panAnimationDuration = (float)Math.Log(-DecelerationThreshold * logValueOfDeceleration / velocityOfLastPan) / logValueOfDeceleration;
1866 Debug.WriteLineIf(LayoutDebugScrollableBase, "\n" +
1867 "================================ \n" +
1868 "[decelerationRate] " + decelerationRate + "\n" +
1869 "[logValueOfDeceleration] " + logValueOfDeceleration + "\n" +
1870 "[Velocity] " + velocityOfLastPan + "\n" +
1871 "[CurrentPosition] " + currentScrollPosition + "\n" +
1872 "[CandidateDelta] " + panAnimationDelta + "\n" +
1873 "[Destination] " + destination + "\n" +
1874 "[Duration] " + panAnimationDuration + "\n" +
1875 "================================ \n"
1879 finalTargetPosition = destination;
1881 customScrollAlphaFunction = new UserAlphaFunctionDelegate(CustomScrollAlphaFunction);
1882 animation.DefaultAlphaFunction = new AlphaFunction(customScrollAlphaFunction);
1883 GC.KeepAlive(customScrollAlphaFunction);
1884 animation.Duration = (int)panAnimationDuration;
1885 animation.AnimateTo(ContentContainer, (ScrollingDirection == Direction.Horizontal) ? "PositionX" : "PositionY", destination);
1889 private void ScrollAnimationFinished(object sender, EventArgs e)
1891 OnScrollAnimationEnded();
1895 /// Adjust scrolling position by own scrolling rules.
1896 /// Override this function when developer wants to change destination of flicking.(e.g. always snap to center of item)
1898 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
1899 [EditorBrowsable(EditorBrowsableState.Never)]
1900 protected virtual float AdjustTargetPositionOfScrollAnimation(float position)
1906 /// Scroll position given to ScrollTo.
1907 /// This is the position in the opposite direction to the position of ContentContainer.
1909 /// <since_tizen> 8 </since_tizen>
1910 public Position ScrollPosition
1914 return new Position(-ContentContainer.Position);
1919 /// Current scroll position in the middle of ScrollTo animation.
1920 /// This is the position in the opposite direction to the current position of ContentContainer.
1922 /// <since_tizen> 8 </since_tizen>
1923 public Position ScrollCurrentPosition
1927 return new Position(-ContentContainer.CurrentPosition);
1932 /// Remove all children in ContentContainer.
1934 /// <param name="dispose">If true, removed child is disposed.</param>
1935 [EditorBrowsable(EditorBrowsableState.Never)]
1936 public void RemoveAllChildren(bool dispose = false)
1938 RecursiveRemoveChildren(ContentContainer, dispose);
1941 private void RecursiveRemoveChildren(View parent, bool dispose)
1947 int maxChild = (int)parent.GetChildCount();
1948 for (int i = maxChild - 1; i >= 0; --i)
1950 View child = parent.GetChildAt((uint)i);
1955 RecursiveRemoveChildren(child, dispose);
1956 parent.Remove(child);
1964 internal bool IsChildNearlyVisble(View child, float offset = 0)
1966 if (ScreenPosition.X - offset < child.ScreenPosition.X + child.SizeWidth &&
1967 ScreenPosition.X + SizeWidth + offset > child.ScreenPosition.X &&
1968 ScreenPosition.Y - offset < child.ScreenPosition.Y + child.SizeHeight &&
1969 ScreenPosition.Y + SizeHeight + offset > child.ScreenPosition.Y)
1980 [EditorBrowsable(EditorBrowsableState.Never)]
1981 public override View GetNextFocusableView(View currentFocusedView, View.FocusDirection direction, bool loopEnabled)
1983 bool isHorizontal = (ScrollingDirection == Direction.Horizontal);
1984 float targetPosition = -(ScrollingDirection == Direction.Horizontal ? ContentContainer.CurrentPosition.X : ContentContainer.CurrentPosition.Y);
1985 float stepDistance = (stepScrollDistance != 0? stepScrollDistance : (isHorizontal ? Size.Width * 0.25f : Size.Height * 0.25f));
1987 bool forward = ((isHorizontal && direction == View.FocusDirection.Right) ||
1988 (!isHorizontal && direction == View.FocusDirection.Down) ||
1989 (direction == View.FocusDirection.Clockwise));
1990 bool backward = ((isHorizontal && direction == View.FocusDirection.Left) ||
1991 (!isHorizontal && direction == View.FocusDirection.Up) ||
1992 (direction == View.FocusDirection.CounterClockwise));
1994 View nextFocusedView = FocusManager.Instance.GetNearestFocusableActor(this, currentFocusedView, direction);
1996 // Move out focus from ScrollableBase.
1997 // FIXME: Forward, Backward is unimplemented other components.
1998 if (direction == View.FocusDirection.Forward ||
1999 direction == View.FocusDirection.Backward ||
2000 (nextFocusedView == null &&
2001 ((forward && maxScrollDistance - targetPosition < 0.1f) ||
2002 (backward && targetPosition < 0.1f))))
2004 var next = FocusManager.Instance.GetNearestFocusableActor(this.Parent, this, direction);
2005 Debug.WriteLineIf(focusDebugScrollableBase, $"Focus move [{direction}] out from ScrollableBase! Next focus target {next}:{next?.ID}");
2009 if (focusDebugScrollableBase)
2011 global::System.Text.StringBuilder debugMessage = new global::System.Text.StringBuilder("=========================================================\n");
2012 debugMessage.Append($"GetNextFocusableView On: {this}:{this.ID}\n");
2013 debugMessage.Append($"----------------Current: {currentFocusedView}:{currentFocusedView?.ID}\n");
2014 debugMessage.Append($"-------------------Next: {nextFocusedView}:{nextFocusedView?.ID}\n");
2015 debugMessage.Append($"--------------Direction: {direction}\n");
2016 debugMessage.Append("=========================================================");
2017 Debug.WriteLineIf(focusDebugScrollableBase, debugMessage);
2020 if (nextFocusedView != null)
2022 if (null != FindDescendantByID(nextFocusedView.ID))
2024 if (IsChildNearlyVisble(nextFocusedView, stepDistance) == true)
2026 ScrollToChild(nextFocusedView, true);
2027 return nextFocusedView;
2032 if (forward || backward)
2034 // Fallback to current focus or scrollableBase till next focus visible in scrollable.
2035 if (null != currentFocusedView && null != FindDescendantByID(currentFocusedView.ID))
2037 nextFocusedView = currentFocusedView;
2041 Debug.WriteLineIf(focusDebugScrollableBase, "current focus view is not decendant. return ScrollableBase!");
2047 targetPosition += stepDistance;
2048 targetPosition = targetPosition > maxScrollDistance ? maxScrollDistance : targetPosition;
2053 targetPosition -= stepDistance;
2054 targetPosition = targetPosition < 0 ? 0 : targetPosition;
2057 ScrollTo(targetPosition, true);
2059 Debug.WriteLineIf(focusDebugScrollableBase, $"ScrollTo :({targetPosition})");
2062 Debug.WriteLineIf(focusDebugScrollableBase, $"return end : {nextFocusedView}:{nextFocusedView?.ID}");
2063 return nextFocusedView;
2067 [EditorBrowsable(EditorBrowsableState.Never)]
2068 protected override bool AccessibilityScrollToChild(View child)
2075 if (ScrollingDirection == Direction.Horizontal)
2077 if (child.ScreenPosition.X + child.Size.Width <= this.ScreenPosition.X)
2081 PageSnap(PageFlickThreshold + 1);
2085 ScrollTo((float)(child.ScreenPosition.X - ContentContainer.ScreenPosition.X), false);
2088 else if (child.ScreenPosition.X >= this.ScreenPosition.X + this.Size.Width)
2092 PageSnap(-(PageFlickThreshold + 1));
2096 ScrollTo((float)(child.ScreenPosition.X + child.Size.Width - ContentContainer.ScreenPosition.X - this.Size.Width), false);
2102 if (child.ScreenPosition.Y + child.Size.Height <= this.ScreenPosition.Y)
2106 PageSnap(PageFlickThreshold + 1);
2110 ScrollTo((float)(child.ScreenPosition.Y - ContentContainer.ScreenPosition.Y), false);
2113 else if (child.ScreenPosition.Y >= this.ScreenPosition.Y + this.Size.Height)
2117 PageSnap(-(PageFlickThreshold + 1));
2121 ScrollTo((float)(child.ScreenPosition.Y + child.Size.Height - ContentContainer.ScreenPosition.Y - this.Size.Height), false);