21952fb32bc8904c9f6dd3997930776254f2a225
[platform/core/csapi/tizenfx.git] / src / Tizen.NUI.Components / Controls / ScrollableBase.cs
1 /* Copyright (c) 2020 Samsung Electronics Co., Ltd.
2  *
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
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
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.
14  *
15  */
16 using System;
17 using Tizen.NUI.BaseComponents;
18 using System.ComponentModel;
19 using System.Diagnostics;
20
21 namespace Tizen.NUI.Components
22 {
23     /// <summary>
24     /// [Draft] This class provides a View that can scroll a single View with a layout. This View can be a nest of Views.
25     /// </summary>
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
29     {
30         static bool LayoutDebugScrollableBase = false; // Debug flag
31         private Direction mScrollingDirection = Direction.Vertical;
32         private bool mScrollEnabled = true;
33         private int mPageWidth = 0;
34
35         private class ScrollableBaseCustomLayout : LayoutGroup
36         {
37             protected override void OnMeasure(MeasureSpecification widthMeasureSpec, MeasureSpecification heightMeasureSpec)
38             {
39                 Extents padding = Padding;
40                 float totalHeight = padding.Top + padding.Bottom;
41                 float totalWidth = padding.Start + padding.End;
42
43                 MeasuredSize.StateType childWidthState = MeasuredSize.StateType.MeasuredSizeOK;
44                 MeasuredSize.StateType childHeightState = MeasuredSize.StateType.MeasuredSizeOK;
45
46                 Direction scrollingDirection = Direction.Vertical;
47                 ScrollableBase scrollableBase = this.Owner as ScrollableBase;
48                 if (scrollableBase)
49                 {
50                     scrollingDirection = scrollableBase.ScrollingDirection;
51                 }
52
53                 // measure child, should be a single scrolling child
54                 foreach (LayoutItem childLayout in LayoutChildren)
55                 {
56                     if (childLayout != null)
57                     {
58                         // Get size of child
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);
62
63                         if (scrollingDirection == Direction.Vertical)
64                         {
65                             MeasureChildWithMargins(childLayout, widthMeasureSpec, new LayoutLength(0), unrestrictedMeasureSpec, new LayoutLength(0));  // Height unrestricted by parent
66                         }
67                         else
68                         {
69                             MeasureChildWithMargins(childLayout, unrestrictedMeasureSpec, new LayoutLength(0), heightMeasureSpec, new LayoutLength(0));  // Width unrestricted by parent
70                         }
71
72                         float childWidth = childLayout.MeasuredWidth.Size.AsDecimal();
73                         float childHeight = childLayout.MeasuredHeight.Size.AsDecimal();
74
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;
80
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;
85
86                         if (childLayout.MeasuredWidth.State == MeasuredSize.StateType.MeasuredSizeTooSmall)
87                         {
88                             childWidthState = MeasuredSize.StateType.MeasuredSizeTooSmall;
89                         }
90                         if (childLayout.MeasuredWidth.State == MeasuredSize.StateType.MeasuredSizeTooSmall)
91                         {
92                             childHeightState = MeasuredSize.StateType.MeasuredSizeTooSmall;
93                         }
94                     }
95                 }
96
97
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();
102
103                 // Ensure layout respects it's given minimum size
104                 totalWidth = Math.Max(totalWidth, SuggestedMinimumWidth.AsDecimal());
105                 totalHeight = Math.Max(totalHeight, SuggestedMinimumHeight.AsDecimal());
106
107                 widthSizeAndState.State = childWidthState;
108                 heightSizeAndState.State = childHeightState;
109
110                 SetMeasuredDimensions(ResolveSizeAndState(new LayoutLength(totalWidth + Padding.Start + Padding.End), widthMeasureSpec, childWidthState),
111                                        ResolveSizeAndState(new LayoutLength(totalHeight + Padding.Top + Padding.Bottom), heightMeasureSpec, childHeightState));
112
113                 // Size of ScrollableBase is changed. Change Page width too.
114                 scrollableBase.mPageWidth = (int)MeasuredWidth.Size.AsRoundedValue();
115             }
116
117             protected override void OnLayout(bool changed, LayoutLength left, LayoutLength top, LayoutLength right, LayoutLength bottom)
118             {
119                 foreach (LayoutItem childLayout in LayoutChildren)
120                 {
121                     if (childLayout != null)
122                     {
123                         LayoutLength childWidth = childLayout.MeasuredWidth.Size;
124                         LayoutLength childHeight = childLayout.MeasuredHeight.Size;
125
126                         Position2D childPosition = childLayout.Owner.Position2D;
127                         Extents padding = Padding;
128                         Extents childMargin = childLayout.Margin;
129
130                         LayoutLength childLeft = new LayoutLength(childPosition.X + childMargin.Start + padding.Start);
131                         LayoutLength childTop = new LayoutLength(childPosition.Y + childMargin.Top + padding.Top);
132
133                         childLayout.Layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight);
134                     }
135                 }
136             }
137         } //  ScrollableBaseCustomLayout
138
139         /// <summary>
140         /// The direction axis to scroll.
141         /// </summary>
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
146         {
147             /// <summary>
148             /// Horizontal axis.
149             /// </summary>
150             /// <since_tizen> 6 </since_tizen>
151             Horizontal,
152
153             /// <summary>
154             /// Vertical axis.
155             /// </summary>
156             /// <since_tizen> 6 </since_tizen>
157             Vertical
158         }
159
160         /// <summary>
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.
163         /// </summary>
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;
167
168         /// <summary>
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)
171         /// </summary>
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;
175
176         /// <summary>
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.
181         /// Second > First.
182         /// </summary>
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);
186
187         /// <summary>
188         /// [Draft] Scrolling direction mode.
189         /// Default is Vertical scrolling.
190         /// </summary>
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
194         {
195             get
196             {
197                 return mScrollingDirection;
198             }
199             set
200             {
201                 if (value != mScrollingDirection)
202                 {
203                     mScrollingDirection = value;
204                     mPanGestureDetector.RemoveDirection(value == Direction.Horizontal ? PanGestureDetector.DirectionVertical : PanGestureDetector.DirectionHorizontal);
205                     mPanGestureDetector.AddDirection(value == Direction.Horizontal ? PanGestureDetector.DirectionHorizontal : PanGestureDetector.DirectionVertical);
206                 }
207             }
208         }
209
210         /// <summary>
211         /// [Draft] Enable or disable scrolling.
212         /// </summary>
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
216         {
217             get
218             {
219                 return mScrollEnabled;
220             }
221             set
222             {
223                 if (value != mScrollEnabled)
224                 {
225                     mScrollEnabled = value;
226                     if (mScrollEnabled)
227                     {
228                         mPanGestureDetector.Detected += OnPanGestureDetected;
229                         mTapGestureDetector.Detected += OnTapGestureDetected;
230                     }
231                     else
232                     {
233                         mPanGestureDetector.Detected -= OnPanGestureDetected;
234                         mTapGestureDetector.Detected -= OnTapGestureDetected;
235                     }
236                 }
237             }
238         }
239
240         /// <summary>
241         /// [Draft] Pages mode, enables moving to the next or return to current page depending on pan displacement.
242         /// Default is false.
243         /// </summary>
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;
247
248         /// <summary>
249         /// [Draft] Get current page.
250         /// Working propery with SnapToPage property.
251         /// </summary>
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;
255
256         /// <summary>
257         /// [Draft] Duration of scroll animation.
258         /// </summary>
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)]
261
262         public int ScrollDuration { set; get; } = 125;
263         /// <summary>
264         /// [Draft] Scroll Available area.
265         /// </summary>
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; }
269
270         /// <summary>
271         /// ScrollEventArgs is a class to record scroll event arguments which will sent to user.
272         /// </summary>
273         /// <since_tizen> 6 </since_tizen>
274         /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
275         [EditorBrowsable(EditorBrowsableState.Never)]
276         public class ScrollEventArgs : EventArgs
277         {
278             Position position;
279
280             /// <summary>
281             /// Default constructor.
282             /// </summary>
283             /// <param name="position">Current scroll position</param>
284             /// <since_tizen> 6 </since_tizen>
285             /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
286             public ScrollEventArgs(Position position)
287             {
288                 this.position = position;
289             }
290
291             /// <summary>
292             /// [Draft] Current scroll position.
293             /// </summary>
294             /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
295             [EditorBrowsable(EditorBrowsableState.Never)]
296             public Position Position
297             {
298                 get
299                 {
300                     return position;
301                 }
302             }
303         }
304
305         /// <summary>
306         /// An event emitted when user starts dragging ScrollableBase, user can subscribe or unsubscribe to this event handler.<br />
307         /// </summary>
308         /// <since_tizen> 6 </since_tizen>
309         /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
310         [EditorBrowsable(EditorBrowsableState.Never)]
311         public event EventHandler<ScrollEventArgs> ScrollDragStartEvent;
312
313         /// <summary>
314         /// An event emitted when user stops dragging ScrollableBase, user can subscribe or unsubscribe to this event handler.<br />
315         /// </summary>
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 event EventHandler<ScrollEventArgs> ScrollDragEndEvent;
320
321
322         /// <summary>
323         /// An event emitted when the scrolling slide animation starts, user can subscribe or unsubscribe to this event handler.<br />
324         /// </summary>
325         /// <since_tizen> 6 </since_tizen>
326         /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
327         [EditorBrowsable(EditorBrowsableState.Never)]
328         public event EventHandler<ScrollEventArgs> ScrollAnimationStartEvent;
329
330         /// <summary>
331         /// An event emitted when the scrolling slide animation ends, user can subscribe or unsubscribe to this event handler.<br />
332         /// </summary>
333         /// <since_tizen> 6 </since_tizen>
334         /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
335         [EditorBrowsable(EditorBrowsableState.Never)]
336         public event EventHandler<ScrollEventArgs> ScrollAnimationEndEvent;
337
338
339         /// <summary>
340         /// An event emitted when scrolling, user can subscribe or unsubscribe to this event handler.<br />
341         /// </summary>
342         /// <since_tizen> 6 </since_tizen>
343         /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
344         [EditorBrowsable(EditorBrowsableState.Never)]
345         public event EventHandler<ScrollEventArgs> ScrollEvent;
346
347         private Animation scrollAnimation;
348         private float maxScrollDistance;
349         private float childTargetPosition = 0.0f;
350         private PanGestureDetector mPanGestureDetector;
351         private TapGestureDetector mTapGestureDetector;
352         private View mScrollingChild;
353         private View mInterruptTouchingChild;
354         private float multiplier = 1.0f;
355         private bool scrolling = false;
356         private float ratioOfScreenWidthToCompleteScroll = 0.5f;
357         private float totalDisplacementForPan = 0.0f;
358
359         // If false then can only flick pages when the current animation/scroll as ended.
360         private bool flickWhenAnimating = false;
361         private PropertyNotification propertyNotification;
362
363         // Let's consider more whether this needs to be set as protected.
364         private float finalTargetPosition;
365
366         /// <summary>
367         /// [Draft] Constructor
368         /// </summary>
369         /// <since_tizen> 6 </since_tizen>
370         /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
371         [EditorBrowsable(EditorBrowsableState.Never)]
372         public ScrollableBase() : base()
373         {
374             mPanGestureDetector = new PanGestureDetector();
375             mPanGestureDetector.Attach(this);
376             mPanGestureDetector.AddDirection(PanGestureDetector.DirectionVertical);
377             mPanGestureDetector.Detected += OnPanGestureDetected;
378
379             mTapGestureDetector = new TapGestureDetector();
380             mTapGestureDetector.Attach(this);
381             mTapGestureDetector.Detected += OnTapGestureDetected;
382
383             ClippingMode = ClippingModeType.ClipChildren;
384
385             mScrollingChild = new View();
386             mScrollingChild.Name = "DefaultScrollingChild";
387
388             //Interrupt touching when panning is started;
389             mInterruptTouchingChild = new View()
390             {
391                 Name = "InterruptTouchingChild",
392                 Size = new Size(Window.Instance.WindowSize),
393                 BackgroundColor = Color.Transparent,
394             };
395
396             mInterruptTouchingChild.TouchEvent += OnIterruptTouchingChildTouched;
397
398             Layout = new ScrollableBaseCustomLayout();
399         }
400
401         private bool OnIterruptTouchingChildTouched(object source, View.TouchEventArgs args)
402         {
403             return true;
404         }
405
406         private void OnPropertyChanged(object source, PropertyNotification.NotifyEventArgs args)
407         {
408             OnScroll();
409         }
410
411         /// <summary>
412         /// Called after a child has been added to the owning view.
413         /// </summary>
414         /// <param name="view">The child which has been added.</param>
415         /// <since_tizen> 6 </since_tizen>
416         /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
417         [EditorBrowsable(EditorBrowsableState.Never)]
418         public override void OnChildAdd(View view)
419         {
420             if (view.Name != "InterruptTouchingChild")
421             {
422                 if (mScrollingChild.Name != "DefaultScrollingChild")
423                 {
424                     propertyNotification.Notified -= OnPropertyChanged;
425                     mScrollingChild.RemovePropertyNotification(propertyNotification);
426                     mScrollingChild.Relayout -= OnScrollingChildRelayout;
427                 }
428
429                 mScrollingChild = view;
430                 mScrollingChild.Layout.SetPositionByLayout = false;
431                 propertyNotification = mScrollingChild?.AddPropertyNotification("position", PropertyCondition.Step(1.0f));
432                 propertyNotification.Notified += OnPropertyChanged;
433                 mScrollingChild.Relayout += OnScrollingChildRelayout;
434             }
435         }
436
437         /// <summary>
438         /// Called after a child has been removed from the owning view.
439         /// </summary>
440         /// <param name="view">The child which has been removed.</param>
441         /// <since_tizen> 6 </since_tizen>
442         /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
443         [EditorBrowsable(EditorBrowsableState.Never)]
444         public override void OnChildRemove(View view)
445         {
446             if (view.Name != "InterruptTouchingChild")
447             {
448                 propertyNotification.Notified -= OnPropertyChanged;
449                 mScrollingChild.RemovePropertyNotification(propertyNotification);
450                 mScrollingChild.Relayout -= OnScrollingChildRelayout;
451
452                 mScrollingChild.Layout.SetPositionByLayout = true;
453                 mScrollingChild = new View();
454             }
455         }
456
457         private void OnScrollingChildRelayout(object source, EventArgs args)
458         {
459             // Size is changed. Calculate maxScrollDistance.
460             maxScrollDistance = CalculateMaximumScrollDistance();
461         }
462
463         /// <summary>
464         /// Scrolls to the item at the specified index.
465         /// </summary>
466         /// <param name="index">Index of item.</param>
467         /// <since_tizen> 6 </since_tizen>
468         /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
469         [EditorBrowsable(EditorBrowsableState.Never)]
470         public void ScrollToIndex(int index)
471         {
472             if (mScrollingChild.ChildCount - 1 < index || index < 0)
473             {
474                 return;
475             }
476
477             if (SnapToPage)
478             {
479                 CurrentPage = index;
480             }
481
482             float targetPosition = Math.Min(ScrollingDirection == Direction.Vertical ? mScrollingChild.Children[index].Position.Y : mScrollingChild.Children[index].Position.X, maxScrollDistance);
483             AnimateChildTo(ScrollDuration, -targetPosition);
484         }
485
486         private void OnScrollDragStart()
487         {
488             ScrollEventArgs eventArgs = new ScrollEventArgs(mScrollingChild.CurrentPosition);
489             ScrollDragStartEvent?.Invoke(this, eventArgs);
490         }
491
492         private void OnScrollDragEnd()
493         {
494             ScrollEventArgs eventArgs = new ScrollEventArgs(mScrollingChild.CurrentPosition);
495             ScrollDragEndEvent?.Invoke(this, eventArgs);
496         }
497
498         private void OnScrollAnimationStart()
499         {
500             ScrollEventArgs eventArgs = new ScrollEventArgs(mScrollingChild.CurrentPosition);
501             ScrollAnimationStartEvent?.Invoke(this, eventArgs);
502         }
503
504         private void OnScrollAnimationEnd()
505         {
506             ScrollEventArgs eventArgs = new ScrollEventArgs(mScrollingChild.CurrentPosition);
507             ScrollAnimationEndEvent?.Invoke(this, eventArgs);
508         }
509
510         private bool readyToNotice = false;
511
512         private float noticeAnimationEndBeforePosition = 0.0f;
513         // Let's consider more whether this needs to be set as protected.
514         public float NoticeAnimationEndBeforePosition { get => noticeAnimationEndBeforePosition; set => noticeAnimationEndBeforePosition = value; }
515
516         private void OnScroll()
517         {
518             ScrollEventArgs eventArgs = new ScrollEventArgs(mScrollingChild.CurrentPosition);
519             ScrollEvent?.Invoke(this, eventArgs);
520
521             CheckPreReachedTargetPosition();
522         }
523
524         private void CheckPreReachedTargetPosition()
525         {
526             // Check whether we reached pre-reached target position
527             if (readyToNotice &&
528                 mScrollingChild.CurrentPosition.Y <= finalTargetPosition + NoticeAnimationEndBeforePosition &&
529                 mScrollingChild.CurrentPosition.Y >= finalTargetPosition - NoticeAnimationEndBeforePosition)
530             {
531                 //Notice first
532                 readyToNotice = false;
533                 OnPreReachedTargetPosition(finalTargetPosition);
534             }
535         }
536
537         /// <summary>
538         /// This helps developer who wants to know before scroll is reaching target position.
539         /// </summary>
540         /// <param name="targetPosition">Index of item.</param>
541         /// <since_tizen> 6 </since_tizen>
542         /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
543         [EditorBrowsable(EditorBrowsableState.Never)]
544         protected virtual void OnPreReachedTargetPosition(float targetPosition)
545         {
546
547         }
548
549         private void StopScroll()
550         {
551             if (scrollAnimation != null)
552             {
553                 if (scrollAnimation.State == Animation.States.Playing)
554                 {
555                     Debug.WriteLineIf(LayoutDebugScrollableBase, "StopScroll Animation Playing");
556                     scrollAnimation.Stop(Animation.EndActions.Cancel);
557                     OnScrollAnimationEnd();
558                 }
559                 scrollAnimation.Clear();
560             }
561         }
562
563         // static constructor registers the control type
564         static ScrollableBase()
565         {
566             // ViewRegistry registers control type with DALi type registry
567             // also uses introspection to find any properties that need to be registered with type registry
568             CustomViewRegistry.Instance.Register(CreateInstance, typeof(ScrollableBase));
569         }
570
571         internal static CustomView CreateInstance()
572         {
573             return new ScrollableBase();
574         }
575
576         private void AnimateChildTo(int duration, float axisPosition)
577         {
578             Debug.WriteLineIf(LayoutDebugScrollableBase, "AnimationTo Animation Duration:" + duration + " Destination:" + axisPosition);
579             finalTargetPosition = axisPosition;
580
581             StopScroll(); // Will replace previous animation so will stop existing one.
582
583             if (scrollAnimation == null)
584             {
585                 scrollAnimation = new Animation();
586                 scrollAnimation.Finished += ScrollAnimationFinished;
587             }
588
589             scrollAnimation.Duration = duration;
590             scrollAnimation.DefaultAlphaFunction = new AlphaFunction(AlphaFunction.BuiltinFunctions.EaseOutSine);
591             scrollAnimation.AnimateTo(mScrollingChild, (ScrollingDirection == Direction.Horizontal) ? "PositionX" : "PositionY", axisPosition);
592             scrolling = true;
593             OnScrollAnimationStart();
594             scrollAnimation.Play();
595         }
596
597         /// <summary>
598         /// Scroll to specific position with or without animation.
599         /// </summary>
600         /// <param name="position">Destination.</param>
601         /// <param name="animate">Scroll with or without animation</param>
602         [EditorBrowsable(EditorBrowsableState.Never)]
603         public void ScrollTo(float position, bool animate)
604         {
605             float currentPositionX = mScrollingChild.CurrentPosition.X != 0 ? mScrollingChild.CurrentPosition.X : mScrollingChild.Position.X;
606             float currentPositionY = mScrollingChild.CurrentPosition.Y != 0 ? mScrollingChild.CurrentPosition.Y : mScrollingChild.Position.Y;
607             float delta = ScrollingDirection == Direction.Horizontal ? currentPositionX : currentPositionY;
608             // The argument position is the new pan position. So the new position of ScrollableBase becomes (-position).
609             // To move ScrollableBase's position to (-position), it moves by (-position - currentPosition).
610             delta = -position - delta;
611
612             ScrollBy(delta, animate);
613         }
614
615         private float BoundScrollPosition(float targetPosition)
616         {
617             if (ScrollAvailableArea != null)
618             {
619                 float minScrollPosition = ScrollAvailableArea.X;
620                 float maxScrollPosition = ScrollAvailableArea.Y;
621
622                 targetPosition = Math.Min(-minScrollPosition, targetPosition);
623                 targetPosition = Math.Max(-maxScrollPosition, targetPosition);
624             }
625             else
626             {
627                 targetPosition = Math.Min(0, targetPosition);
628                 targetPosition = Math.Max(-maxScrollDistance, targetPosition);
629             }
630
631             return targetPosition;
632         }
633
634         private void ScrollBy(float displacement, bool animate)
635         {
636             if (GetChildCount() == 0 || maxScrollDistance < 0)
637             {
638                 return;
639             }
640
641             float childCurrentPosition = (ScrollingDirection == Direction.Horizontal) ? mScrollingChild.PositionX : mScrollingChild.PositionY;
642
643             Debug.WriteLineIf(LayoutDebugScrollableBase, "ScrollBy childCurrentPosition:" + childCurrentPosition +
644                                                    " displacement:" + displacement,
645                                                    " maxScrollDistance:" + maxScrollDistance);
646
647             childTargetPosition = childCurrentPosition + displacement; // child current position + gesture displacement
648
649
650             Debug.WriteLineIf(LayoutDebugScrollableBase, "ScrollBy currentAxisPosition:" + childCurrentPosition + "childTargetPosition:" + childTargetPosition);
651
652             if (animate)
653             {
654                 // Calculate scroll animaton duration
655                 float scrollDistance = Math.Abs(displacement);
656                 int duration = (int)((320 * FlickAnimationSpeed) + (scrollDistance * FlickAnimationSpeed));
657                 Debug.WriteLineIf(LayoutDebugScrollableBase, "Scroll Animation Duration:" + duration + " Distance:" + scrollDistance);
658
659                 readyToNotice = true;
660
661                 AnimateChildTo(duration, BoundScrollPosition(AdjustTargetPositionOfScrollAnimation(BoundScrollPosition(childTargetPosition))));
662             }
663             else
664             {
665                 finalTargetPosition = BoundScrollPosition(childTargetPosition);
666
667                 // Set position of scrolling child without an animation
668                 if (ScrollingDirection == Direction.Horizontal)
669                 {
670                     mScrollingChild.PositionX = finalTargetPosition;
671                 }
672                 else
673                 {
674                     mScrollingChild.PositionY = finalTargetPosition;
675                 }
676
677             }
678         }
679
680         /// <summary>
681         /// you can override it to clean-up your own resources.
682         /// </summary>
683         /// <param name="type">DisposeTypes</param>
684         /// <since_tizen> 6 </since_tizen>
685         /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API.
686         [EditorBrowsable(EditorBrowsableState.Never)]
687         protected override void Dispose(DisposeTypes type)
688         {
689             if (disposed)
690             {
691                 return;
692             }
693
694             if (type == DisposeTypes.Explicit)
695             {
696                 StopScroll();
697
698                 if (mPanGestureDetector != null)
699                 {
700                     mPanGestureDetector.Detected -= OnPanGestureDetected;
701                     mPanGestureDetector.Dispose();
702                     mPanGestureDetector = null;
703                 }
704
705                 if (mTapGestureDetector != null)
706                 {
707                     mTapGestureDetector.Detected -= OnTapGestureDetected;
708                     mTapGestureDetector.Dispose();
709                     mTapGestureDetector = null;
710                 }
711             }
712             base.Dispose(type);
713         }
714
715         private float CalculateDisplacementFromVelocity(float axisVelocity)
716         {
717             // Map: flick speed of range (2.0 - 6.0) to flick multiplier of range (0.7 - 1.6)
718             float speedMinimum = FlickThreshold;
719             float speedMaximum = FlickThreshold + 6.0f;
720             float multiplierMinimum = FlickDistanceMultiplierRange.X;
721             float multiplierMaximum = FlickDistanceMultiplierRange.Y;
722
723             float flickDisplacement = 0.0f;
724
725             float speed = Math.Min(4.0f, Math.Abs(axisVelocity));
726
727             Debug.WriteLineIf(LayoutDebugScrollableBase, "ScrollableBase Candidate Flick speed:" + speed);
728
729             if (speed > FlickThreshold)
730             {
731                 // Flick length is the length of the ScrollableBase.
732                 float flickLength = (ScrollingDirection == Direction.Horizontal) ? CurrentSize.Width : CurrentSize.Height;
733
734                 // Calculate multiplier by mapping speed between the multiplier minimum and maximum.
735                 multiplier = ((speed - speedMinimum) / ((speedMaximum - speedMinimum) * (multiplierMaximum - multiplierMinimum))) + multiplierMinimum;
736
737                 // flick displacement is the product of the flick length and multiplier
738                 flickDisplacement = ((flickLength * multiplier) * speed) / axisVelocity;  // *speed and /velocity to perserve sign.
739
740                 Debug.WriteLineIf(LayoutDebugScrollableBase, "Calculated FlickDisplacement[" + flickDisplacement + "] from speed[" + speed + "] multiplier:"
741                                                         + multiplier);
742             }
743             return flickDisplacement;
744         }
745
746         private float CalculateMaximumScrollDistance()
747         {
748             int scrollingChildLength = 0;
749             int scrollerLength = 0;
750             if (ScrollingDirection == Direction.Horizontal)
751             {
752                 Debug.WriteLineIf(LayoutDebugScrollableBase, "Horizontal");
753
754                 scrollingChildLength = (int)mScrollingChild.Layout.MeasuredWidth.Size.AsRoundedValue();
755                 scrollerLength = CurrentSize.Width;
756             }
757             else
758             {
759                 Debug.WriteLineIf(LayoutDebugScrollableBase, "Vertical");
760                 scrollingChildLength = (int)mScrollingChild.Layout.MeasuredHeight.Size.AsRoundedValue();
761                 scrollerLength = CurrentSize.Height;
762             }
763
764             Debug.WriteLineIf(LayoutDebugScrollableBase, "ScrollBy maxScrollDistance:" + (scrollingChildLength - scrollerLength) +
765                                                    " parent length:" + scrollerLength +
766                                                    " scrolling child length:" + scrollingChildLength);
767
768             return Math.Max(scrollingChildLength - scrollerLength, 0);
769         }
770
771         private void PageSnap()
772         {
773             Debug.WriteLineIf(LayoutDebugScrollableBase, "PageSnap with pan candidate totalDisplacement:" + totalDisplacementForPan +
774                                                                 " currentPage[" + CurrentPage + "]");
775
776             //Increment current page if total displacement enough to warrant a page change.
777             if (Math.Abs(totalDisplacementForPan) > (mPageWidth * ratioOfScreenWidthToCompleteScroll))
778             {
779                 if (totalDisplacementForPan < 0)
780                 {
781                     CurrentPage = Math.Min(Math.Max(mScrollingChild.Children.Count - 1, 0), ++CurrentPage);
782                 }
783                 else
784                 {
785                     CurrentPage = Math.Max(0, --CurrentPage);
786                 }
787             }
788
789             // Animate to new page or reposition to current page
790             float destinationX = -(mScrollingChild.Children[CurrentPage].Position.X + mScrollingChild.Children[CurrentPage].CurrentSize.Width / 2 - CurrentSize.Width / 2); // set to middle of current page
791             Debug.WriteLineIf(LayoutDebugScrollableBase, "Snapping to page[" + CurrentPage + "] to:" + destinationX + " from:" + mScrollingChild.PositionX);
792             AnimateChildTo(ScrollDuration, destinationX);
793         }
794
795         private void Flick(float flickDisplacement)
796         {
797             if (SnapToPage)
798             {
799                 if ((flickWhenAnimating && scrolling == true) || (scrolling == false))
800                 {
801                     if (flickDisplacement < 0)
802                     {
803                         CurrentPage = Math.Min(Math.Max(mScrollingChild.Children.Count - 1, 0), CurrentPage + 1);
804                         Debug.WriteLineIf(LayoutDebugScrollableBase, "Snap - to page:" + CurrentPage);
805                     }
806                     else
807                     {
808                         CurrentPage = Math.Max(0, CurrentPage - 1);
809                         Debug.WriteLineIf(LayoutDebugScrollableBase, "Snap + to page:" + CurrentPage);
810                     }
811
812                     float destinationX = -(mScrollingChild.Children[CurrentPage].Position.X + mScrollingChild.Children[CurrentPage].CurrentSize.Width / 2.0f - CurrentSize.Width / 2.0f); // set to middle of current page
813                     Debug.WriteLineIf(LayoutDebugScrollableBase, "Snapping to :" + destinationX);
814                     AnimateChildTo(ScrollDuration, destinationX);
815                 }
816             }
817             else
818             {
819                 ScrollBy(flickDisplacement, true); // Animate flickDisplacement.
820             }
821         }
822
823         private void OnPanGestureDetected(object source, PanGestureDetector.DetectedEventArgs e)
824         {
825             if (e.PanGesture.State == Gesture.StateType.Started)
826             {
827                 Add(mInterruptTouchingChild);
828                 Debug.WriteLineIf(LayoutDebugScrollableBase, "Gesture Start");
829                 if (scrolling && !SnapToPage)
830                 {
831                     StopScroll();
832                 }
833                 totalDisplacementForPan = 0.0f;
834                 OnScrollDragStart();
835             }
836             else if (e.PanGesture.State == Gesture.StateType.Continuing)
837             {
838                 if (ScrollingDirection == Direction.Horizontal)
839                 {
840                     ScrollBy(e.PanGesture.Displacement.X, false);
841                     totalDisplacementForPan += e.PanGesture.Displacement.X;
842                 }
843                 else
844                 {
845                     ScrollBy(e.PanGesture.Displacement.Y, false);
846                     totalDisplacementForPan += e.PanGesture.Displacement.Y;
847                 }
848                 Debug.WriteLineIf(LayoutDebugScrollableBase, "OnPanGestureDetected Continue totalDisplacementForPan:" + totalDisplacementForPan);
849             }
850             else if (e.PanGesture.State == Gesture.StateType.Finished)
851             {
852                 float axisVelocity = (ScrollingDirection == Direction.Horizontal) ? e.PanGesture.Velocity.X : e.PanGesture.Velocity.Y;
853                 float flickDisplacement = CalculateDisplacementFromVelocity(axisVelocity);
854
855                 Debug.WriteLineIf(LayoutDebugScrollableBase, "FlickDisplacement:" + flickDisplacement + "TotalDisplacementForPan:" + totalDisplacementForPan);
856                 OnScrollDragEnd();
857
858                 if (flickDisplacement > 0 | flickDisplacement < 0)// Flick detected
859                 {
860                     Flick(flickDisplacement);
861                 }
862                 else
863                 {
864                     // End of panning gesture but was not a flick
865                     if (SnapToPage)
866                     {
867                         PageSnap();
868                     }
869                     else
870                     {
871                         ScrollBy(0, true);
872                     }
873                 }
874                 totalDisplacementForPan = 0;
875
876                 Remove(mInterruptTouchingChild);
877             }
878         }
879
880         private new void OnTapGestureDetected(object source, TapGestureDetector.DetectedEventArgs e)
881         {
882             if (e.TapGesture.Type == Gesture.GestureType.Tap)
883             {
884                 // Stop scrolling if tap detected (press then relase).
885                 // Unless in Pages mode, do not want a page change to stop part way.
886                 if (scrolling && !SnapToPage)
887                 {
888                     StopScroll();
889                 }
890             }
891         }
892
893         private void ScrollAnimationFinished(object sender, EventArgs e)
894         {
895             scrolling = false;
896             CheckPreReachedTargetPosition();
897             OnScrollAnimationEnd();
898         }
899
900         /// <summary>
901         /// Adjust scrolling position by own scrolling rules.
902         /// Override this function when developer wants to change destination of flicking.(e.g. always snap to center of item)
903         /// </summary>
904         /// <since_tizen> 6 </since_tizen>
905         /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
906         [EditorBrowsable(EditorBrowsableState.Never)]
907         protected virtual float AdjustTargetPositionOfScrollAnimation(float position)
908         {
909             return position;
910         }
911
912     }
913
914 } // namespace