1 /* Copyright (c) 2020 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 public class ScrollEventArgs : EventArgs
32 private Position position;
35 /// Default constructor.
37 /// <param name="position">Current scroll position</param>
38 /// <since_tizen> 8 </since_tizen>
39 public ScrollEventArgs(Position position)
41 this.position = position;
45 /// Current position of ContentContainer.
47 /// <since_tizen> 8 </since_tizen>
48 public Position Position
58 /// This class provides a View that can scroll a single View with a layout. This View can be a nest of Views.
60 /// <since_tizen> 8 </since_tizen>
61 public class ScrollableBase : Control
63 static bool LayoutDebugScrollableBase = false; // Debug flag
64 private Direction mScrollingDirection = Direction.Vertical;
65 private bool mScrollEnabled = true;
66 private int mScrollDuration = 125;
67 private int mPageWidth = 0;
68 private float mPageFlickThreshold = 0.4f;
70 private class ScrollableBaseCustomLayout : LayoutGroup
72 protected override void OnMeasure(MeasureSpecification widthMeasureSpec, MeasureSpecification heightMeasureSpec)
74 Extents padding = Padding;
75 float totalHeight = padding.Top + padding.Bottom;
76 float totalWidth = padding.Start + padding.End;
78 MeasuredSize.StateType childWidthState = MeasuredSize.StateType.MeasuredSizeOK;
79 MeasuredSize.StateType childHeightState = MeasuredSize.StateType.MeasuredSizeOK;
81 Direction scrollingDirection = Direction.Vertical;
82 ScrollableBase scrollableBase = this.Owner as ScrollableBase;
85 scrollingDirection = scrollableBase.ScrollingDirection;
88 // measure child, should be a single scrolling child
89 foreach (LayoutItem childLayout in LayoutChildren)
91 if (childLayout != null)
94 // Use an Unspecified MeasureSpecification mode so scrolling child is not restricted to it's parents size in Height (for vertical scrolling)
95 // or Width for horizontal scrolling
96 MeasureSpecification unrestrictedMeasureSpec = new MeasureSpecification(heightMeasureSpec.Size, MeasureSpecification.ModeType.Unspecified);
98 if (scrollingDirection == Direction.Vertical)
100 MeasureChildWithMargins(childLayout, widthMeasureSpec, new LayoutLength(0), unrestrictedMeasureSpec, new LayoutLength(0)); // Height unrestricted by parent
104 MeasureChildWithMargins(childLayout, unrestrictedMeasureSpec, new LayoutLength(0), heightMeasureSpec, new LayoutLength(0)); // Width unrestricted by parent
107 float childWidth = childLayout.MeasuredWidth.Size.AsDecimal();
108 float childHeight = childLayout.MeasuredHeight.Size.AsDecimal();
110 // Determine the width and height needed by the children using their given position and size.
111 // Children could overlap so find the left most and right most child.
112 Position2D childPosition = childLayout.Owner.Position2D;
113 float childLeft = childPosition.X;
114 float childTop = childPosition.Y;
116 // Store current width and height needed to contain all children.
117 Extents childMargin = childLayout.Margin;
118 totalWidth = childWidth + childMargin.Start + childMargin.End;
119 totalHeight = childHeight + childMargin.Top + childMargin.Bottom;
121 if (childLayout.MeasuredWidth.State == MeasuredSize.StateType.MeasuredSizeTooSmall)
123 childWidthState = MeasuredSize.StateType.MeasuredSizeTooSmall;
125 if (childLayout.MeasuredHeight.State == MeasuredSize.StateType.MeasuredSizeTooSmall)
127 childHeightState = MeasuredSize.StateType.MeasuredSizeTooSmall;
133 MeasuredSize widthSizeAndState = ResolveSizeAndState(new LayoutLength(totalWidth + Padding.Start + Padding.End), widthMeasureSpec, MeasuredSize.StateType.MeasuredSizeOK);
134 MeasuredSize heightSizeAndState = ResolveSizeAndState(new LayoutLength(totalHeight + Padding.Top + Padding.Bottom), heightMeasureSpec, MeasuredSize.StateType.MeasuredSizeOK);
135 totalWidth = widthSizeAndState.Size.AsDecimal();
136 totalHeight = heightSizeAndState.Size.AsDecimal();
138 // Ensure layout respects it's given minimum size
139 totalWidth = Math.Max(totalWidth, SuggestedMinimumWidth.AsDecimal());
140 totalHeight = Math.Max(totalHeight, SuggestedMinimumHeight.AsDecimal());
142 widthSizeAndState.State = childWidthState;
143 heightSizeAndState.State = childHeightState;
145 SetMeasuredDimensions(ResolveSizeAndState(new LayoutLength(totalWidth + Padding.Start + Padding.End), widthMeasureSpec, childWidthState),
146 ResolveSizeAndState(new LayoutLength(totalHeight + Padding.Top + Padding.Bottom), heightMeasureSpec, childHeightState));
148 // Size of ScrollableBase is changed. Change Page width too.
149 scrollableBase.mPageWidth = (int)MeasuredWidth.Size.AsRoundedValue();
152 protected override void OnLayout(bool changed, LayoutLength left, LayoutLength top, LayoutLength right, LayoutLength bottom)
154 foreach (LayoutItem childLayout in LayoutChildren)
156 if (childLayout != null)
158 LayoutLength childWidth = childLayout.MeasuredWidth.Size;
159 LayoutLength childHeight = childLayout.MeasuredHeight.Size;
161 Position2D childPosition = childLayout.Owner.Position2D;
162 Extents padding = Padding;
163 Extents childMargin = childLayout.Margin;
165 LayoutLength childLeft = new LayoutLength(childPosition.X + childMargin.Start + padding.Start);
166 LayoutLength childTop = new LayoutLength(childPosition.Y + childMargin.Top + padding.Top);
168 childLayout.Layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight);
172 } // ScrollableBaseCustomLayout
175 /// The direction axis to scroll.
177 /// <since_tizen> 8 </since_tizen>
178 public enum Direction
183 /// <since_tizen> 8 </since_tizen>
189 /// <since_tizen> 8 </since_tizen>
194 /// Scrolling direction mode.
195 /// Default is Vertical scrolling.
197 /// <since_tizen> 8 </since_tizen>
198 public Direction ScrollingDirection
202 return mScrollingDirection;
206 if (value != mScrollingDirection)
208 mScrollingDirection = value;
209 mPanGestureDetector.RemoveDirection(value == Direction.Horizontal ?
210 PanGestureDetector.DirectionVertical : PanGestureDetector.DirectionHorizontal);
211 mPanGestureDetector.AddDirection(value == Direction.Horizontal ?
212 PanGestureDetector.DirectionHorizontal : PanGestureDetector.DirectionVertical);
214 ContentContainer.WidthSpecification = mScrollingDirection == Direction.Vertical ?
215 LayoutParamPolicies.MatchParent : LayoutParamPolicies.WrapContent;
216 ContentContainer.HeightSpecification = mScrollingDirection == Direction.Vertical ?
217 LayoutParamPolicies.WrapContent : LayoutParamPolicies.MatchParent;
223 /// Enable or disable scrolling.
225 /// <since_tizen> 8 </since_tizen>
226 public bool ScrollEnabled
230 return mScrollEnabled;
234 if (value != mScrollEnabled)
236 mScrollEnabled = value;
239 mPanGestureDetector.Detected += OnPanGestureDetected;
243 mPanGestureDetector.Detected -= OnPanGestureDetected;
250 /// Pages mode, enables moving to the next or return to current page depending on pan displacement.
251 /// Default is false.
253 /// <since_tizen> 8 </since_tizen>
254 public bool SnapToPage { set; get; } = false;
257 /// Get current page.
258 /// Working property with SnapToPage property.
260 /// <since_tizen> 8 </since_tizen>
261 public int CurrentPage { get; private set; } = 0;
264 /// Duration of scroll animation.
265 /// Default value is 125ms.
267 /// <since_tizen> 8 </since_tizen>
268 public int ScrollDuration
272 mScrollDuration = value >= 0 ? value : mScrollDuration;
276 return mScrollDuration;
281 /// Scroll Available area.
283 /// <since_tizen> 8 </since_tizen>
284 public Vector2 ScrollAvailableArea { set; get; }
287 /// An event emitted when user starts dragging ScrollableBase, user can subscribe or unsubscribe to this event handler.<br />
289 /// <since_tizen> 8 </since_tizen>
290 public event EventHandler<ScrollEventArgs> ScrollDragStarted;
293 /// An event emitted when user stops dragging ScrollableBase, user can subscribe or unsubscribe to this event handler.<br />
295 /// <since_tizen> 8 </since_tizen>
296 public event EventHandler<ScrollEventArgs> ScrollDragEnded;
300 /// An event emitted when the scrolling slide animation starts, user can subscribe or unsubscribe to this event handler.<br />
302 /// <since_tizen> 8 </since_tizen>
303 public event EventHandler<ScrollEventArgs> ScrollAnimationStarted;
306 /// An event emitted when the scrolling slide animation ends, user can subscribe or unsubscribe to this event handler.<br />
308 /// <since_tizen> 8 </since_tizen>
309 public event EventHandler<ScrollEventArgs> ScrollAnimationEnded;
313 /// An event emitted when scrolling, user can subscribe or unsubscribe to this event handler.<br />
315 /// <since_tizen> 8 </since_tizen>
316 public event EventHandler<ScrollEventArgs> Scrolling;
320 /// Scrollbar for ScrollableBase.
322 /// <since_tizen> 8 </since_tizen>
323 public ScrollbarBase Scrollbar
333 scrollBar.Unparent();
337 scrollBar.Name = "ScrollBar";
354 /// Always hide Scrollbar.
356 /// <since_tizen> 8 </since_tizen>
357 public bool HideScrollbar
361 return hideScrollbar;
365 hideScrollbar = value;
382 /// Container which has content of ScrollableBase.
384 /// <since_tizen> 8 </since_tizen>
385 public View ContentContainer { get; private set; }
388 /// Set the layout on this View. Replaces any existing Layout.
390 /// <since_tizen> 8 </since_tizen>
391 public new LayoutItem Layout
395 return ContentContainer.Layout;
399 ContentContainer.Layout = value;
400 if (ContentContainer.Layout != null)
402 ContentContainer.Layout.SetPositionByLayout = false;
408 /// List of children of Container.
410 /// <since_tizen> 8 </since_tizen>
411 public new List<View> Children
415 return ContentContainer.Children;
420 /// Deceleration rate of scrolling by finger.
421 /// Rate should be bigger than 0 and smaller than 1.
422 /// Default value is 0.998f;
424 /// <since_tizen> 8 </since_tizen>
425 public float DecelerationRate
429 return decelerationRate;
433 decelerationRate = (value < 1 && value > 0) ? value : decelerationRate;
434 logValueOfDeceleration = (float)Math.Log(value);
439 /// Threashold not to go infinit at the end of scrolling animation.
441 [EditorBrowsable(EditorBrowsableState.Never)]
442 public float DecelerationThreshold { get; set; } = 0.1f;
445 /// Page will be changed when velocity of panning is over threshold.
446 /// The unit of threshold is pixel per milisec.
448 /// <since_tizen> 8 </since_tizen>
449 public float PageFlickThreshold
453 return mPageFlickThreshold;
457 mPageFlickThreshold = value >= 0f ? value : mPageFlickThreshold;
462 /// Alphafunction for scroll animation.
464 [EditorBrowsable(EditorBrowsableState.Never)]
465 public AlphaFunction ScrollAlphaFunction { get; set; } = new AlphaFunction(AlphaFunction.BuiltinFunctions.Linear);
467 private bool hideScrollbar = true;
468 private float maxScrollDistance;
469 private float childTargetPosition = 0.0f;
470 private PanGestureDetector mPanGestureDetector;
471 private View mInterruptTouchingChild;
472 private ScrollbarBase scrollBar;
473 private bool scrolling = false;
474 private float ratioOfScreenWidthToCompleteScroll = 0.5f;
475 private float totalDisplacementForPan = 0.0f;
476 private Size previousContainerSize = new Size();
477 private PropertyNotification propertyNotification;
478 private float noticeAnimationEndBeforePosition = 0.0f;
479 private bool readyToNotice = false;
482 /// Notice before animation is finished.
484 [EditorBrowsable(EditorBrowsableState.Never)]
485 // Let's consider more whether this needs to be set as protected.
486 public float NoticeAnimationEndBeforePosition { get => noticeAnimationEndBeforePosition; set => noticeAnimationEndBeforePosition = value; }
488 // Let's consider more whether this needs to be set as protected.
489 private float finalTargetPosition;
491 private Animation scrollAnimation;
492 // Declare user alpha function delegate
493 [UnmanagedFunctionPointer(CallingConvention.StdCall)]
494 private delegate float UserAlphaFunctionDelegate(float progress);
495 private UserAlphaFunctionDelegate customScrollAlphaFunction;
496 private float velocityOfLastPan = 0.0f;
497 private float panAnimationDuration = 0.0f;
498 private float panAnimationDelta = 0.0f;
499 private float logValueOfDeceleration = 0.0f;
500 private float decelerationRate = 0.0f;
503 /// Default Constructor
505 /// <since_tizen> 8 </since_tizen>
506 public ScrollableBase() : base()
508 DecelerationRate = 0.998f;
510 base.Layout = new ScrollableBaseCustomLayout();
511 mPanGestureDetector = new PanGestureDetector();
512 mPanGestureDetector.Attach(this);
513 mPanGestureDetector.AddDirection(PanGestureDetector.DirectionVertical);
514 mPanGestureDetector.Detected += OnPanGestureDetected;
516 ClippingMode = ClippingModeType.ClipChildren;
518 //Default Scrolling child
519 ContentContainer = new View()
521 WidthSpecification = ScrollingDirection == Direction.Vertical ? LayoutParamPolicies.MatchParent : LayoutParamPolicies.WrapContent,
522 HeightSpecification = ScrollingDirection == Direction.Vertical ? LayoutParamPolicies.WrapContent : LayoutParamPolicies.MatchParent,
523 Layout = new AbsoluteLayout() { SetPositionByLayout = false },
525 ContentContainer.Relayout += OnScrollingChildRelayout;
526 propertyNotification = ContentContainer.AddPropertyNotification("position", PropertyCondition.Step(1.0f));
527 propertyNotification.Notified += OnPropertyChanged;
528 base.Add(ContentContainer);
530 //Interrupt touching when panning is started
531 mInterruptTouchingChild = new View()
533 Size = new Size(Window.Instance.WindowSize),
534 BackgroundColor = Color.Transparent,
536 mInterruptTouchingChild.TouchEvent += OnIterruptTouchingChildTouched;
537 Scrollbar = new Scrollbar();
539 AccessibilityManager.Instance.SetAccessibilityAttribute(this, AccessibilityManager.AccessibilityAttribute.Trait, "ScrollableBase");
542 private bool OnIterruptTouchingChildTouched(object source, View.TouchEventArgs args)
544 if (args.Touch.GetState(0) == PointStateType.Down)
546 if (scrolling && !SnapToPage)
554 private void OnPropertyChanged(object source, PropertyNotification.NotifyEventArgs args)
560 /// Called after a child has been added to the owning view.
562 /// <param name="view">The child which has been added.</param>
563 /// <since_tizen> 8 </since_tizen>
564 public override void Add(View view)
566 ContentContainer.Add(view);
570 /// Called after a child has been removed from the owning view.
572 /// <param name="view">The child which has been removed.</param>
573 /// <since_tizen> 8 </since_tizen>
574 public override void Remove(View view)
576 if (SnapToPage && CurrentPage == Children.IndexOf(view) && CurrentPage == Children.Count - 1)
578 // Target View is current page and also last child.
579 // CurrentPage should be changed to previous page.
580 CurrentPage = Math.Max(0, CurrentPage - 1);
581 ScrollToIndex(CurrentPage);
584 ContentContainer.Remove(view);
587 private void OnScrollingChildRelayout(object source, EventArgs args)
589 // Size is changed. Calculate maxScrollDistance.
590 bool isSizeChanged = previousContainerSize.Width != ContentContainer.Size.Width || previousContainerSize.Height != ContentContainer.Size.Height;
594 maxScrollDistance = CalculateMaximumScrollDistance();
598 previousContainerSize = ContentContainer.Size;
602 /// The composition of a Scrollbar can vary depending on how you use ScrollableBase.
603 /// Set the composition that will go into the ScrollableBase according to your ScrollableBase.
605 /// <since_tizen> 8 </since_tizen>
606 [EditorBrowsable(EditorBrowsableState.Never)]
607 protected virtual void SetScrollbar()
611 bool isHorizontal = ScrollingDirection == Direction.Horizontal;
612 float contentLength = isHorizontal ? ContentContainer.Size.Width : ContentContainer.Size.Height;
613 float viewportLength = isHorizontal ? Size.Width : Size.Height;
614 float currentPosition = isHorizontal ? ContentContainer.CurrentPosition.X : ContentContainer.CurrentPosition.Y;
615 Scrollbar.Initialize(contentLength, viewportLength, currentPosition, isHorizontal);
620 /// Scrolls to the item at the specified index.
622 /// <param name="index">Index of item.</param>
623 /// <since_tizen> 8 </since_tizen>
624 public void ScrollToIndex(int index)
626 if (ContentContainer.ChildCount - 1 < index || index < 0)
636 float targetPosition = Math.Min(ScrollingDirection == Direction.Vertical ? Children[index].Position.Y : Children[index].Position.X, maxScrollDistance);
637 AnimateChildTo(ScrollDuration, -targetPosition);
640 private void OnScrollDragStarted()
642 ScrollEventArgs eventArgs = new ScrollEventArgs(ContentContainer.CurrentPosition);
643 ScrollDragStarted?.Invoke(this, eventArgs);
646 private void OnScrollDragEnded()
648 ScrollEventArgs eventArgs = new ScrollEventArgs(ContentContainer.CurrentPosition);
649 ScrollDragEnded?.Invoke(this, eventArgs);
652 private void OnScrollAnimationStarted()
654 ScrollEventArgs eventArgs = new ScrollEventArgs(ContentContainer.CurrentPosition);
655 ScrollAnimationStarted?.Invoke(this, eventArgs);
658 private void OnScrollAnimationEnded()
661 base.Remove(mInterruptTouchingChild);
663 ScrollEventArgs eventArgs = new ScrollEventArgs(ContentContainer.CurrentPosition);
664 ScrollAnimationEnded?.Invoke(this, eventArgs);
667 private void OnScroll()
669 ScrollEventArgs eventArgs = new ScrollEventArgs(ContentContainer.CurrentPosition);
670 Scrolling?.Invoke(this, eventArgs);
672 bool isHorizontal = ScrollingDirection == Direction.Horizontal;
673 float contentLength = isHorizontal ? ContentContainer.Size.Width : ContentContainer.Size.Height;
674 float currentPosition = isHorizontal ? ContentContainer.CurrentPosition.X : ContentContainer.CurrentPosition.Y;
676 scrollBar.Update(contentLength, Math.Abs(currentPosition));
677 CheckPreReachedTargetPosition();
680 private void CheckPreReachedTargetPosition()
682 // Check whether we reached pre-reached target position
684 ContentContainer.CurrentPosition.Y <= finalTargetPosition + NoticeAnimationEndBeforePosition &&
685 ContentContainer.CurrentPosition.Y >= finalTargetPosition - NoticeAnimationEndBeforePosition)
688 readyToNotice = false;
689 OnPreReachedTargetPosition(finalTargetPosition);
694 /// This helps developer who wants to know before scroll is reaching target position.
696 /// <param name="targetPosition">Index of item.</param>
697 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
698 [EditorBrowsable(EditorBrowsableState.Never)]
699 protected virtual void OnPreReachedTargetPosition(float targetPosition)
704 private void StopScroll()
706 if (scrollAnimation != null)
708 if (scrollAnimation.State == Animation.States.Playing)
710 Debug.WriteLineIf(LayoutDebugScrollableBase, "StopScroll Animation Playing");
711 scrollAnimation.Stop(Animation.EndActions.Cancel);
712 OnScrollAnimationEnded();
714 scrollAnimation.Clear();
718 private void AnimateChildTo(int duration, float axisPosition)
720 Debug.WriteLineIf(LayoutDebugScrollableBase, "AnimationTo Animation Duration:" + duration + " Destination:" + axisPosition);
721 finalTargetPosition = axisPosition;
723 StopScroll(); // Will replace previous animation so will stop existing one.
725 if (scrollAnimation == null)
727 scrollAnimation = new Animation();
728 scrollAnimation.Finished += ScrollAnimationFinished;
731 scrollAnimation.Duration = duration;
732 scrollAnimation.DefaultAlphaFunction = new AlphaFunction(AlphaFunction.BuiltinFunctions.EaseOutSquare);
733 scrollAnimation.AnimateTo(ContentContainer, (ScrollingDirection == Direction.Horizontal) ? "PositionX" : "PositionY", axisPosition, ScrollAlphaFunction);
735 OnScrollAnimationStarted();
736 scrollAnimation.Play();
740 /// Scroll to specific position with or without animation.
742 /// <param name="position">Destination.</param>
743 /// <param name="animate">Scroll with or without animation</param>
744 /// <since_tizen> 8 </since_tizen>
745 public void ScrollTo(float position, bool animate)
747 float currentPositionX = ContentContainer.CurrentPosition.X != 0 ? ContentContainer.CurrentPosition.X : ContentContainer.Position.X;
748 float currentPositionY = ContentContainer.CurrentPosition.Y != 0 ? ContentContainer.CurrentPosition.Y : ContentContainer.Position.Y;
749 float delta = ScrollingDirection == Direction.Horizontal ? currentPositionX : currentPositionY;
750 // The argument position is the new pan position. So the new position of ScrollableBase becomes (-position).
751 // To move ScrollableBase's position to (-position), it moves by (-position - currentPosition).
752 delta = -position - delta;
754 ScrollBy(delta, animate);
757 private float BoundScrollPosition(float targetPosition)
759 if (ScrollAvailableArea != null)
761 float minScrollPosition = ScrollAvailableArea.X;
762 float maxScrollPosition = ScrollAvailableArea.Y;
764 targetPosition = Math.Min(-minScrollPosition, targetPosition);
765 targetPosition = Math.Max(-maxScrollPosition, targetPosition);
769 targetPosition = Math.Min(0, targetPosition);
770 targetPosition = Math.Max(-maxScrollDistance, targetPosition);
773 return targetPosition;
776 private void ScrollBy(float displacement, bool animate)
778 if (GetChildCount() == 0 || maxScrollDistance < 0)
783 float childCurrentPosition = (ScrollingDirection == Direction.Horizontal) ? ContentContainer.PositionX : ContentContainer.PositionY;
785 Debug.WriteLineIf(LayoutDebugScrollableBase, "ScrollBy childCurrentPosition:" + childCurrentPosition +
786 " displacement:" + displacement,
787 " maxScrollDistance:" + maxScrollDistance);
789 childTargetPosition = childCurrentPosition + displacement; // child current position + gesture displacement
792 Debug.WriteLineIf(LayoutDebugScrollableBase, "ScrollBy currentAxisPosition:" + childCurrentPosition + "childTargetPosition:" + childTargetPosition);
796 // Calculate scroll animaton duration
797 float scrollDistance = Math.Abs(displacement);
798 readyToNotice = true;
800 AnimateChildTo(ScrollDuration, BoundScrollPosition(AdjustTargetPositionOfScrollAnimation(BoundScrollPosition(childTargetPosition))));
804 finalTargetPosition = BoundScrollPosition(childTargetPosition);
806 // Set position of scrolling child without an animation
807 if (ScrollingDirection == Direction.Horizontal)
809 ContentContainer.PositionX = finalTargetPosition;
813 ContentContainer.PositionY = finalTargetPosition;
820 /// you can override it to clean-up your own resources.
822 /// <param name="type">DisposeTypes</param>
823 /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API.
824 [EditorBrowsable(EditorBrowsableState.Never)]
825 protected override void Dispose(DisposeTypes type)
832 if (type == DisposeTypes.Explicit)
836 if (mPanGestureDetector != null)
838 mPanGestureDetector.Detected -= OnPanGestureDetected;
839 mPanGestureDetector.Dispose();
840 mPanGestureDetector = null;
846 private float CalculateMaximumScrollDistance()
848 float scrollingChildLength = 0;
849 float scrollerLength = 0;
850 if (ScrollingDirection == Direction.Horizontal)
852 Debug.WriteLineIf(LayoutDebugScrollableBase, "Horizontal");
854 scrollingChildLength = ContentContainer.Size.Width;
855 scrollerLength = Size.Width;
859 Debug.WriteLineIf(LayoutDebugScrollableBase, "Vertical");
860 scrollingChildLength = ContentContainer.Size.Height;
861 scrollerLength = Size.Height;
864 Debug.WriteLineIf(LayoutDebugScrollableBase, "ScrollBy maxScrollDistance:" + (scrollingChildLength - scrollerLength) +
865 " parent length:" + scrollerLength +
866 " scrolling child length:" + scrollingChildLength);
868 return Math.Max(scrollingChildLength - scrollerLength, 0);
871 private void PageSnap(float velocity)
873 Debug.WriteLineIf(LayoutDebugScrollableBase, "PageSnap with pan candidate totalDisplacement:" + totalDisplacementForPan +
874 " currentPage[" + CurrentPage + "]");
876 //Increment current page if total displacement enough to warrant a page change.
877 if (Math.Abs(totalDisplacementForPan) > (mPageWidth * ratioOfScreenWidthToCompleteScroll))
879 if (totalDisplacementForPan < 0)
881 CurrentPage = Math.Min(Math.Max(Children.Count - 1, 0), ++CurrentPage);
885 CurrentPage = Math.Max(0, --CurrentPage);
888 else if (Math.Abs(velocity) > PageFlickThreshold)
892 CurrentPage = Math.Min(Math.Max(Children.Count - 1, 0), ++CurrentPage);
896 CurrentPage = Math.Max(0, --CurrentPage);
900 // Animate to new page or reposition to current page
901 float destinationX = -(Children[CurrentPage].Position.X + Children[CurrentPage].CurrentSize.Width / 2 - CurrentSize.Width / 2); // set to middle of current page
902 Debug.WriteLineIf(LayoutDebugScrollableBase, "Snapping to page[" + CurrentPage + "] to:" + destinationX + " from:" + ContentContainer.PositionX);
903 AnimateChildTo(ScrollDuration, destinationX);
906 private void OnPanGestureDetected(object source, PanGestureDetector.DetectedEventArgs e)
908 OnPanGesture(e.PanGesture);
911 private void OnPanGesture(PanGesture panGesture)
913 if (SnapToPage && scrollAnimation != null && scrollAnimation.State == Animation.States.Playing)
918 if (panGesture.State == Gesture.StateType.Started)
920 readyToNotice = false;
921 base.Add(mInterruptTouchingChild);
922 Debug.WriteLineIf(LayoutDebugScrollableBase, "Gesture Start");
923 if (scrolling && !SnapToPage)
927 totalDisplacementForPan = 0.0f;
928 OnScrollDragStarted();
930 else if (panGesture.State == Gesture.StateType.Continuing)
932 if (ScrollingDirection == Direction.Horizontal)
934 ScrollBy(panGesture.Displacement.X, false);
935 totalDisplacementForPan += panGesture.Displacement.X;
939 ScrollBy(panGesture.Displacement.Y, false);
940 totalDisplacementForPan += panGesture.Displacement.Y;
942 Debug.WriteLineIf(LayoutDebugScrollableBase, "OnPanGestureDetected Continue totalDisplacementForPan:" + totalDisplacementForPan);
944 else if (panGesture.State == Gesture.StateType.Finished)
947 StopScroll(); // Will replace previous animation so will stop existing one.
949 if (scrollAnimation == null)
951 scrollAnimation = new Animation();
952 scrollAnimation.Finished += ScrollAnimationFinished;
955 float panVelocity = (ScrollingDirection == Direction.Horizontal) ? panGesture.Velocity.X : panGesture.Velocity.Y;
959 PageSnap(panVelocity);
963 if (panVelocity == 0)
965 float currentScrollPosition = (ScrollingDirection == Direction.Horizontal ? ContentContainer.CurrentPosition.X : ContentContainer.CurrentPosition.Y);
966 scrollAnimation.DefaultAlphaFunction = new AlphaFunction(AlphaFunction.BuiltinFunctions.Linear);
967 scrollAnimation.Duration = 0;
968 scrollAnimation.AnimateTo(ContentContainer, (ScrollingDirection == Direction.Horizontal) ? "PositionX" : "PositionY", currentScrollPosition);
969 scrollAnimation.Play();
973 Decelerating(panVelocity, scrollAnimation);
977 totalDisplacementForPan = 0;
979 readyToNotice = true;
980 OnScrollAnimationStarted();
984 internal override bool OnAccessibilityPan(PanGesture gestures)
986 if (SnapToPage && scrollAnimation != null && scrollAnimation.State == Animation.States.Playing)
991 OnPanGesture(gestures);
995 private float CustomScrollAlphaFunction(float progress)
997 if (panAnimationDelta == 0)
1003 // Parameter "progress" is normalized value. We need to multiply target duration to calculate distance.
1004 // Can get real distance using equation of deceleration (check Decelerating function)
1005 // After get real distance, normalize it
1006 float realDuration = progress * panAnimationDuration;
1007 float realDistance = velocityOfLastPan * ((float)Math.Pow(decelerationRate, realDuration) - 1) / logValueOfDeceleration;
1008 float result = Math.Min(realDistance / Math.Abs(panAnimationDelta), 1.0f);
1014 /// you can override it to custom your decelerating
1016 /// <param name="velocity">Velocity of current pan.</param>
1017 /// <param name="animation">Scroll animation.</param>
1018 [EditorBrowsable(EditorBrowsableState.Never)]
1019 protected virtual void Decelerating(float velocity, Animation animation)
1021 // Decelerating using deceleration equation ===========
1023 // V : velocity (pixel per milisecond)
1024 // V0 : initial velocity
1025 // d : deceleration rate,
1027 // X : final position after decelerating
1028 // log : natural logarithm
1030 // V(t) = V0 * d pow t;
1031 // X(t) = V0 * (d pow t - 1) / log d; <-- Integrate the velocity function
1032 // X(∞) = V0 * d / (1 - d); <-- Result using inifit T can be final position because T is tending to infinity.
1034 // Because of final T is tending to inifity, we should use threshold value to finish.
1035 // Final T = log(-threshold * log d / |V0| ) / log d;
1037 velocityOfLastPan = Math.Abs(velocity);
1039 float currentScrollPosition = -(ScrollingDirection == Direction.Horizontal ? ContentContainer.CurrentPosition.X : ContentContainer.CurrentPosition.Y);
1040 panAnimationDelta = (velocityOfLastPan * decelerationRate) / (1 - decelerationRate);
1041 panAnimationDelta = velocity > 0 ? -panAnimationDelta : panAnimationDelta;
1043 float destination = -(panAnimationDelta + currentScrollPosition);
1044 float adjustDestination = AdjustTargetPositionOfScrollAnimation(destination);
1045 float maxPosition = ScrollAvailableArea != null ? ScrollAvailableArea.Y : maxScrollDistance;
1046 float minPosition = ScrollAvailableArea != null ? ScrollAvailableArea.X : 0;
1048 if (destination < -maxPosition || destination > minPosition)
1050 panAnimationDelta = velocity > 0 ? (currentScrollPosition - minPosition) : (maxPosition - currentScrollPosition);
1051 destination = velocity > 0 ? minPosition : -maxPosition;
1053 if (panAnimationDelta == 0)
1055 panAnimationDuration = 0.0f;
1059 panAnimationDuration = (float)Math.Log((panAnimationDelta * logValueOfDeceleration / velocityOfLastPan + 1), decelerationRate);
1062 Debug.WriteLineIf(LayoutDebugScrollableBase, "\n" +
1063 "OverRange======================= \n" +
1064 "[decelerationRate] " + decelerationRate + "\n" +
1065 "[logValueOfDeceleration] " + logValueOfDeceleration + "\n" +
1066 "[Velocity] " + velocityOfLastPan + "\n" +
1067 "[CurrentPosition] " + currentScrollPosition + "\n" +
1068 "[CandidateDelta] " + panAnimationDelta + "\n" +
1069 "[Destination] " + destination + "\n" +
1070 "[Duration] " + panAnimationDuration + "\n" +
1071 "================================ \n"
1076 panAnimationDuration = (float)Math.Log(-DecelerationThreshold * logValueOfDeceleration / velocityOfLastPan) / logValueOfDeceleration;
1078 if (adjustDestination != destination)
1080 destination = adjustDestination;
1081 panAnimationDelta = destination + currentScrollPosition;
1082 velocityOfLastPan = Math.Abs(panAnimationDelta * logValueOfDeceleration / ((float)Math.Pow(decelerationRate, panAnimationDuration) - 1));
1083 panAnimationDuration = (float)Math.Log(-DecelerationThreshold * logValueOfDeceleration / velocityOfLastPan) / logValueOfDeceleration;
1086 Debug.WriteLineIf(LayoutDebugScrollableBase, "\n" +
1087 "================================ \n" +
1088 "[decelerationRate] " + decelerationRate + "\n" +
1089 "[logValueOfDeceleration] " + logValueOfDeceleration + "\n" +
1090 "[Velocity] " + velocityOfLastPan + "\n" +
1091 "[CurrentPosition] " + currentScrollPosition + "\n" +
1092 "[CandidateDelta] " + panAnimationDelta + "\n" +
1093 "[Destination] " + destination + "\n" +
1094 "[Duration] " + panAnimationDuration + "\n" +
1095 "================================ \n"
1099 finalTargetPosition = destination;
1101 customScrollAlphaFunction = new UserAlphaFunctionDelegate(CustomScrollAlphaFunction);
1102 animation.DefaultAlphaFunction = new AlphaFunction(customScrollAlphaFunction);
1103 GC.KeepAlive(customScrollAlphaFunction);
1104 animation.Duration = (int)panAnimationDuration;
1105 animation.AnimateTo(ContentContainer, (ScrollingDirection == Direction.Horizontal) ? "PositionX" : "PositionY", destination);
1109 private void ScrollAnimationFinished(object sender, EventArgs e)
1111 OnScrollAnimationEnded();
1115 /// Adjust scrolling position by own scrolling rules.
1116 /// Override this function when developer wants to change destination of flicking.(e.g. always snap to center of item)
1118 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
1119 [EditorBrowsable(EditorBrowsableState.Never)]
1120 protected virtual float AdjustTargetPositionOfScrollAnimation(float position)
1126 /// Scroll position given to ScrollTo.
1127 /// This is the position in the opposite direction to the position of ContentContainer.
1129 /// <since_tizen> 8 </since_tizen>
1130 public Position ScrollPosition
1134 return new Position(-ContentContainer.Position);
1139 /// Current scroll position in the middle of ScrollTo animation.
1140 /// This is the position in the opposite direction to the current position of ContentContainer.
1142 /// <since_tizen> 8 </since_tizen>
1143 public Position ScrollCurrentPosition
1147 return new Position(-ContentContainer.CurrentPosition);