1 /* Copyright (c) 2019 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;
20 namespace Tizen.NUI.Components
23 /// [Draft] This class provides a View that can scroll a single View with a layout. This View can be a nest of Views.
25 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API.
26 [EditorBrowsable(EditorBrowsableState.Never)]
27 public class ScrollableBase : Control
29 static bool LayoutDebugScrollableBase = false; // Debug flag
30 private Direction mScrollingDirection = Direction.Vertical;
31 private bool mScrollEnabled = true;
33 private class ScrollableBaseCustomLayout : LayoutGroup
35 protected override void OnMeasure(MeasureSpecification widthMeasureSpec, MeasureSpecification heightMeasureSpec)
37 Extents padding = Padding;
38 float totalHeight = padding.Top + padding.Bottom;
39 float totalWidth = padding.Start + padding.End;
41 MeasuredSize.StateType childWidthState = MeasuredSize.StateType.MeasuredSizeOK;
42 MeasuredSize.StateType childHeightState = MeasuredSize.StateType.MeasuredSizeOK;
44 Direction scrollingDirection = Direction.Vertical;
45 ScrollableBase scrollableBase = this.Owner as ScrollableBase;
48 scrollingDirection = scrollableBase.ScrollingDirection;
51 // measure child, should be a single scrolling child
52 foreach( LayoutItem childLayout in LayoutChildren )
54 if (childLayout != null)
57 // Use an Unspecified MeasureSpecification mode so scrolling child is not restricted to it's parents size in Height (for vertical scrolling)
58 // or Width for horizontal scrolling
59 MeasureSpecification unrestrictedMeasureSpec = new MeasureSpecification( heightMeasureSpec.Size, MeasureSpecification.ModeType.Unspecified);
61 if (scrollingDirection == Direction.Vertical)
63 MeasureChild( childLayout, widthMeasureSpec, unrestrictedMeasureSpec ); // Height unrestricted by parent
67 MeasureChild( childLayout, unrestrictedMeasureSpec, heightMeasureSpec ); // Width unrestricted by parent
70 float childWidth = childLayout.MeasuredWidth.Size.AsDecimal();
71 float childHeight = childLayout.MeasuredHeight.Size.AsDecimal();
73 // Determine the width and height needed by the children using their given position and size.
74 // Children could overlap so find the left most and right most child.
75 Position2D childPosition = childLayout.Owner.Position2D;
76 float childLeft = childPosition.X;
77 float childTop = childPosition.Y;
79 // Store current width and height needed to contain all children.
80 Extents childMargin = childLayout.Margin;
81 totalWidth = childWidth + childMargin.Start + childMargin.End;
82 totalHeight = childHeight + childMargin.Top + childMargin.Bottom;
84 if (childLayout.MeasuredWidth.State == MeasuredSize.StateType.MeasuredSizeTooSmall)
86 childWidthState = MeasuredSize.StateType.MeasuredSizeTooSmall;
88 if (childLayout.MeasuredWidth.State == MeasuredSize.StateType.MeasuredSizeTooSmall)
90 childHeightState = MeasuredSize.StateType.MeasuredSizeTooSmall;
96 MeasuredSize widthSizeAndState = ResolveSizeAndState(new LayoutLength(totalWidth), widthMeasureSpec, MeasuredSize.StateType.MeasuredSizeOK);
97 MeasuredSize heightSizeAndState = ResolveSizeAndState(new LayoutLength(totalHeight), heightMeasureSpec, MeasuredSize.StateType.MeasuredSizeOK);
98 totalWidth = widthSizeAndState.Size.AsDecimal();
99 totalHeight = heightSizeAndState.Size.AsDecimal();
101 // Ensure layout respects it's given minimum size
102 totalWidth = Math.Max( totalWidth, SuggestedMinimumWidth.AsDecimal() );
103 totalHeight = Math.Max( totalHeight, SuggestedMinimumHeight.AsDecimal() );
105 widthSizeAndState.State = childWidthState;
106 heightSizeAndState.State = childHeightState;
108 SetMeasuredDimensions( ResolveSizeAndState( new LayoutLength(totalWidth), widthMeasureSpec, childWidthState ),
109 ResolveSizeAndState( new LayoutLength(totalHeight), heightMeasureSpec, childHeightState ) );
113 protected override void OnLayout(bool changed, LayoutLength left, LayoutLength top, LayoutLength right, LayoutLength bottom)
115 foreach( LayoutItem childLayout in LayoutChildren )
117 if( childLayout != null )
119 LayoutLength childWidth = childLayout.MeasuredWidth.Size;
120 LayoutLength childHeight = childLayout.MeasuredHeight.Size;
122 Position2D childPosition = childLayout.Owner.Position2D;
123 Extents padding = Padding;
124 Extents childMargin = childLayout.Margin;
126 LayoutLength childLeft = new LayoutLength(childPosition.X + childMargin.Start + padding.Start);
127 LayoutLength childTop = new LayoutLength(childPosition.Y + childMargin.Top + padding.Top);
129 childLayout.Layout( childLeft, childTop, childLeft + childWidth, childTop + childHeight );
133 } // ScrollableBaseCustomLayout
136 /// The direction axis to scroll.
138 /// <since_tizen> 6 </since_tizen>
139 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API.
140 [EditorBrowsable(EditorBrowsableState.Never)]
141 public enum Direction
146 /// <since_tizen> 6 </since_tizen>
152 /// <since_tizen> 6 </since_tizen>
157 /// [Draft] Configurable speed threshold that register the gestures as a flick.
158 /// If the flick speed less than the threshold then will not be considered a flick.
160 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API.
161 [EditorBrowsable(EditorBrowsableState.Never)]
162 public float FlickThreshold { get; set; } = 0.2f;
165 /// [Draft] Configurable duration modifer for the flick animation.
166 /// Determines the speed of the scroll, large value results in a longer flick animation. Range (0.1 - 1.0)
168 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
169 [EditorBrowsable(EditorBrowsableState.Never)]
170 public float FlickAnimationSpeed { get; set; } = 0.4f;
173 /// [Draft] Configurable modifer for the distance to be scrolled when flicked detected.
174 /// It a ratio of the ScrollableBase's length. (not child's length).
175 /// First value is the ratio of the distance to scroll with the weakest flick.
176 /// Second value is the ratio of the distance to scroll with the strongest flick.
179 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
180 [EditorBrowsable(EditorBrowsableState.Never)]
181 public Vector2 FlickDistanceMultiplierRange { get; set; } = new Vector2(0.6f, 1.8f);
184 /// [Draft] Scrolling direction mode.
185 /// Default is Vertical scrolling.
187 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
188 [EditorBrowsable(EditorBrowsableState.Never)]
189 public Direction ScrollingDirection
193 return mScrollingDirection;
197 if(value != mScrollingDirection)
199 mScrollingDirection = value;
200 mPanGestureDetector.RemoveDirection(value == Direction.Horizontal ? PanGestureDetector.DirectionVertical : PanGestureDetector.DirectionHorizontal);
201 mPanGestureDetector.AddDirection(value == Direction.Horizontal ? PanGestureDetector.DirectionHorizontal : PanGestureDetector.DirectionVertical);
207 /// [Draft] Enable or disable scrolling.
209 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
210 [EditorBrowsable(EditorBrowsableState.Never)]
211 public bool ScrollEnabled
215 return mScrollEnabled;
219 if (value != mScrollEnabled)
221 mScrollEnabled = value;
224 mPanGestureDetector.Detected += OnPanGestureDetected;
225 mTapGestureDetector.Detected += OnTapGestureDetected;
229 mPanGestureDetector.Detected -= OnPanGestureDetected;
230 mTapGestureDetector.Detected -= OnTapGestureDetected;
237 /// [Draft] Pages mode, enables moving to the next or return to current page depending on pan displacement.
238 /// Default is false.
240 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
241 [EditorBrowsable(EditorBrowsableState.Never)]
242 public bool SnapToPage { set; get; } = false;
245 /// [Draft] Get current page.
246 /// Working propery with SnapToPage property.
248 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
249 [EditorBrowsable(EditorBrowsableState.Never)]
250 public int CurrentPage { get; private set; } = 0;
253 /// [Draft] Pages mode, Number of pages.
255 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
256 [EditorBrowsable(EditorBrowsableState.Never)]
257 public int NumberOfPages { set; get; } = 1;
260 /// [Draft] Duration of scroll animation.
262 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
263 [EditorBrowsable(EditorBrowsableState.Never)]
264 public int ScrollDuration { set; get; } = 125;
267 /// [Draft] Width of the Page.
269 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
270 [EditorBrowsable(EditorBrowsableState.Never)]
271 public int PageWidth { set; get; } = 1080; // Temporary use for prototype, should get ScrollableBase width
274 /// ScrollEventArgs is a class to record scroll event arguments which will sent to user.
276 /// <since_tizen> 6 </since_tizen>
277 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
278 [EditorBrowsable(EditorBrowsableState.Never)]
279 public class ScrollEventArgs : EventArgs
284 /// An event emitted when the scrolling starts, user can subscribe or unsubscribe to this event handler.<br />
286 /// <since_tizen> 6 </since_tizen>
287 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
288 [EditorBrowsable(EditorBrowsableState.Never)]
289 public event EventHandler<ScrollEventArgs> ScrollStartedEvent;
292 /// An event emitted when the scrolling ends, user can subscribe or unsubscribe to this event handler.<br />
294 /// <since_tizen> 6 </since_tizen>
295 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
296 [EditorBrowsable(EditorBrowsableState.Never)]
297 public event EventHandler<ScrollEventArgs> ScrollEndedEvent;
299 private Animation scrollAnimation;
300 private float maxScrollDistance;
301 private float childTargetPosition = 0.0f;
302 private PanGestureDetector mPanGestureDetector;
303 private TapGestureDetector mTapGestureDetector;
304 private View mScrollingChild;
305 private float multiplier =1.0f;
306 private bool scrolling = false;
307 private float ratioOfScreenWidthToCompleteScroll = 0.5f;
308 private float totalDisplacementForPan = 0.0f;
310 // If false then can only flick pages when the current animation/scroll as ended.
311 private bool flickWhenAnimating = false;
314 /// [Draft] Constructor
316 /// <since_tizen> 6 </since_tizen>
317 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
318 [EditorBrowsable(EditorBrowsableState.Never)]
319 public ScrollableBase() : base()
321 mPanGestureDetector = new PanGestureDetector();
322 mPanGestureDetector.Attach(this);
323 mPanGestureDetector.AddDirection(PanGestureDetector.DirectionVertical);
324 mPanGestureDetector.Detected += OnPanGestureDetected;
326 mTapGestureDetector = new TapGestureDetector();
327 mTapGestureDetector.Attach(this);
328 mTapGestureDetector.Detected += OnTapGestureDetected;
330 ClippingMode = ClippingModeType.ClipToBoundingBox;
332 mScrollingChild = new View();
334 Layout = new ScrollableBaseCustomLayout();
338 /// Called after a child has been added to the owning view.
340 /// <param name="view">The child which has been added.</param>
341 /// <since_tizen> 6 </since_tizen>
342 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
343 [EditorBrowsable(EditorBrowsableState.Never)]
344 public override void OnChildAdd(View view)
346 mScrollingChild = view;
348 if (Children.Count > 1)
349 Log.Error("ScrollableBase", $"Only 1 child should be added to ScrollableBase.");
354 /// Called after a child has been removed from the owning view.
356 /// <param name="view">The child which has been removed.</param>
357 /// <since_tizen> 6 </since_tizen>
358 /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
359 [EditorBrowsable(EditorBrowsableState.Never)]
360 public override void OnChildRemove(View view)
362 mScrollingChild = new View();
365 private void OnScrollStart()
367 ScrollEventArgs eventArgs = new ScrollEventArgs();
368 ScrollStartedEvent?.Invoke(this, eventArgs);
371 private void OnScrollEnd()
373 ScrollEventArgs eventArgs = new ScrollEventArgs();
374 ScrollEndedEvent?.Invoke(this, eventArgs);
377 private void StopScroll()
379 if (scrollAnimation != null)
381 if (scrollAnimation.State == Animation.States.Playing)
383 Debug.WriteLineIf(LayoutDebugScrollableBase, "StopScroll Animation Playing");
384 scrollAnimation.Stop(Animation.EndActions.Cancel);
387 scrollAnimation.Clear();
391 // static constructor registers the control type
392 static ScrollableBase()
394 // ViewRegistry registers control type with DALi type registry
395 // also uses introspection to find any properties that need to be registered with type registry
396 CustomViewRegistry.Instance.Register(CreateInstance, typeof(ScrollableBase));
399 internal static CustomView CreateInstance()
401 return new ScrollableBase();
404 private void AnimateChildTo(int duration, float axisPosition)
406 Debug.WriteLineIf(LayoutDebugScrollableBase, "AnimationTo Animation Duration:" + duration + " Destination:" + axisPosition);
408 StopScroll(); // Will replace previous animation so will stop existing one.
410 if (scrollAnimation == null)
412 scrollAnimation = new Animation();
413 scrollAnimation.Finished += ScrollAnimationFinished;
416 scrollAnimation.Duration = duration;
417 scrollAnimation.DefaultAlphaFunction = new AlphaFunction(AlphaFunction.BuiltinFunctions.EaseOutSine);
418 scrollAnimation.AnimateTo(mScrollingChild, (ScrollingDirection == Direction.Horizontal) ? "PositionX" : "PositionY", axisPosition);
421 scrollAnimation.Play();
424 private void ScrollBy(float displacement, bool animate)
426 if (GetChildCount() == 0 || displacement == 0 || maxScrollDistance < 0)
431 float childCurrentPosition = (ScrollingDirection == Direction.Horizontal) ? mScrollingChild.PositionX: mScrollingChild.PositionY;
433 Debug.WriteLineIf(LayoutDebugScrollableBase, "ScrollBy childCurrentPosition:" + childCurrentPosition +
434 " displacement:" + displacement,
435 " maxScrollDistance:" + maxScrollDistance );
437 childTargetPosition = childCurrentPosition + displacement; // child current position + gesture displacement
438 childTargetPosition = Math.Min(0,childTargetPosition);
439 childTargetPosition = Math.Max(-maxScrollDistance,childTargetPosition);
441 Debug.WriteLineIf( LayoutDebugScrollableBase, "ScrollBy currentAxisPosition:" + childCurrentPosition + "childTargetPosition:" + childTargetPosition);
445 // Calculate scroll animaton duration
446 float scrollDistance = 0.0f;
447 if (childCurrentPosition < childTargetPosition)
449 scrollDistance = Math.Abs(childCurrentPosition + childTargetPosition);
453 scrollDistance = Math.Abs(childCurrentPosition - childTargetPosition);
456 int duration = (int)((320*FlickAnimationSpeed) + (scrollDistance * FlickAnimationSpeed));
457 Debug.WriteLineIf(LayoutDebugScrollableBase, "Scroll Animation Duration:" + duration + " Distance:" + scrollDistance);
459 AnimateChildTo(duration, childTargetPosition);
463 // Set position of scrolling child without an animation
464 if (ScrollingDirection == Direction.Horizontal)
466 mScrollingChild.PositionX = childTargetPosition;
470 mScrollingChild.PositionY = childTargetPosition;
476 /// you can override it to clean-up your own resources.
478 /// <param name="type">DisposeTypes</param>
479 /// <since_tizen> 6 </since_tizen>
480 /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API.
481 [EditorBrowsable(EditorBrowsableState.Never)]
482 protected override void Dispose(DisposeTypes type)
489 if (type == DisposeTypes.Explicit)
493 if (mPanGestureDetector != null)
495 mPanGestureDetector.Detected -= OnPanGestureDetected;
496 mPanGestureDetector.Dispose();
497 mPanGestureDetector = null;
500 if (mTapGestureDetector != null)
502 mTapGestureDetector.Detected -= OnTapGestureDetected;
503 mTapGestureDetector.Dispose();
504 mTapGestureDetector = null;
510 private float CalculateDisplacementFromVelocity(float axisVelocity)
512 // Map: flick speed of range (2.0 - 6.0) to flick multiplier of range (0.7 - 1.6)
513 float speedMinimum = FlickThreshold;
514 float speedMaximum = FlickThreshold + 6.0f;
515 float multiplierMinimum = FlickDistanceMultiplierRange.X;
516 float multiplierMaximum = FlickDistanceMultiplierRange.Y;
518 float flickDisplacement = 0.0f;
520 float speed = Math.Min(4.0f,Math.Abs(axisVelocity));
522 Debug.WriteLineIf(LayoutDebugScrollableBase, "ScrollableBase Candidate Flick speed:" + speed);
524 if (speed > FlickThreshold)
526 // Flick length is the length of the ScrollableBase.
527 float flickLength = (ScrollingDirection == Direction.Horizontal) ?CurrentSize.Width:CurrentSize.Height;
529 // Calculate multiplier by mapping speed between the multiplier minimum and maximum.
530 multiplier =( (speed - speedMinimum) / ( (speedMaximum - speedMinimum) * (multiplierMaximum - multiplierMinimum) ) )+ multiplierMinimum;
532 // flick displacement is the product of the flick length and multiplier
533 flickDisplacement = ((flickLength * multiplier) * speed) / axisVelocity; // *speed and /velocity to perserve sign.
535 Debug.WriteLineIf(LayoutDebugScrollableBase, "Calculated FlickDisplacement[" + flickDisplacement +"] from speed[" + speed + "] multiplier:"
538 return flickDisplacement;
541 private float CalculateMaximumScrollDistance()
543 int scrollingChildLength = 0;
544 int scrollerLength = 0;
545 if (ScrollingDirection == Direction.Horizontal)
547 Debug.WriteLineIf(LayoutDebugScrollableBase, "Horizontal");
549 scrollingChildLength = (int)mScrollingChild.Layout.MeasuredWidth.Size.AsRoundedValue();
550 scrollerLength = CurrentSize.Width;
554 Debug.WriteLineIf(LayoutDebugScrollableBase, "Vertical");
555 scrollingChildLength = (int)mScrollingChild.Layout.MeasuredHeight.Size.AsRoundedValue();
556 scrollerLength = CurrentSize.Height;
559 Debug.WriteLineIf(LayoutDebugScrollableBase, "ScrollBy maxScrollDistance:" + (scrollingChildLength - scrollerLength) +
560 " parent length:" + scrollerLength +
561 " scrolling child length:" + scrollingChildLength);
563 return scrollingChildLength - scrollerLength;
566 private void PageSnap()
568 Debug.WriteLineIf(LayoutDebugScrollableBase, "PageSnap with pan candidate totalDisplacement:" + totalDisplacementForPan +
569 " currentPage[" + CurrentPage + "]" );
571 //Increment current page if total displacement enough to warrant a page change.
572 if (Math.Abs(totalDisplacementForPan) > (PageWidth * ratioOfScreenWidthToCompleteScroll))
574 if (totalDisplacementForPan < 0)
576 CurrentPage = Math.Min(NumberOfPages - 1, ++CurrentPage);
580 CurrentPage = Math.Max(0, --CurrentPage);
584 // Animate to new page or reposition to current page
585 int destinationX = -(CurrentPage * PageWidth);
586 Debug.WriteLineIf(LayoutDebugScrollableBase, "Snapping to page[" + CurrentPage + "] to:"+ destinationX + " from:" + mScrollingChild.PositionX);
587 AnimateChildTo(ScrollDuration, destinationX);
590 private void Flick(float flickDisplacement)
594 if ( ( flickWhenAnimating && scrolling == true) || ( scrolling == false) )
596 if(flickDisplacement < 0)
598 CurrentPage = Math.Min(NumberOfPages - 1, CurrentPage + 1);
599 Debug.WriteLineIf(LayoutDebugScrollableBase, "Snap - to page:" + CurrentPage);
603 CurrentPage = Math.Max(0, CurrentPage - 1);
604 Debug.WriteLineIf(LayoutDebugScrollableBase, "Snap + to page:" + CurrentPage);
606 float targetPosition = -(CurrentPage* PageWidth); // page size
607 Debug.WriteLineIf(LayoutDebugScrollableBase, "Snapping to :" + targetPosition);
608 AnimateChildTo(ScrollDuration,targetPosition);
613 ScrollBy(flickDisplacement, true); // Animate flickDisplacement.
617 private void OnPanGestureDetected(object source, PanGestureDetector.DetectedEventArgs e)
619 if (e.PanGesture.State == Gesture.StateType.Started)
621 Debug.WriteLineIf(LayoutDebugScrollableBase, "Gesture Start");
622 if (scrolling && !SnapToPage)
626 maxScrollDistance = CalculateMaximumScrollDistance();
627 totalDisplacementForPan = 0.0f;
629 else if (e.PanGesture.State == Gesture.StateType.Continuing)
631 if (ScrollingDirection == Direction.Horizontal)
633 ScrollBy(e.PanGesture.Displacement.X, false);
634 totalDisplacementForPan += e.PanGesture.Displacement.X;
638 ScrollBy(e.PanGesture.Displacement.Y, false);
639 totalDisplacementForPan += e.PanGesture.Displacement.Y;
641 Debug.WriteLineIf(LayoutDebugScrollableBase, "OnPanGestureDetected Continue totalDisplacementForPan:" + totalDisplacementForPan);
644 else if (e.PanGesture.State == Gesture.StateType.Finished)
646 float axisVelocity = (ScrollingDirection == Direction.Horizontal) ? e.PanGesture.Velocity.X : e.PanGesture.Velocity.Y;
647 float flickDisplacement = CalculateDisplacementFromVelocity(axisVelocity);
649 Debug.WriteLineIf(LayoutDebugScrollableBase, "FlickDisplacement:" + flickDisplacement + "TotalDisplacementForPan:" + totalDisplacementForPan);
651 if (flickDisplacement > 0 | flickDisplacement < 0)// Flick detected
653 Flick(flickDisplacement);
657 // End of panning gesture but was not a flick
663 totalDisplacementForPan = 0;
667 private new void OnTapGestureDetected(object source, TapGestureDetector.DetectedEventArgs e)
669 if (e.TapGesture.Type == Gesture.GestureType.Tap)
671 // Stop scrolling if tap detected (press then relase).
672 // Unless in Pages mode, do not want a page change to stop part way.
673 if(scrolling && !SnapToPage)
680 private void ScrollAnimationFinished(object sender, EventArgs e)