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.ComponentModel;
19 using System.Diagnostics;
21 namespace Tizen.NUI.Components
24 /// [Draft] This class provides a View that can scroll a single View with a layout. This View can be a nest of Views.
26 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API.
27 [EditorBrowsable(EditorBrowsableState.Never)]
28 public class ScrollableBase : Control
30 static bool LayoutDebugScrollableBase = false; // Debug flag
31 private Direction mScrollingDirection = Direction.Vertical;
32 private bool mScrollEnabled = true;
33 private int mPageWidth = 0;
35 private class ScrollableBaseCustomLayout : LayoutGroup
37 protected override void OnMeasure(MeasureSpecification widthMeasureSpec, MeasureSpecification heightMeasureSpec)
39 Extents padding = Padding;
40 float totalHeight = padding.Top + padding.Bottom;
41 float totalWidth = padding.Start + padding.End;
43 MeasuredSize.StateType childWidthState = MeasuredSize.StateType.MeasuredSizeOK;
44 MeasuredSize.StateType childHeightState = MeasuredSize.StateType.MeasuredSizeOK;
46 Direction scrollingDirection = Direction.Vertical;
47 ScrollableBase scrollableBase = this.Owner as ScrollableBase;
50 scrollingDirection = scrollableBase.ScrollingDirection;
53 // measure child, should be a single scrolling child
54 foreach (LayoutItem childLayout in LayoutChildren)
56 if (childLayout != null)
59 // Use an Unspecified MeasureSpecification mode so scrolling child is not restricted to it's parents size in Height (for vertical scrolling)
60 // or Width for horizontal scrolling
61 MeasureSpecification unrestrictedMeasureSpec = new MeasureSpecification(heightMeasureSpec.Size, MeasureSpecification.ModeType.Unspecified);
63 if (scrollingDirection == Direction.Vertical)
65 MeasureChildWithMargins(childLayout, widthMeasureSpec, new LayoutLength(0), unrestrictedMeasureSpec, new LayoutLength(0)); // Height unrestricted by parent
69 MeasureChildWithMargins(childLayout, unrestrictedMeasureSpec, new LayoutLength(0), heightMeasureSpec, new LayoutLength(0)); // Width unrestricted by parent
72 float childWidth = childLayout.MeasuredWidth.Size.AsDecimal();
73 float childHeight = childLayout.MeasuredHeight.Size.AsDecimal();
75 // Determine the width and height needed by the children using their given position and size.
76 // Children could overlap so find the left most and right most child.
77 Position2D childPosition = childLayout.Owner.Position2D;
78 float childLeft = childPosition.X;
79 float childTop = childPosition.Y;
81 // Store current width and height needed to contain all children.
82 Extents childMargin = childLayout.Margin;
83 totalWidth = childWidth + childMargin.Start + childMargin.End;
84 totalHeight = childHeight + childMargin.Top + childMargin.Bottom;
86 if (childLayout.MeasuredWidth.State == MeasuredSize.StateType.MeasuredSizeTooSmall)
88 childWidthState = MeasuredSize.StateType.MeasuredSizeTooSmall;
90 if (childLayout.MeasuredWidth.State == MeasuredSize.StateType.MeasuredSizeTooSmall)
92 childHeightState = MeasuredSize.StateType.MeasuredSizeTooSmall;
98 MeasuredSize widthSizeAndState = ResolveSizeAndState(new LayoutLength(totalWidth + Padding.Start + Padding.End), widthMeasureSpec, MeasuredSize.StateType.MeasuredSizeOK);
99 MeasuredSize heightSizeAndState = ResolveSizeAndState(new LayoutLength(totalHeight + Padding.Top + Padding.Bottom), heightMeasureSpec, MeasuredSize.StateType.MeasuredSizeOK);
100 totalWidth = widthSizeAndState.Size.AsDecimal();
101 totalHeight = heightSizeAndState.Size.AsDecimal();
103 // Ensure layout respects it's given minimum size
104 totalWidth = Math.Max(totalWidth, SuggestedMinimumWidth.AsDecimal());
105 totalHeight = Math.Max(totalHeight, SuggestedMinimumHeight.AsDecimal());
107 widthSizeAndState.State = childWidthState;
108 heightSizeAndState.State = childHeightState;
110 SetMeasuredDimensions(ResolveSizeAndState(new LayoutLength(totalWidth + Padding.Start + Padding.End), widthMeasureSpec, childWidthState),
111 ResolveSizeAndState(new LayoutLength(totalHeight + Padding.Top + Padding.Bottom), heightMeasureSpec, childHeightState));
113 // Size of ScrollableBase is changed. Change Page width too.
114 scrollableBase.mPageWidth = (int)MeasuredWidth.Size.AsRoundedValue();
117 protected override void OnLayout(bool changed, LayoutLength left, LayoutLength top, LayoutLength right, LayoutLength bottom)
119 foreach (LayoutItem childLayout in LayoutChildren)
121 if (childLayout != null)
123 LayoutLength childWidth = childLayout.MeasuredWidth.Size;
124 LayoutLength childHeight = childLayout.MeasuredHeight.Size;
126 Position2D childPosition = childLayout.Owner.Position2D;
127 Extents padding = Padding;
128 Extents childMargin = childLayout.Margin;
130 LayoutLength childLeft = new LayoutLength(childPosition.X + childMargin.Start + padding.Start);
131 LayoutLength childTop = new LayoutLength(childPosition.Y + childMargin.Top + padding.Top);
133 childLayout.Layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight);
137 } // ScrollableBaseCustomLayout
140 /// The direction axis to scroll.
142 /// <since_tizen> 6 </since_tizen>
143 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API.
144 [EditorBrowsable(EditorBrowsableState.Never)]
145 public enum Direction
150 /// <since_tizen> 6 </since_tizen>
156 /// <since_tizen> 6 </since_tizen>
161 /// [Draft] Configurable speed threshold that register the gestures as a flick.
162 /// If the flick speed less than the threshold then will not be considered a flick.
164 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API.
165 [EditorBrowsable(EditorBrowsableState.Never)]
166 public float FlickThreshold { get; set; } = 0.2f;
169 /// [Draft] Configurable duration modifer for the flick animation.
170 /// Determines the speed of the scroll, large value results in a longer flick animation. Range (0.1 - 1.0)
172 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
173 [EditorBrowsable(EditorBrowsableState.Never)]
174 public float FlickAnimationSpeed { get; set; } = 0.4f;
177 /// [Draft] Configurable modifer for the distance to be scrolled when flicked detected.
178 /// It a ratio of the ScrollableBase's length. (not child's length).
179 /// First value is the ratio of the distance to scroll with the weakest flick.
180 /// Second value is the ratio of the distance to scroll with the strongest flick.
183 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
184 [EditorBrowsable(EditorBrowsableState.Never)]
185 public Vector2 FlickDistanceMultiplierRange { get; set; } = new Vector2(0.6f, 1.8f);
188 /// [Draft] Scrolling direction mode.
189 /// Default is Vertical scrolling.
191 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
192 [EditorBrowsable(EditorBrowsableState.Never)]
193 public Direction ScrollingDirection
197 return mScrollingDirection;
201 if (value != mScrollingDirection)
203 mScrollingDirection = value;
204 mPanGestureDetector.RemoveDirection(value == Direction.Horizontal ? PanGestureDetector.DirectionVertical : PanGestureDetector.DirectionHorizontal);
205 mPanGestureDetector.AddDirection(value == Direction.Horizontal ? PanGestureDetector.DirectionHorizontal : PanGestureDetector.DirectionVertical);
211 /// [Draft] Enable or disable scrolling.
213 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
214 [EditorBrowsable(EditorBrowsableState.Never)]
215 public bool ScrollEnabled
219 return mScrollEnabled;
223 if (value != mScrollEnabled)
225 mScrollEnabled = value;
228 mPanGestureDetector.Detected += OnPanGestureDetected;
229 mTapGestureDetector.Detected += OnTapGestureDetected;
233 mPanGestureDetector.Detected -= OnPanGestureDetected;
234 mTapGestureDetector.Detected -= OnTapGestureDetected;
241 /// [Draft] Pages mode, enables moving to the next or return to current page depending on pan displacement.
242 /// Default is false.
244 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
245 [EditorBrowsable(EditorBrowsableState.Never)]
246 public bool SnapToPage { set; get; } = false;
249 /// [Draft] Get current page.
250 /// Working propery with SnapToPage property.
252 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
253 [EditorBrowsable(EditorBrowsableState.Never)]
254 public int CurrentPage { get; private set; } = 0;
257 /// [Draft] Duration of scroll animation.
259 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
260 [EditorBrowsable(EditorBrowsableState.Never)]
262 public int ScrollDuration { set; get; } = 125;
264 /// [Draft] Scroll Available area.
266 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
267 [EditorBrowsable(EditorBrowsableState.Never)]
268 public Vector2 ScrollAvailableArea { set; get; }
271 /// ScrollEventArgs is a class to record scroll event arguments which will sent to user.
273 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
274 [EditorBrowsable(EditorBrowsableState.Never)]
275 public class ScrollEventArgs : EventArgs
280 /// Default constructor.
282 /// <param name="position">Current scroll position</param>
283 /// <since_tizen> 6 </since_tizen>
284 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
285 public ScrollEventArgs(Position position)
287 this.position = position;
291 /// [Draft] Current scroll position.
293 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
294 [EditorBrowsable(EditorBrowsableState.Never)]
295 public Position Position
305 /// An event emitted when user starts dragging ScrollableBase, user can subscribe or unsubscribe to this event handler.<br />
307 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
308 [EditorBrowsable(EditorBrowsableState.Never)]
309 public event EventHandler<ScrollEventArgs> ScrollDragStartEvent;
312 /// An event emitted when user stops dragging ScrollableBase, user can subscribe or unsubscribe to this event handler.<br />
314 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
315 [EditorBrowsable(EditorBrowsableState.Never)]
316 public event EventHandler<ScrollEventArgs> ScrollDragEndEvent;
320 /// An event emitted when the scrolling slide animation starts, user can subscribe or unsubscribe to this event handler.<br />
322 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
323 [EditorBrowsable(EditorBrowsableState.Never)]
324 public event EventHandler<ScrollEventArgs> ScrollAnimationStartEvent;
327 /// An event emitted when the scrolling slide animation ends, user can subscribe or unsubscribe to this event handler.<br />
329 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
330 [EditorBrowsable(EditorBrowsableState.Never)]
331 public event EventHandler<ScrollEventArgs> ScrollAnimationEndEvent;
335 /// An event emitted when scrolling, user can subscribe or unsubscribe to this event handler.<br />
337 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
338 [EditorBrowsable(EditorBrowsableState.Never)]
339 public event EventHandler<ScrollEventArgs> ScrollEvent;
343 /// Scrollbar for ScrollableBase.<br />
345 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
346 [EditorBrowsable(EditorBrowsableState.Never)]
347 public ScrollbarBase Scrollbar
357 scrollBar.Unparent();
361 scrollBar.Name = "ScrollBar";
378 /// [Draft] Always hide Scrollbar.
380 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
381 [EditorBrowsable(EditorBrowsableState.Never)]
382 public bool HideScrollBar
386 return hideScrollbar;
390 hideScrollbar = value;
406 private bool hideScrollbar = true;
407 private Animation scrollAnimation;
408 private float maxScrollDistance;
409 private float childTargetPosition = 0.0f;
410 private PanGestureDetector mPanGestureDetector;
411 private TapGestureDetector mTapGestureDetector;
412 private View mScrollingChild;
413 private View mInterruptTouchingChild;
414 private ScrollbarBase scrollBar;
415 private float multiplier = 1.0f;
416 private bool scrolling = false;
417 private float ratioOfScreenWidthToCompleteScroll = 0.5f;
418 private float totalDisplacementForPan = 0.0f;
419 private Size previousContainerSize = new Size();
421 // If false then can only flick pages when the current animation/scroll as ended.
422 private bool flickWhenAnimating = false;
423 private PropertyNotification propertyNotification;
425 // Let's consider more whether this needs to be set as protected.
426 private float finalTargetPosition;
429 /// [Draft] Constructor
431 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
432 [EditorBrowsable(EditorBrowsableState.Never)]
433 public ScrollableBase() : base()
435 mPanGestureDetector = new PanGestureDetector();
436 mPanGestureDetector.Attach(this);
437 mPanGestureDetector.AddDirection(PanGestureDetector.DirectionVertical);
438 mPanGestureDetector.Detected += OnPanGestureDetected;
440 mTapGestureDetector = new TapGestureDetector();
441 mTapGestureDetector.Attach(this);
442 mTapGestureDetector.Detected += OnTapGestureDetected;
444 ClippingMode = ClippingModeType.ClipChildren;
446 mScrollingChild = new View();
447 mScrollingChild.Name = "DefaultScrollingChild";
449 //Interrupt touching when panning is started;
450 mInterruptTouchingChild = new View()
452 Name = "InterruptTouchingChild",
453 Size = new Size(Window.Instance.WindowSize),
454 BackgroundColor = Color.Transparent,
457 mInterruptTouchingChild.TouchEvent += OnIterruptTouchingChildTouched;
459 Layout = new ScrollableBaseCustomLayout();
461 Scrollbar = new Scrollbar();
464 private bool OnIterruptTouchingChildTouched(object source, View.TouchEventArgs args)
469 private void OnPropertyChanged(object source, PropertyNotification.NotifyEventArgs args)
475 /// Called after a child has been added to the owning view.
477 /// <param name="view">The child which has been added.</param>
478 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
479 [EditorBrowsable(EditorBrowsableState.Never)]
480 public override void OnChildAdd(View view)
482 if (view.Name != "InterruptTouchingChild" && view.Name != "ScrollBar")
484 if (mScrollingChild.Name != "DefaultScrollingChild")
486 propertyNotification.Notified -= OnPropertyChanged;
487 mScrollingChild.RemovePropertyNotification(propertyNotification);
488 mScrollingChild.Relayout -= OnScrollingChildRelayout;
491 mScrollingChild = view;
492 mScrollingChild.Layout.SetPositionByLayout = false;
493 propertyNotification = mScrollingChild?.AddPropertyNotification("position", PropertyCondition.Step(1.0f));
494 propertyNotification.Notified += OnPropertyChanged;
495 mScrollingChild.Relayout += OnScrollingChildRelayout;
496 mScrollingChild.LowerToBottom();
501 /// Called after a child has been removed from the owning view.
503 /// <param name="view">The child which has been removed.</param>
504 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
505 [EditorBrowsable(EditorBrowsableState.Never)]
506 public override void OnChildRemove(View view)
508 if (view.Name != "InterruptTouchingChild" && view.Name != "ScrollBar")
510 propertyNotification.Notified -= OnPropertyChanged;
511 mScrollingChild.RemovePropertyNotification(propertyNotification);
512 mScrollingChild.Relayout -= OnScrollingChildRelayout;
514 mScrollingChild.Layout.SetPositionByLayout = true;
515 mScrollingChild = new View();
519 private void OnScrollingChildRelayout(object source, EventArgs args)
521 // Size is changed. Calculate maxScrollDistance.
522 bool isSizeChanged = previousContainerSize.Width != mScrollingChild.Size.Width || previousContainerSize.Height != mScrollingChild.Size.Height;
526 maxScrollDistance = CalculateMaximumScrollDistance();
530 previousContainerSize = mScrollingChild.Size;
534 /// The composition of a Scrollbar can vary depending on how you use ScrollableBase.
535 /// Set the composition that will go into the ScrollableBase according to your ScrollableBase.
537 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
538 [EditorBrowsable(EditorBrowsableState.Never)]
539 protected virtual void SetScrollbar()
543 bool isHorizontal = ScrollingDirection == Direction.Horizontal;
544 float contentLength = isHorizontal ? mScrollingChild.Size.Width : mScrollingChild.Size.Height;
545 float viewportLength = isHorizontal ? Size.Width : Size.Height;
546 float currentPosition = isHorizontal ? mScrollingChild.CurrentPosition.X : mScrollingChild.CurrentPosition.Y;
547 Scrollbar.Initialize(contentLength, viewportLength, currentPosition, isHorizontal);
552 /// Scrolls to the item at the specified index.
554 /// <param name="index">Index of item.</param>
555 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
556 [EditorBrowsable(EditorBrowsableState.Never)]
557 public void ScrollToIndex(int index)
559 if (mScrollingChild.ChildCount - 1 < index || index < 0)
569 float targetPosition = Math.Min(ScrollingDirection == Direction.Vertical ? mScrollingChild.Children[index].Position.Y : mScrollingChild.Children[index].Position.X, maxScrollDistance);
570 AnimateChildTo(ScrollDuration, -targetPosition);
573 private void OnScrollDragStart()
575 ScrollEventArgs eventArgs = new ScrollEventArgs(mScrollingChild.CurrentPosition);
576 ScrollDragStartEvent?.Invoke(this, eventArgs);
579 private void OnScrollDragEnd()
581 ScrollEventArgs eventArgs = new ScrollEventArgs(mScrollingChild.CurrentPosition);
582 ScrollDragEndEvent?.Invoke(this, eventArgs);
585 private void OnScrollAnimationStart()
587 ScrollEventArgs eventArgs = new ScrollEventArgs(mScrollingChild.CurrentPosition);
588 ScrollAnimationStartEvent?.Invoke(this, eventArgs);
591 private void OnScrollAnimationEnd()
593 ScrollEventArgs eventArgs = new ScrollEventArgs(mScrollingChild.CurrentPosition);
594 ScrollAnimationEndEvent?.Invoke(this, eventArgs);
597 private bool readyToNotice = false;
599 private float noticeAnimationEndBeforePosition = 0.0f;
600 // Let's consider more whether this needs to be set as protected.
601 public float NoticeAnimationEndBeforePosition { get => noticeAnimationEndBeforePosition; set => noticeAnimationEndBeforePosition = value; }
603 private void OnScroll()
605 ScrollEventArgs eventArgs = new ScrollEventArgs(mScrollingChild.CurrentPosition);
606 ScrollEvent?.Invoke(this, eventArgs);
608 bool isHorizontal = ScrollingDirection == Direction.Horizontal;
609 float contentLength = isHorizontal ? mScrollingChild.Size.Width : mScrollingChild.Size.Height;
610 float currentPosition = isHorizontal ? mScrollingChild.CurrentPosition.X : mScrollingChild.CurrentPosition.Y;
612 scrollBar.Update(contentLength, Math.Abs(currentPosition));
613 CheckPreReachedTargetPosition();
616 private void CheckPreReachedTargetPosition()
618 // Check whether we reached pre-reached target position
620 mScrollingChild.CurrentPosition.Y <= finalTargetPosition + NoticeAnimationEndBeforePosition &&
621 mScrollingChild.CurrentPosition.Y >= finalTargetPosition - NoticeAnimationEndBeforePosition)
624 readyToNotice = false;
625 OnPreReachedTargetPosition(finalTargetPosition);
630 /// This helps developer who wants to know before scroll is reaching target position.
632 /// <param name="targetPosition">Index of item.</param>
633 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
634 [EditorBrowsable(EditorBrowsableState.Never)]
635 protected virtual void OnPreReachedTargetPosition(float targetPosition)
640 private void StopScroll()
642 if (scrollAnimation != null)
644 if (scrollAnimation.State == Animation.States.Playing)
646 Debug.WriteLineIf(LayoutDebugScrollableBase, "StopScroll Animation Playing");
647 scrollAnimation.Stop(Animation.EndActions.Cancel);
648 OnScrollAnimationEnd();
650 scrollAnimation.Clear();
654 // static constructor registers the control type
655 static ScrollableBase()
657 // ViewRegistry registers control type with DALi type registry
658 // also uses introspection to find any properties that need to be registered with type registry
659 CustomViewRegistry.Instance.Register(CreateInstance, typeof(ScrollableBase));
662 internal static CustomView CreateInstance()
664 return new ScrollableBase();
667 private void AnimateChildTo(int duration, float axisPosition)
669 Debug.WriteLineIf(LayoutDebugScrollableBase, "AnimationTo Animation Duration:" + duration + " Destination:" + axisPosition);
670 finalTargetPosition = axisPosition;
672 StopScroll(); // Will replace previous animation so will stop existing one.
674 if (scrollAnimation == null)
676 scrollAnimation = new Animation();
677 scrollAnimation.Finished += ScrollAnimationFinished;
680 scrollAnimation.Duration = duration;
681 scrollAnimation.DefaultAlphaFunction = new AlphaFunction(AlphaFunction.BuiltinFunctions.EaseOutSine);
682 scrollAnimation.AnimateTo(mScrollingChild, (ScrollingDirection == Direction.Horizontal) ? "PositionX" : "PositionY", axisPosition);
684 OnScrollAnimationStart();
685 scrollAnimation.Play();
689 /// Scroll to specific position with or without animation.
691 /// <param name="position">Destination.</param>
692 /// <param name="animate">Scroll with or without animation</param>
693 [EditorBrowsable(EditorBrowsableState.Never)]
694 public void ScrollTo(float position, bool animate)
696 float currentPositionX = mScrollingChild.CurrentPosition.X != 0 ? mScrollingChild.CurrentPosition.X : mScrollingChild.Position.X;
697 float currentPositionY = mScrollingChild.CurrentPosition.Y != 0 ? mScrollingChild.CurrentPosition.Y : mScrollingChild.Position.Y;
698 float delta = ScrollingDirection == Direction.Horizontal ? currentPositionX : currentPositionY;
699 // The argument position is the new pan position. So the new position of ScrollableBase becomes (-position).
700 // To move ScrollableBase's position to (-position), it moves by (-position - currentPosition).
701 delta = -position - delta;
703 ScrollBy(delta, animate);
706 private float BoundScrollPosition(float targetPosition)
708 if (ScrollAvailableArea != null)
710 float minScrollPosition = ScrollAvailableArea.X;
711 float maxScrollPosition = ScrollAvailableArea.Y;
713 targetPosition = Math.Min(-minScrollPosition, targetPosition);
714 targetPosition = Math.Max(-maxScrollPosition, targetPosition);
718 targetPosition = Math.Min(0, targetPosition);
719 targetPosition = Math.Max(-maxScrollDistance, targetPosition);
722 return targetPosition;
725 private void ScrollBy(float displacement, bool animate)
727 if (GetChildCount() == 0 || maxScrollDistance < 0)
732 float childCurrentPosition = (ScrollingDirection == Direction.Horizontal) ? mScrollingChild.PositionX : mScrollingChild.PositionY;
734 Debug.WriteLineIf(LayoutDebugScrollableBase, "ScrollBy childCurrentPosition:" + childCurrentPosition +
735 " displacement:" + displacement,
736 " maxScrollDistance:" + maxScrollDistance);
738 childTargetPosition = childCurrentPosition + displacement; // child current position + gesture displacement
741 Debug.WriteLineIf(LayoutDebugScrollableBase, "ScrollBy currentAxisPosition:" + childCurrentPosition + "childTargetPosition:" + childTargetPosition);
745 // Calculate scroll animaton duration
746 float scrollDistance = Math.Abs(displacement);
747 int duration = (int)((320 * FlickAnimationSpeed) + (scrollDistance * FlickAnimationSpeed));
748 Debug.WriteLineIf(LayoutDebugScrollableBase, "Scroll Animation Duration:" + duration + " Distance:" + scrollDistance);
750 readyToNotice = true;
752 AnimateChildTo(duration, BoundScrollPosition(AdjustTargetPositionOfScrollAnimation(BoundScrollPosition(childTargetPosition))));
756 finalTargetPosition = BoundScrollPosition(childTargetPosition);
758 // Set position of scrolling child without an animation
759 if (ScrollingDirection == Direction.Horizontal)
761 mScrollingChild.PositionX = finalTargetPosition;
765 mScrollingChild.PositionY = finalTargetPosition;
772 /// you can override it to clean-up your own resources.
774 /// <param name="type">DisposeTypes</param>
775 /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API.
776 [EditorBrowsable(EditorBrowsableState.Never)]
777 protected override void Dispose(DisposeTypes type)
784 if (type == DisposeTypes.Explicit)
788 if (mPanGestureDetector != null)
790 mPanGestureDetector.Detected -= OnPanGestureDetected;
791 mPanGestureDetector.Dispose();
792 mPanGestureDetector = null;
795 if (mTapGestureDetector != null)
797 mTapGestureDetector.Detected -= OnTapGestureDetected;
798 mTapGestureDetector.Dispose();
799 mTapGestureDetector = null;
805 private float CalculateDisplacementFromVelocity(float axisVelocity)
807 // Map: flick speed of range (2.0 - 6.0) to flick multiplier of range (0.7 - 1.6)
808 float speedMinimum = FlickThreshold;
809 float speedMaximum = FlickThreshold + 6.0f;
810 float multiplierMinimum = FlickDistanceMultiplierRange.X;
811 float multiplierMaximum = FlickDistanceMultiplierRange.Y;
813 float flickDisplacement = 0.0f;
815 float speed = Math.Min(4.0f, Math.Abs(axisVelocity));
817 Debug.WriteLineIf(LayoutDebugScrollableBase, "ScrollableBase Candidate Flick speed:" + speed);
819 if (speed > FlickThreshold)
821 // Flick length is the length of the ScrollableBase.
822 float flickLength = (ScrollingDirection == Direction.Horizontal) ? CurrentSize.Width : CurrentSize.Height;
824 // Calculate multiplier by mapping speed between the multiplier minimum and maximum.
825 multiplier = ((speed - speedMinimum) / ((speedMaximum - speedMinimum) * (multiplierMaximum - multiplierMinimum))) + multiplierMinimum;
827 // flick displacement is the product of the flick length and multiplier
828 flickDisplacement = ((flickLength * multiplier) * speed) / axisVelocity; // *speed and /velocity to perserve sign.
830 Debug.WriteLineIf(LayoutDebugScrollableBase, "Calculated FlickDisplacement[" + flickDisplacement + "] from speed[" + speed + "] multiplier:"
833 return flickDisplacement;
836 private float CalculateMaximumScrollDistance()
838 float scrollingChildLength = 0;
839 float scrollerLength = 0;
840 if (ScrollingDirection == Direction.Horizontal)
842 Debug.WriteLineIf(LayoutDebugScrollableBase, "Horizontal");
844 scrollingChildLength = mScrollingChild.Size.Width;
845 scrollerLength = Size.Width;
849 Debug.WriteLineIf(LayoutDebugScrollableBase, "Vertical");
850 scrollingChildLength = mScrollingChild.Size.Height;
851 scrollerLength = Size.Height;
854 Debug.WriteLineIf(LayoutDebugScrollableBase, "ScrollBy maxScrollDistance:" + (scrollingChildLength - scrollerLength) +
855 " parent length:" + scrollerLength +
856 " scrolling child length:" + scrollingChildLength);
858 return Math.Max(scrollingChildLength - scrollerLength, 0);
861 private void PageSnap()
863 Debug.WriteLineIf(LayoutDebugScrollableBase, "PageSnap with pan candidate totalDisplacement:" + totalDisplacementForPan +
864 " currentPage[" + CurrentPage + "]");
866 //Increment current page if total displacement enough to warrant a page change.
867 if (Math.Abs(totalDisplacementForPan) > (mPageWidth * ratioOfScreenWidthToCompleteScroll))
869 if (totalDisplacementForPan < 0)
871 CurrentPage = Math.Min(Math.Max(mScrollingChild.Children.Count - 1, 0), ++CurrentPage);
875 CurrentPage = Math.Max(0, --CurrentPage);
879 // Animate to new page or reposition to current page
880 float destinationX = -(mScrollingChild.Children[CurrentPage].Position.X + mScrollingChild.Children[CurrentPage].CurrentSize.Width / 2 - CurrentSize.Width / 2); // set to middle of current page
881 Debug.WriteLineIf(LayoutDebugScrollableBase, "Snapping to page[" + CurrentPage + "] to:" + destinationX + " from:" + mScrollingChild.PositionX);
882 AnimateChildTo(ScrollDuration, destinationX);
885 private void Flick(float flickDisplacement)
889 if ((flickWhenAnimating && scrolling == true) || (scrolling == false))
891 if (flickDisplacement < 0)
893 CurrentPage = Math.Min(Math.Max(mScrollingChild.Children.Count - 1, 0), CurrentPage + 1);
894 Debug.WriteLineIf(LayoutDebugScrollableBase, "Snap - to page:" + CurrentPage);
898 CurrentPage = Math.Max(0, CurrentPage - 1);
899 Debug.WriteLineIf(LayoutDebugScrollableBase, "Snap + to page:" + CurrentPage);
902 float destinationX = -(mScrollingChild.Children[CurrentPage].Position.X + mScrollingChild.Children[CurrentPage].CurrentSize.Width / 2.0f - CurrentSize.Width / 2.0f); // set to middle of current page
903 Debug.WriteLineIf(LayoutDebugScrollableBase, "Snapping to :" + destinationX);
904 AnimateChildTo(ScrollDuration, destinationX);
909 ScrollBy(flickDisplacement, true); // Animate flickDisplacement.
913 private void OnPanGestureDetected(object source, PanGestureDetector.DetectedEventArgs e)
915 if (e.PanGesture.State == Gesture.StateType.Started)
917 Add(mInterruptTouchingChild);
918 Debug.WriteLineIf(LayoutDebugScrollableBase, "Gesture Start");
919 if (scrolling && !SnapToPage)
923 totalDisplacementForPan = 0.0f;
926 else if (e.PanGesture.State == Gesture.StateType.Continuing)
928 if (ScrollingDirection == Direction.Horizontal)
930 ScrollBy(e.PanGesture.Displacement.X, false);
931 totalDisplacementForPan += e.PanGesture.Displacement.X;
935 ScrollBy(e.PanGesture.Displacement.Y, false);
936 totalDisplacementForPan += e.PanGesture.Displacement.Y;
938 Debug.WriteLineIf(LayoutDebugScrollableBase, "OnPanGestureDetected Continue totalDisplacementForPan:" + totalDisplacementForPan);
940 else if (e.PanGesture.State == Gesture.StateType.Finished)
942 float axisVelocity = (ScrollingDirection == Direction.Horizontal) ? e.PanGesture.Velocity.X : e.PanGesture.Velocity.Y;
943 float flickDisplacement = CalculateDisplacementFromVelocity(axisVelocity);
945 Debug.WriteLineIf(LayoutDebugScrollableBase, "FlickDisplacement:" + flickDisplacement + "TotalDisplacementForPan:" + totalDisplacementForPan);
948 if (flickDisplacement > 0 | flickDisplacement < 0)// Flick detected
950 Flick(flickDisplacement);
954 // End of panning gesture but was not a flick
964 totalDisplacementForPan = 0;
966 Remove(mInterruptTouchingChild);
970 private new void OnTapGestureDetected(object source, TapGestureDetector.DetectedEventArgs e)
972 if (e.TapGesture.Type == Gesture.GestureType.Tap)
974 // Stop scrolling if tap detected (press then relase).
975 // Unless in Pages mode, do not want a page change to stop part way.
976 if (scrolling && !SnapToPage)
983 private void ScrollAnimationFinished(object sender, EventArgs e)
986 CheckPreReachedTargetPosition();
987 OnScrollAnimationEnd();
991 /// Adjust scrolling position by own scrolling rules.
992 /// Override this function when developer wants to change destination of flicking.(e.g. always snap to center of item)
994 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
995 [EditorBrowsable(EditorBrowsableState.Never)]
996 protected virtual float AdjustTargetPositionOfScrollAnimation(float position)