[NUI] Fix Scrolling position issue by animation
[platform/core/csapi/tizenfx.git] / src / Tizen.NUI.Components / Controls / ScrollableBase.cs
1 /* Copyright (c) 2021 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.Collections.Generic;
19 using System.ComponentModel;
20 using System.Diagnostics;
21 using System.Runtime.InteropServices;
22 using Tizen.NUI.Accessibility;
23
24 namespace Tizen.NUI.Components
25 {
26     /// <summary>
27     /// ScrollEventArgs is a class to record scroll event arguments which will sent to user.
28     /// </summary>
29     /// <since_tizen> 8 </since_tizen>
30     public class ScrollEventArgs : EventArgs
31     {
32         private Position position;
33         private Position scrollPosition;
34
35         /// <summary>
36         /// Default constructor.
37         /// </summary>
38         /// <param name="position">Current container position</param>
39         /// <since_tizen> 8 </since_tizen>
40         public ScrollEventArgs(Position position)
41         {
42             this.position = position;
43             this.scrollPosition = new Position(-position);
44         }
45
46         /// <summary>
47         /// Current position of ContentContainer.
48         /// </summary>
49         /// <since_tizen> 8 </since_tizen>
50         public Position Position
51         {
52             get
53             {
54                 return position;
55             }
56         }
57         /// <summary>
58         /// Current scroll position of scrollableBase pan.
59         /// This is the position in the opposite direction to the current position of ContentContainer.
60         /// </summary>
61         [EditorBrowsable(EditorBrowsableState.Never)]
62         public Position ScrollPosition
63         {
64             get
65             {
66                 return scrollPosition;
67             }
68         }
69     }
70
71     /// <summary>
72     /// ScrollOutofBoundEventArgs is to record scroll out-of-bound event arguments which will be sent to user.
73     /// </summary>
74     [EditorBrowsable(EditorBrowsableState.Never)]
75     public class ScrollOutOfBoundEventArgs : EventArgs
76     {
77         /// <summary>
78         /// The direction to be touched.
79         /// </summary>
80         [EditorBrowsable(EditorBrowsableState.Never)]
81         public enum Direction
82         {
83             /// <summary>
84             /// Upwards.
85             /// </summary>
86             [EditorBrowsable(EditorBrowsableState.Never)]
87             Up,
88
89             /// <summary>
90             /// Downwards.
91             /// </summary>
92             [EditorBrowsable(EditorBrowsableState.Never)]
93             Down,
94
95             /// <summary>
96             /// Left bound.
97             /// </summary>
98             [EditorBrowsable(EditorBrowsableState.Never)]
99             Left,
100
101             /// <summary>
102             /// Right bound.
103             /// </summary>
104             [EditorBrowsable(EditorBrowsableState.Never)]
105             Right,
106         }
107
108         /// <summary>
109         /// Constructor.
110         /// </summary>
111         /// <param name="direction">Current pan direction</param>
112         /// <param name="displacement">Current total displacement</param>
113         [EditorBrowsable(EditorBrowsableState.Never)]
114         public ScrollOutOfBoundEventArgs(Direction direction, float displacement)
115         {
116             PanDirection = direction;
117             Displacement = displacement;
118         }
119
120         /// <summary>
121         /// Current pan direction of ContentContainer.
122         /// </summary>
123         [EditorBrowsable(EditorBrowsableState.Never)]
124         public Direction PanDirection
125         {
126             get;
127         }
128
129         /// <summary>
130         /// Current total displacement of ContentContainer.
131         /// if its value is greater than 0, it is at the top/left;
132         /// if less than 0, it is at the bottom/right.
133         /// </summary>
134         [EditorBrowsable(EditorBrowsableState.Never)]
135         public float Displacement
136         {
137             get;
138         }
139     }
140
141     /// <summary>
142     /// This class provides a View that can scroll a single View with a layout. This View can be a nest of Views.
143     /// </summary>
144     /// <since_tizen> 8 </since_tizen>
145     public class ScrollableBase : Control
146     {
147         static bool LayoutDebugScrollableBase = false; // Debug flag
148         private Direction mScrollingDirection = Direction.Vertical;
149         private bool mScrollEnabled = true;
150         private int mScrollDuration = 125;
151         private int mPageWidth = 0;
152         private float mPageFlickThreshold = 0.4f;
153         private float mScrollingEventThreshold = 0.001f;
154
155         private class ScrollableBaseCustomLayout : AbsoluteLayout
156         {
157             protected override void OnMeasure(MeasureSpecification widthMeasureSpec, MeasureSpecification heightMeasureSpec)
158             {
159                 MeasuredSize.StateType childWidthState = MeasuredSize.StateType.MeasuredSizeOK;
160                 MeasuredSize.StateType childHeightState = MeasuredSize.StateType.MeasuredSizeOK;
161
162                 Direction scrollingDirection = Direction.Vertical;
163                 ScrollableBase scrollableBase = this.Owner as ScrollableBase;
164                 if (scrollableBase != null)
165                 {
166                     scrollingDirection = scrollableBase.ScrollingDirection;
167                 }
168
169                 float totalWidth = 0.0f;
170                 float totalHeight = 0.0f;
171
172                 // measure child, should be a single scrolling child
173                 foreach (LayoutItem childLayout in LayoutChildren)
174                 {
175                     if (childLayout != null && childLayout.Owner.Name == "ContentContainer")
176                     {
177                         // Get size of child
178                         // Use an Unspecified MeasureSpecification mode so scrolling child is not restricted to it's parents size in Height (for vertical scrolling)
179                         // or Width for horizontal scrolling
180                         if (scrollingDirection == Direction.Vertical)
181                         {
182                             MeasureSpecification unrestrictedMeasureSpec = new MeasureSpecification(heightMeasureSpec.Size, MeasureSpecification.ModeType.Unspecified);
183                             MeasureChildWithMargins(childLayout, widthMeasureSpec, new LayoutLength(0), unrestrictedMeasureSpec, new LayoutLength(0)); // Height unrestricted by parent
184                         }
185                         else
186                         {
187                             MeasureSpecification unrestrictedMeasureSpec = new MeasureSpecification(widthMeasureSpec.Size, MeasureSpecification.ModeType.Unspecified);
188                             MeasureChildWithMargins(childLayout, unrestrictedMeasureSpec, new LayoutLength(0), heightMeasureSpec, new LayoutLength(0)); // Width unrestricted by parent
189                         }
190
191                         totalWidth = (childLayout.MeasuredWidth.Size + (childLayout.Padding.Start + childLayout.Padding.End)).AsDecimal();
192                         totalHeight = (childLayout.MeasuredHeight.Size + (childLayout.Padding.Top + childLayout.Padding.Bottom)).AsDecimal();
193
194                         if (childLayout.MeasuredWidth.State == MeasuredSize.StateType.MeasuredSizeTooSmall)
195                         {
196                             childWidthState = MeasuredSize.StateType.MeasuredSizeTooSmall;
197                         }
198                         if (childLayout.MeasuredHeight.State == MeasuredSize.StateType.MeasuredSizeTooSmall)
199                         {
200                             childHeightState = MeasuredSize.StateType.MeasuredSizeTooSmall;
201                         }
202                     }
203                 }
204
205                 MeasuredSize widthSizeAndState = ResolveSizeAndState(new LayoutLength(totalWidth), widthMeasureSpec, MeasuredSize.StateType.MeasuredSizeOK);
206                 MeasuredSize heightSizeAndState = ResolveSizeAndState(new LayoutLength(totalHeight), heightMeasureSpec, MeasuredSize.StateType.MeasuredSizeOK);
207                 totalWidth = widthSizeAndState.Size.AsDecimal();
208                 totalHeight = heightSizeAndState.Size.AsDecimal();
209
210                 // Ensure layout respects it's given minimum size
211                 totalWidth = Math.Max(totalWidth, SuggestedMinimumWidth.AsDecimal());
212                 totalHeight = Math.Max(totalHeight, SuggestedMinimumHeight.AsDecimal());
213
214                 widthSizeAndState.State = childWidthState;
215                 heightSizeAndState.State = childHeightState;
216
217                 SetMeasuredDimensions(ResolveSizeAndState(new LayoutLength(totalWidth), widthMeasureSpec, childWidthState),
218                     ResolveSizeAndState(new LayoutLength(totalHeight), heightMeasureSpec, childHeightState));
219
220                 // Size of ScrollableBase is changed. Change Page width too.
221                 if (scrollableBase != null)
222                 {
223                     scrollableBase.mPageWidth = (int)MeasuredWidth.Size.AsRoundedValue();
224                     scrollableBase.OnScrollingChildRelayout(null, null);
225                 }
226             }
227         } //  ScrollableBaseCustomLayout
228
229         /// <summary>
230         /// The direction axis to scroll.
231         /// </summary>
232         /// <since_tizen> 8 </since_tizen>
233         public enum Direction
234         {
235             /// <summary>
236             /// Horizontal axis.
237             /// </summary>
238             /// <since_tizen> 8 </since_tizen>
239             Horizontal,
240
241             /// <summary>
242             /// Vertical axis.
243             /// </summary>
244             /// <since_tizen> 8 </since_tizen>
245             Vertical
246         }
247
248         /// <summary>
249         /// Scrolling direction mode.
250         /// Default is Vertical scrolling.
251         /// </summary>
252         /// <since_tizen> 8 </since_tizen>
253         public Direction ScrollingDirection
254         {
255             get
256             {
257                 return mScrollingDirection;
258             }
259             set
260             {
261                 if (value != mScrollingDirection)
262                 {
263                     //Reset scroll position and stop scroll animation
264                     ScrollTo(0, false);
265
266                     mScrollingDirection = value;
267                     mPanGestureDetector.ClearAngles();
268                     mPanGestureDetector.AddDirection(value == Direction.Horizontal ?
269                         PanGestureDetector.DirectionHorizontal : PanGestureDetector.DirectionVertical);
270
271                     ContentContainer.WidthSpecification = ScrollingDirection == Direction.Vertical ? LayoutParamPolicies.MatchParent : LayoutParamPolicies.WrapContent;
272                     ContentContainer.HeightSpecification = ScrollingDirection == Direction.Vertical ? LayoutParamPolicies.WrapContent : LayoutParamPolicies.MatchParent;
273                     SetScrollbar();
274                 }
275             }
276         }
277
278         /// <summary>
279         /// Enable or disable scrolling.
280         /// </summary>
281         /// <since_tizen> 8 </since_tizen>
282         public bool ScrollEnabled
283         {
284             get
285             {
286                 return mScrollEnabled;
287             }
288             set
289             {
290                 if (value != mScrollEnabled)
291                 {
292                     mScrollEnabled = value;
293                     if (mScrollEnabled)
294                     {
295                         mPanGestureDetector.Detected += OnPanGestureDetected;
296                     }
297                     else
298                     {
299                         mPanGestureDetector.Detected -= OnPanGestureDetected;
300                     }
301                 }
302             }
303         }
304
305         /// <summary>
306         /// Gets scrollable status.
307         /// </summary>
308         [EditorBrowsable(EditorBrowsableState.Never)]
309         protected override bool AccessibilityIsScrollable()
310         {
311             return true;
312         }
313
314         /// <summary>
315         /// Pages mode, enables moving to the next or return to current page depending on pan displacement.
316         /// Default is false.
317         /// </summary>
318         /// <since_tizen> 8 </since_tizen>
319         public bool SnapToPage { set; get; } = false;
320
321         /// <summary>
322         /// Get current page.
323         /// Working property with SnapToPage property.
324         /// </summary>
325         /// <since_tizen> 8 </since_tizen>
326         public int CurrentPage { get; private set; } = 0;
327
328         /// <summary>
329         /// Duration of scroll animation.
330         /// Default value is 125ms.
331         /// </summary>
332         /// <since_tizen> 8 </since_tizen>
333         public int ScrollDuration
334         {
335             set
336             {
337                 mScrollDuration = value >= 0 ? value : mScrollDuration;
338             }
339             get
340             {
341                 return mScrollDuration;
342             }
343         }
344
345         /// <summary>
346         /// Scroll Available area.
347         /// </summary>
348         /// <since_tizen> 8 </since_tizen>
349         public Vector2 ScrollAvailableArea { set; get; }
350
351         /// <summary>
352         /// An event emitted when user starts dragging ScrollableBase, user can subscribe or unsubscribe to this event handler.<br />
353         /// </summary>
354         /// <since_tizen> 8 </since_tizen>
355         public event EventHandler<ScrollEventArgs> ScrollDragStarted;
356
357         /// <summary>
358         /// An event emitted when user stops dragging ScrollableBase, user can subscribe or unsubscribe to this event handler.<br />
359         /// </summary>
360         /// <since_tizen> 8 </since_tizen>
361         public event EventHandler<ScrollEventArgs> ScrollDragEnded;
362
363         /// <summary>
364         /// An event emitted when the scrolling slide animation starts, user can subscribe or unsubscribe to this event handler.<br />
365         /// </summary>
366         /// <since_tizen> 8 </since_tizen>
367         public event EventHandler<ScrollEventArgs> ScrollAnimationStarted;
368
369         /// <summary>
370         /// An event emitted when the scrolling slide animation ends, user can subscribe or unsubscribe to this event handler.<br />
371         /// </summary>
372         /// <since_tizen> 8 </since_tizen>
373         public event EventHandler<ScrollEventArgs> ScrollAnimationEnded;
374
375         /// <summary>
376         /// An event emitted when scrolling, user can subscribe or unsubscribe to this event handler.<br />
377         /// </summary>
378         /// <since_tizen> 8 </since_tizen>
379         public event EventHandler<ScrollEventArgs> Scrolling;
380
381         /// <summary>
382         /// An event emitted when scrolling out of bound, user can subscribe or unsubscribe to this event handler.<br />
383         /// </summary>
384         [EditorBrowsable(EditorBrowsableState.Never)]
385         public event EventHandler<ScrollOutOfBoundEventArgs> ScrollOutOfBound;
386
387         /// <summary>
388         /// Scrollbar for ScrollableBase.
389         /// </summary>
390         /// <since_tizen> 8 </since_tizen>
391         public ScrollbarBase Scrollbar
392         {
393             get
394             {
395                 return scrollBar;
396             }
397             set
398             {
399                 if (scrollBar)
400                 {
401                     base.Remove(scrollBar);
402                 }
403                 scrollBar = value;
404
405                 if (scrollBar != null)
406                 {
407                     scrollBar.Name = "ScrollBar";
408                     base.Add(scrollBar);
409
410                     if (hideScrollbar)
411                     {
412                         scrollBar.Hide();
413                     }
414                     else
415                     {
416                         scrollBar.Show();
417                     }
418
419                     SetScrollbar();
420                 }
421             }
422         }
423
424         /// <summary>
425         /// Always hide Scrollbar.
426         /// </summary>
427         /// <since_tizen> 8 </since_tizen>
428         public bool HideScrollbar
429         {
430             get
431             {
432                 return hideScrollbar;
433             }
434             set
435             {
436                 hideScrollbar = value;
437
438                 if (scrollBar)
439                 {
440                     if (value)
441                     {
442                         scrollBar.Hide();
443                     }
444                     else
445                     {
446                         scrollBar.Show();
447                     }
448                 }
449             }
450         }
451
452         /// <summary>
453         /// Container which has content of ScrollableBase.
454         /// </summary>
455         /// <since_tizen> 8 </since_tizen>
456         public View ContentContainer { get; private set; }
457
458         /// <summary>
459         /// Set the layout on this View. Replaces any existing Layout.
460         /// </summary>
461         /// <since_tizen> 8 </since_tizen>
462         public new LayoutItem Layout
463         {
464             get
465             {
466                 return ContentContainer.Layout;
467             }
468             set
469             {
470                 ContentContainer.Layout = value;
471             }
472         }
473
474         /// <summary>
475         /// List of children of Container.
476         /// </summary>
477         /// <since_tizen> 8 </since_tizen>
478         public new List<View> Children
479         {
480             get
481             {
482                 return ContentContainer.Children;
483             }
484         }
485
486         /// <summary>
487         /// Deceleration rate of scrolling by finger.
488         /// Rate should be bigger than 0 and smaller than 1.
489         /// Default value is 0.998f;
490         /// </summary>
491         /// <since_tizen> 8 </since_tizen>
492         public float DecelerationRate
493         {
494             get
495             {
496                 return decelerationRate;
497             }
498             set
499             {
500                 decelerationRate = (value < 1 && value > 0) ? value : decelerationRate;
501                 logValueOfDeceleration = (float)Math.Log(value);
502             }
503         }
504
505         /// <summary>
506         /// Threshold not to go infinite at the end of scrolling animation.
507         /// </summary>
508         [EditorBrowsable(EditorBrowsableState.Never)]
509         public float DecelerationThreshold { get; set; } = 0.1f;
510
511         /// <summary>
512         /// Scrolling event will be thrown when this amount of scroll position is changed.
513         /// If this threshold becomes smaller, the tracking detail increases but the scrolling range that can be tracked becomes smaller.
514         /// If large sized ContentContainer is required, please use larger threshold value.
515         /// Default ScrollingEventThreshold value is 0.001f.
516         /// </summary>
517         [EditorBrowsable(EditorBrowsableState.Never)]
518         public float ScrollingEventThreshold
519         {
520             get
521             {
522                 return mScrollingEventThreshold;
523             }
524             set
525             {
526                 if (mScrollingEventThreshold != value && value > 0)
527                 {
528                     ContentContainer.RemovePropertyNotification(propertyNotification);
529                     propertyNotification = ContentContainer.AddPropertyNotification("position", PropertyCondition.Step(value));
530                     propertyNotification.Notified += OnPropertyChanged;
531                     mScrollingEventThreshold = value;
532                 }
533             }
534         }
535
536         /// <summary>
537         /// Page will be changed when velocity of panning is over threshold.
538         /// The unit of threshold is pixel per millisecond.
539         /// </summary>
540         /// <since_tizen> 8 </since_tizen>
541         public float PageFlickThreshold
542         {
543             get
544             {
545                 return mPageFlickThreshold;
546             }
547             set
548             {
549                 mPageFlickThreshold = value >= 0f ? value : mPageFlickThreshold;
550             }
551         }
552
553         /// <summary>
554         /// Padding for the ScrollableBase
555         /// </summary>
556         [EditorBrowsable(EditorBrowsableState.Never)]
557         public new Extents Padding
558         {
559             get
560             {
561                 return ContentContainer.Padding;
562             }
563             set
564             {
565                 ContentContainer.Padding = value;
566             }
567         }
568
569         /// <summary>
570         /// Alphafunction for scroll animation.
571         /// </summary>
572         [EditorBrowsable(EditorBrowsableState.Never)]
573         public AlphaFunction ScrollAlphaFunction { get; set; } = new AlphaFunction(AlphaFunction.BuiltinFunctions.Linear);
574
575         private bool hideScrollbar = true;
576         private float maxScrollDistance;
577         private float childTargetPosition = 0.0f;
578         private PanGestureDetector mPanGestureDetector;
579         private ScrollbarBase scrollBar;
580         private bool scrolling = false;
581         private float ratioOfScreenWidthToCompleteScroll = 0.5f;
582         private float totalDisplacementForPan = 0.0f;
583         private Size previousContainerSize = new Size();
584         private Size previousSize = new Size();
585         private PropertyNotification propertyNotification;
586         private float noticeAnimationEndBeforePosition = 0.0f;
587         private bool readyToNotice = false;
588
589         /// <summary>
590         /// Notice before animation is finished.
591         /// </summary>
592         [EditorBrowsable(EditorBrowsableState.Never)]
593         // Let's consider more whether this needs to be set as protected.
594         public float NoticeAnimationEndBeforePosition
595         {
596             get => noticeAnimationEndBeforePosition;
597             set => noticeAnimationEndBeforePosition = value;
598         }
599
600         // Let's consider more whether this needs to be set as protected.
601         private float finalTargetPosition;
602
603         private Animation scrollAnimation;
604         // Declare user alpha function delegate
605         [UnmanagedFunctionPointer(CallingConvention.StdCall)]
606         private delegate float UserAlphaFunctionDelegate(float progress);
607         private UserAlphaFunctionDelegate customScrollAlphaFunction;
608         private float velocityOfLastPan = 0.0f;
609         private float panAnimationDuration = 0.0f;
610         private float panAnimationDelta = 0.0f;
611         private float logValueOfDeceleration = 0.0f;
612         private float decelerationRate = 0.0f;
613
614         private View topOverShootingShadowView;
615         private View bottomOverShootingShadowView;
616         private View leftOverShootingShadowView;
617         private View rightOverShootingShadowView;
618         private const int overShootingShadowScaleHeightLimit = 64 * 3;
619         private const int overShootingShadowAnimationDuration = 300;
620         private Animation overShootingShadowAnimation;
621         private bool isOverShootingShadowShown = false;
622         private float startShowShadowDisplacement;
623
624         /// <summary>
625         /// Default Constructor
626         /// </summary>
627         /// <since_tizen> 8 </since_tizen>
628         public ScrollableBase() : base()
629         {
630             DecelerationRate = 0.998f;
631
632             base.Layout = new ScrollableBaseCustomLayout();
633             mPanGestureDetector = new PanGestureDetector();
634             mPanGestureDetector.Attach(this);
635             mPanGestureDetector.AddDirection(PanGestureDetector.DirectionVertical);
636             if (mPanGestureDetector.GetMaximumTouchesRequired() < 2) mPanGestureDetector.SetMaximumTouchesRequired(2);
637             mPanGestureDetector.Detected += OnPanGestureDetected;
638
639             ClippingMode = ClippingModeType.ClipToBoundingBox;
640
641             //Default Scrolling child
642             ContentContainer = new View()
643             {
644                 Name = "ContentContainer",
645                 WidthSpecification = ScrollingDirection == Direction.Vertical ? LayoutParamPolicies.MatchParent : LayoutParamPolicies.WrapContent,
646                 HeightSpecification = ScrollingDirection == Direction.Vertical ? LayoutParamPolicies.WrapContent : LayoutParamPolicies.MatchParent,
647             };
648             ContentContainer.Relayout += OnScrollingChildRelayout;
649             propertyNotification = ContentContainer.AddPropertyNotification("position", PropertyCondition.Step(mScrollingEventThreshold));
650             propertyNotification.Notified += OnPropertyChanged;
651             base.Add(ContentContainer);
652
653             Scrollbar = new Scrollbar();
654
655             //Show vertical shadow on the top (or bottom) of the scrollable when panning down (or up).
656             topOverShootingShadowView = new View
657             {
658                 BackgroundImage = FrameworkInformation.ResourcePath + "nui_component_default_scroll_over_shooting_top.png",
659                 Opacity = 1.0f,
660                 SizeHeight = 0.0f,
661                 PositionUsesPivotPoint = true,
662                 ParentOrigin = NUI.ParentOrigin.TopCenter,
663                 PivotPoint = NUI.PivotPoint.TopCenter,
664             };
665             bottomOverShootingShadowView = new View
666             {
667                 BackgroundImage = FrameworkInformation.ResourcePath + "nui_component_default_scroll_over_shooting_bottom.png",
668                 Opacity = 1.0f,
669                 SizeHeight = 0.0f,
670                 PositionUsesPivotPoint = true,
671                 ParentOrigin = NUI.ParentOrigin.BottomCenter,
672                 PivotPoint = NUI.PivotPoint.BottomCenter,
673             };
674             //Show horizontal shadow on the left (or right) of the scrollable when panning down (or up).
675             leftOverShootingShadowView = new View
676             {
677                 BackgroundImage = FrameworkInformation.ResourcePath + "nui_component_default_scroll_over_shooting_left.png",
678                 Opacity = 1.0f,
679                 SizeWidth = 0.0f,
680                 PositionUsesPivotPoint = true,
681                 ParentOrigin = NUI.ParentOrigin.CenterLeft,
682                 PivotPoint = NUI.PivotPoint.CenterLeft,
683             };
684             rightOverShootingShadowView = new View
685             {
686                 BackgroundImage = FrameworkInformation.ResourcePath + "nui_component_default_scroll_over_shooting_right.png",
687                 Opacity = 1.0f,
688                 SizeWidth = 0.0f,
689                 PositionUsesPivotPoint = true,
690                 ParentOrigin = NUI.ParentOrigin.CenterRight,
691                 PivotPoint = NUI.PivotPoint.CenterRight,
692             };
693
694             AccessibilityManager.Instance.SetAccessibilityAttribute(this, AccessibilityManager.AccessibilityAttribute.Trait, "ScrollableBase");
695         }
696
697         private bool OnInterruptTouchingChildTouched(object source, View.TouchEventArgs args)
698         {
699             if (args.Touch.GetState(0) == PointStateType.Down)
700             {
701                 if (scrolling && !SnapToPage)
702                 {
703                     StopScroll();
704                 }
705             }
706             return true;
707         }
708
709         private void OnPropertyChanged(object source, PropertyNotification.NotifyEventArgs args)
710         {
711             OnScroll();
712         }
713
714         /// <summary>
715         /// Called after a child has been added to the owning view.
716         /// </summary>
717         /// <param name="view">The child which has been added.</param>
718         /// <since_tizen> 8 </since_tizen>
719         public override void Add(View view)
720         {
721             ContentContainer.Add(view);
722         }
723
724         /// <summary>
725         /// Called after a child has been removed from the owning view.
726         /// </summary>
727         /// <param name="view">The child which has been removed.</param>
728         /// <since_tizen> 8 </since_tizen>
729         public override void Remove(View view)
730         {
731             if (SnapToPage && CurrentPage == Children.IndexOf(view) && CurrentPage == Children.Count - 1 && Children.Count > 1)
732             {
733                 // Target View is current page and also last child.
734                 // CurrentPage should be changed to previous page.
735                 ScrollToIndex(CurrentPage - 1);
736             }
737
738             ContentContainer.Remove(view);
739         }
740
741         private void OnScrollingChildRelayout(object source, EventArgs args)
742         {
743             // Size is changed. Calculate maxScrollDistance.
744             bool isSizeChanged = previousContainerSize.Width != ContentContainer.Size.Width || previousContainerSize.Height != ContentContainer.Size.Height ||
745                 previousSize.Width != Size.Width || previousSize.Height != Size.Height;
746
747             if (isSizeChanged)
748             {
749                 maxScrollDistance = CalculateMaximumScrollDistance();
750                 if (!ReviseContainerPositionIfNeed())
751                 {
752                     UpdateScrollbar();
753                 }
754             }
755
756             previousContainerSize = ContentContainer.Size;
757             previousSize = Size;
758         }
759
760         private bool ReviseContainerPositionIfNeed()
761         {
762             bool isHorizontal = ScrollingDirection == Direction.Horizontal;
763             float currentPosition = isHorizontal ? ContentContainer.CurrentPosition.X : ContentContainer.CurrentPosition.Y;
764
765             if (Math.Abs(currentPosition) > maxScrollDistance)
766             {
767                 StopScroll();
768                 var targetPosition = BoundScrollPosition(-maxScrollDistance);
769                 if (isHorizontal) ContentContainer.PositionX = targetPosition;
770                 else ContentContainer.PositionY = targetPosition;
771                 return true;
772             }
773
774             return false;
775         }
776
777         /// <summary>
778         /// The composition of a Scrollbar can vary depending on how you use ScrollableBase.
779         /// Set the composition that will go into the ScrollableBase according to your ScrollableBase.
780         /// </summary>
781         /// <since_tizen> 8 </since_tizen>
782         [EditorBrowsable(EditorBrowsableState.Never)]
783         protected virtual void SetScrollbar()
784         {
785             if (Scrollbar)
786             {
787                 bool isHorizontal = ScrollingDirection == Direction.Horizontal;
788                 float contentLength = isHorizontal ? ContentContainer.Size.Width : ContentContainer.Size.Height;
789                 float viewportLength = isHorizontal ? Size.Width : Size.Height;
790                 float currentPosition = isHorizontal ? ContentContainer.CurrentPosition.X : ContentContainer.CurrentPosition.Y;
791                 Scrollbar.Initialize(contentLength, viewportLength, -currentPosition, isHorizontal);
792             }
793         }
794
795         /// Update scrollbar position and size.
796         [EditorBrowsable(EditorBrowsableState.Never)]
797         protected virtual void UpdateScrollbar()
798         {
799             if (Scrollbar)
800             {
801                 bool isHorizontal = ScrollingDirection == Direction.Horizontal;
802                 float contentLength = isHorizontal ? ContentContainer.Size.Width : ContentContainer.Size.Height;
803                 float viewportLength = isHorizontal ? Size.Width : Size.Height;
804                 float currentPosition = isHorizontal ? ContentContainer.CurrentPosition.X : ContentContainer.CurrentPosition.Y;
805                 Scrollbar.Update(contentLength, viewportLength, -currentPosition);
806             }
807         }
808
809         /// <summary>
810         /// Scrolls to the item at the specified index.
811         /// </summary>
812         /// <param name="index">Index of item.</param>
813         /// <since_tizen> 8 </since_tizen>
814         public void ScrollToIndex(int index)
815         {
816             if (ContentContainer.ChildCount - 1 < index || index < 0)
817             {
818                 return;
819             }
820
821             if (SnapToPage)
822             {
823                 CurrentPage = index;
824             }
825
826             float targetPosition = Math.Min(ScrollingDirection == Direction.Vertical ? Children[index].Position.Y : Children[index].Position.X, maxScrollDistance);
827             AnimateChildTo(ScrollDuration, -targetPosition);
828         }
829
830         private void OnScrollDragStarted()
831         {
832             ScrollEventArgs eventArgs = new ScrollEventArgs(ContentContainer.CurrentPosition);
833             ScrollDragStarted?.Invoke(this, eventArgs);
834         }
835
836         private void OnScrollDragEnded()
837         {
838             ScrollEventArgs eventArgs = new ScrollEventArgs(ContentContainer.CurrentPosition);
839             ScrollDragEnded?.Invoke(this, eventArgs);
840         }
841
842         private void OnScrollAnimationStarted()
843         {
844             ScrollEventArgs eventArgs = new ScrollEventArgs(ContentContainer.CurrentPosition);
845             ScrollAnimationStarted?.Invoke(this, eventArgs);
846         }
847
848         private void OnScrollAnimationEnded()
849         {
850             scrolling = false;
851             this.InterceptTouchEvent -= OnInterruptTouchingChildTouched;
852
853             ScrollEventArgs eventArgs = new ScrollEventArgs(ContentContainer.CurrentPosition);
854             ScrollAnimationEnded?.Invoke(this, eventArgs);
855         }
856
857         private void OnScroll()
858         {
859             ScrollEventArgs eventArgs = new ScrollEventArgs(ContentContainer.CurrentPosition);
860             Scrolling?.Invoke(this, eventArgs);
861
862             bool isHorizontal = ScrollingDirection == Direction.Horizontal;
863             float contentLength = isHorizontal ? ContentContainer.Size.Width : ContentContainer.Size.Height;
864             float currentPosition = isHorizontal ? ContentContainer.CurrentPosition.X : ContentContainer.CurrentPosition.Y;
865
866             scrollBar?.Update(contentLength, Math.Abs(currentPosition));
867             CheckPreReachedTargetPosition();
868         }
869
870         private void CheckPreReachedTargetPosition()
871         {
872             // Check whether we reached pre-reached target position
873             if (readyToNotice &&
874                 ContentContainer.CurrentPosition.Y <= finalTargetPosition + NoticeAnimationEndBeforePosition &&
875                 ContentContainer.CurrentPosition.Y >= finalTargetPosition - NoticeAnimationEndBeforePosition)
876             {
877                 //Notice first
878                 readyToNotice = false;
879                 OnPreReachedTargetPosition(finalTargetPosition);
880             }
881         }
882
883         /// <summary>
884         /// This helps developer who wants to know before scroll is reaching target position.
885         /// </summary>
886         /// <param name="targetPosition">Index of item.</param>
887         /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
888         [EditorBrowsable(EditorBrowsableState.Never)]
889         protected virtual void OnPreReachedTargetPosition(float targetPosition)
890         {
891
892         }
893
894         private void StopScroll()
895         {
896             if (scrollAnimation != null)
897             {
898                 if (scrollAnimation.State == Animation.States.Playing)
899                 {
900                     Debug.WriteLineIf(LayoutDebugScrollableBase, "StopScroll Animation Playing");
901                     scrollAnimation.Stop(Animation.EndActions.Cancel);
902                     OnScrollAnimationEnded();
903                 }
904                 scrollAnimation.Clear();
905             }
906         }
907
908         private void AnimateChildTo(int duration, float axisPosition)
909         {
910             Debug.WriteLineIf(LayoutDebugScrollableBase, "AnimationTo Animation Duration:" + duration + " Destination:" + axisPosition);
911             finalTargetPosition = axisPosition;
912
913             StopScroll(); // Will replace previous animation so will stop existing one.
914
915             if (scrollAnimation == null)
916             {
917                 scrollAnimation = new Animation();
918                 scrollAnimation.Finished += ScrollAnimationFinished;
919             }
920
921             scrollAnimation.Duration = duration;
922             scrollAnimation.DefaultAlphaFunction = new AlphaFunction(AlphaFunction.BuiltinFunctions.EaseOutSquare);
923             scrollAnimation.AnimateTo(ContentContainer, (ScrollingDirection == Direction.Horizontal) ? "PositionX" : "PositionY", axisPosition, ScrollAlphaFunction);
924             scrolling = true;
925             OnScrollAnimationStarted();
926             scrollAnimation.Play();
927         }
928
929         /// <summary>
930         /// Scroll to specific position with or without animation.
931         /// </summary>
932         /// <param name="position">Destination.</param>
933         /// <param name="animate">Scroll with or without animation</param>
934         /// <since_tizen> 8 </since_tizen>
935         public void ScrollTo(float position, bool animate)
936         {
937             StopScroll();
938             float currentPositionX = ContentContainer.CurrentPosition.X != 0 ? ContentContainer.CurrentPosition.X : ContentContainer.Position.X;
939             float currentPositionY = ContentContainer.CurrentPosition.Y != 0 ? ContentContainer.CurrentPosition.Y : ContentContainer.Position.Y;
940             float delta = ScrollingDirection == Direction.Horizontal ? currentPositionX : currentPositionY;
941             // The argument position is the new pan position. So the new position of ScrollableBase becomes (-position).
942             // To move ScrollableBase's position to (-position), it moves by (-position - currentPosition).
943             delta = -position - delta;
944
945             ScrollBy(delta, animate);
946         }
947
948         private float BoundScrollPosition(float targetPosition)
949         {
950             if (ScrollAvailableArea != null)
951             {
952                 float minScrollPosition = ScrollAvailableArea.X;
953                 float maxScrollPosition = ScrollAvailableArea.Y;
954
955                 targetPosition = Math.Min(-minScrollPosition, targetPosition);
956                 targetPosition = Math.Max(-maxScrollPosition, targetPosition);
957             }
958             else
959             {
960                 targetPosition = Math.Min(0, targetPosition);
961                 targetPosition = Math.Max(-maxScrollDistance, targetPosition);
962             }
963
964             return targetPosition;
965         }
966
967         private void ScrollBy(float displacement, bool animate)
968         {
969             if (GetChildCount() == 0 || maxScrollDistance < 0)
970             {
971                 return;
972             }
973
974             float childCurrentPosition = (ScrollingDirection == Direction.Horizontal) ? ContentContainer.PositionX : ContentContainer.PositionY;
975
976             Debug.WriteLineIf(LayoutDebugScrollableBase, "ScrollBy childCurrentPosition:" + childCurrentPosition +
977                 " displacement:" + displacement,
978                 " maxScrollDistance:" + maxScrollDistance);
979
980             childTargetPosition = childCurrentPosition + displacement; // child current position + gesture displacement
981
982             Debug.WriteLineIf(LayoutDebugScrollableBase, "ScrollBy currentAxisPosition:" + childCurrentPosition + "childTargetPosition:" + childTargetPosition);
983
984             if (animate)
985             {
986                 // Calculate scroll animation duration
987                 float scrollDistance = Math.Abs(displacement);
988                 readyToNotice = true;
989
990                 AnimateChildTo(ScrollDuration, BoundScrollPosition(AdjustTargetPositionOfScrollAnimation(BoundScrollPosition(childTargetPosition))));
991             }
992             else
993             {
994                 StopScroll();
995                 finalTargetPosition = BoundScrollPosition(childTargetPosition);
996
997                 // Set position of scrolling child without an animation
998                 if (ScrollingDirection == Direction.Horizontal)
999                 {
1000                     ContentContainer.PositionX = finalTargetPosition;
1001                 }
1002                 else
1003                 {
1004                     ContentContainer.PositionY = finalTargetPosition;
1005                 }
1006             }
1007         }
1008
1009         /// <summary>
1010         /// you can override it to clean-up your own resources.
1011         /// </summary>
1012         /// <param name="type">DisposeTypes</param>
1013         /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API.
1014         [EditorBrowsable(EditorBrowsableState.Never)]
1015         protected override void Dispose(DisposeTypes type)
1016         {
1017             if (disposed)
1018             {
1019                 return;
1020             }
1021
1022             if (type == DisposeTypes.Explicit)
1023             {
1024                 StopOverShootingShadowAnimation();
1025                 StopScroll();
1026
1027                 if (mPanGestureDetector != null)
1028                 {
1029                     mPanGestureDetector.Detected -= OnPanGestureDetected;
1030                     mPanGestureDetector.Dispose();
1031                     mPanGestureDetector = null;
1032                 }
1033
1034                 propertyNotification.Dispose();
1035             }
1036             base.Dispose(type);
1037         }
1038
1039         private float CalculateMaximumScrollDistance()
1040         {
1041             float scrollingChildLength = 0;
1042             float scrollerLength = 0;
1043             if (ScrollingDirection == Direction.Horizontal)
1044             {
1045                 Debug.WriteLineIf(LayoutDebugScrollableBase, "Horizontal");
1046
1047                 scrollingChildLength = ContentContainer.Size.Width;
1048                 scrollerLength = Size.Width;
1049             }
1050             else
1051             {
1052                 Debug.WriteLineIf(LayoutDebugScrollableBase, "Vertical");
1053                 scrollingChildLength = ContentContainer.Size.Height;
1054                 scrollerLength = Size.Height;
1055             }
1056
1057             Debug.WriteLineIf(LayoutDebugScrollableBase, "ScrollBy maxScrollDistance:" + (scrollingChildLength - scrollerLength) +
1058                 " parent length:" + scrollerLength +
1059                 " scrolling child length:" + scrollingChildLength);
1060
1061             return Math.Max(scrollingChildLength - scrollerLength, 0);
1062         }
1063
1064         private void PageSnap(float velocity)
1065         {
1066             float destination;
1067
1068             Debug.WriteLineIf(LayoutDebugScrollableBase, "PageSnap with pan candidate totalDisplacement:" + totalDisplacementForPan +
1069                 " currentPage[" + CurrentPage + "]");
1070
1071             //Increment current page if total displacement enough to warrant a page change.
1072             if (Math.Abs(totalDisplacementForPan) > (mPageWidth * ratioOfScreenWidthToCompleteScroll))
1073             {
1074                 if (totalDisplacementForPan < 0)
1075                 {
1076                     CurrentPage = Math.Min(Math.Max(Children.Count - 1, 0), ++CurrentPage);
1077                 }
1078                 else
1079                 {
1080                     CurrentPage = Math.Max(0, --CurrentPage);
1081                 }
1082             }
1083             else if (Math.Abs(velocity) > PageFlickThreshold)
1084             {
1085                 if (velocity < 0)
1086                 {
1087                     CurrentPage = Math.Min(Math.Max(Children.Count - 1, 0), ++CurrentPage);
1088                 }
1089                 else
1090                 {
1091                     CurrentPage = Math.Max(0, --CurrentPage);
1092                 }
1093             }
1094
1095             // Animate to new page or reposition to current page
1096             if (ScrollingDirection == Direction.Horizontal)
1097                 destination = -(Children[CurrentPage].Position.X + Children[CurrentPage].CurrentSize.Width / 2 - CurrentSize.Width / 2); // set to middle of current page
1098             else
1099                 destination = -(Children[CurrentPage].Position.Y + Children[CurrentPage].CurrentSize.Height / 2 - CurrentSize.Height / 2);
1100
1101             AnimateChildTo(ScrollDuration, destination);
1102         }
1103
1104         /// <summary>
1105         /// Enable/Disable overshooting effect. default is disabled.
1106         /// </summary>
1107         [EditorBrowsable(EditorBrowsableState.Never)]
1108         public bool EnableOverShootingEffect { get; set; } = false;
1109
1110         private void AttachOverShootingShadowView()
1111         {
1112             if (!EnableOverShootingEffect)
1113                 return;
1114
1115             // stop animation if necessary.
1116             StopOverShootingShadowAnimation();
1117
1118             if (ScrollingDirection == Direction.Horizontal)
1119             {
1120                 base.Add(leftOverShootingShadowView);
1121                 base.Add(rightOverShootingShadowView);
1122
1123                 leftOverShootingShadowView.Size = new Size(0.0f, SizeHeight);
1124                 leftOverShootingShadowView.Opacity = 1.0f;
1125                 leftOverShootingShadowView.RaiseToTop();
1126
1127                 rightOverShootingShadowView.Size = new Size(0.0f, SizeHeight);
1128                 rightOverShootingShadowView.Opacity = 1.0f;
1129                 rightOverShootingShadowView.RaiseToTop();
1130             }
1131             else
1132             {
1133                 base.Add(topOverShootingShadowView);
1134                 base.Add(bottomOverShootingShadowView);
1135
1136                 topOverShootingShadowView.Size = new Size(SizeWidth, 0.0f);
1137                 topOverShootingShadowView.Opacity = 1.0f;
1138                 topOverShootingShadowView.RaiseToTop();
1139
1140                 bottomOverShootingShadowView.Size = new Size(SizeWidth, 0.0f);
1141                 bottomOverShootingShadowView.Opacity = 1.0f;
1142                 bottomOverShootingShadowView.RaiseToTop();
1143             }
1144
1145             // at the beginning, height or width of overshooting shadow is 0, so it is invisible.
1146             isOverShootingShadowShown = false;
1147         }
1148
1149         private void DragOverShootingShadow(float totalPanDisplacement, float panDisplacement)
1150         {
1151             if (!EnableOverShootingEffect)
1152                 return;
1153
1154             if (totalPanDisplacement > 0) // downwards
1155             {
1156                 // check if reaching at the top / left.
1157                 if ((int)finalTargetPosition != 0)
1158                 {
1159                     isOverShootingShadowShown = false;
1160                     return;
1161                 }
1162
1163                 // save start displacement, and re-calculate displacement.
1164                 if (!isOverShootingShadowShown)
1165                 {
1166                     startShowShadowDisplacement = totalPanDisplacement;
1167                 }
1168                 isOverShootingShadowShown = true;
1169
1170                 float newDisplacement = (int)totalPanDisplacement < (int)startShowShadowDisplacement ? 0 : totalPanDisplacement - startShowShadowDisplacement;
1171
1172                 if (ScrollingDirection == Direction.Horizontal)
1173                 {
1174                     // scale limit of height is 60%.
1175                     float heightScale = newDisplacement / overShootingShadowScaleHeightLimit;
1176                     leftOverShootingShadowView.SizeHeight = heightScale > 0.6f ? SizeHeight * 0.4f : SizeHeight * (1.0f - heightScale);
1177
1178                     // scale limit of width is 300%.
1179                     leftOverShootingShadowView.SizeWidth = newDisplacement > overShootingShadowScaleHeightLimit ? overShootingShadowScaleHeightLimit : newDisplacement;
1180
1181                     // trigger event
1182                     ScrollOutOfBoundEventArgs.Direction scrollDirection = panDisplacement > 0 ?
1183                        ScrollOutOfBoundEventArgs.Direction.Right : ScrollOutOfBoundEventArgs.Direction.Left;
1184                     OnScrollOutOfBound(scrollDirection, totalPanDisplacement);
1185                 }
1186                 else
1187                 {
1188                     // scale limit of width is 60%.
1189                     float widthScale = newDisplacement / overShootingShadowScaleHeightLimit;
1190                     topOverShootingShadowView.SizeWidth = widthScale > 0.6f ? SizeWidth * 0.4f : SizeWidth * (1.0f - widthScale);
1191
1192                     // scale limit of height is 300%.
1193                     topOverShootingShadowView.SizeHeight = newDisplacement > overShootingShadowScaleHeightLimit ? overShootingShadowScaleHeightLimit : newDisplacement;
1194
1195                     // trigger event
1196                     ScrollOutOfBoundEventArgs.Direction scrollDirection = panDisplacement > 0 ?
1197                        ScrollOutOfBoundEventArgs.Direction.Down : ScrollOutOfBoundEventArgs.Direction.Up;
1198                     OnScrollOutOfBound(scrollDirection, totalPanDisplacement);
1199                 }
1200             }
1201             else if (totalPanDisplacement < 0) // upwards
1202             {
1203                 // check if reaching at the bottom.
1204                 if (-(int)finalTargetPosition != (int)maxScrollDistance)
1205                 {
1206                     isOverShootingShadowShown = false;
1207                     return;
1208                 }
1209
1210                 // save start displacement, and re-calculate displacement.
1211                 if (!isOverShootingShadowShown)
1212                 {
1213                     startShowShadowDisplacement = totalPanDisplacement;
1214                 }
1215                 isOverShootingShadowShown = true;
1216
1217                 float newDisplacement = (int)startShowShadowDisplacement < (int)totalPanDisplacement ? 0 : startShowShadowDisplacement - totalPanDisplacement;
1218
1219                 if (ScrollingDirection == Direction.Horizontal)
1220                 {
1221                     // scale limit of height is 60%.
1222                     float heightScale = newDisplacement / overShootingShadowScaleHeightLimit;
1223                     rightOverShootingShadowView.SizeHeight = heightScale > 0.6f ? SizeHeight * 0.4f : SizeHeight * (1.0f - heightScale);
1224
1225                     // scale limit of width is 300%.
1226                     rightOverShootingShadowView.SizeWidth = newDisplacement > overShootingShadowScaleHeightLimit ? overShootingShadowScaleHeightLimit : newDisplacement;
1227
1228                     // trigger event
1229                     ScrollOutOfBoundEventArgs.Direction scrollDirection = panDisplacement > 0 ?
1230                        ScrollOutOfBoundEventArgs.Direction.Right : ScrollOutOfBoundEventArgs.Direction.Left;
1231                     OnScrollOutOfBound(scrollDirection, totalPanDisplacement);
1232                 }
1233                 else
1234                 {
1235                     // scale limit of width is 60%.
1236                     float widthScale = newDisplacement / overShootingShadowScaleHeightLimit;
1237                     bottomOverShootingShadowView.SizeWidth = widthScale > 0.6f ? SizeWidth * 0.4f : SizeWidth * (1.0f - widthScale);
1238
1239                     // scale limit of height is 300%.
1240                     bottomOverShootingShadowView.SizeHeight = newDisplacement > overShootingShadowScaleHeightLimit ? overShootingShadowScaleHeightLimit : newDisplacement;
1241
1242                     // trigger event
1243                     ScrollOutOfBoundEventArgs.Direction scrollDirection = panDisplacement > 0 ?
1244                        ScrollOutOfBoundEventArgs.Direction.Down : ScrollOutOfBoundEventArgs.Direction.Up;
1245                     OnScrollOutOfBound(scrollDirection, totalPanDisplacement);
1246                 }
1247             }
1248             else
1249             {
1250                 // if total displacement is 0, shadow would become invisible.
1251                 isOverShootingShadowShown = false;
1252             }
1253         }
1254
1255         private void PlayOverShootingShadowAnimation()
1256         {
1257             if (!EnableOverShootingEffect)
1258                 return;
1259
1260             // stop animation if necessary.
1261             StopOverShootingShadowAnimation();
1262
1263             if (overShootingShadowAnimation == null)
1264             {
1265                 overShootingShadowAnimation = new Animation(overShootingShadowAnimationDuration);
1266                 overShootingShadowAnimation.Finished += OnOverShootingShadowAnimationFinished;
1267             }
1268
1269             if (ScrollingDirection == Direction.Horizontal)
1270             {
1271                 View targetView = totalDisplacementForPan < 0 ? rightOverShootingShadowView : leftOverShootingShadowView;
1272                 overShootingShadowAnimation.AnimateTo(targetView, "SizeHeight", SizeHeight);
1273                 overShootingShadowAnimation.AnimateTo(targetView, "SizeWidth", 0.0f);
1274                 overShootingShadowAnimation.AnimateTo(targetView, "Opacity", 0.0f);
1275             }
1276             else
1277             {
1278                 View targetView = totalDisplacementForPan < 0 ? bottomOverShootingShadowView : topOverShootingShadowView;
1279                 overShootingShadowAnimation.AnimateTo(targetView, "SizeWidth", SizeWidth);
1280                 overShootingShadowAnimation.AnimateTo(targetView, "SizeHeight", 0.0f);
1281                 overShootingShadowAnimation.AnimateTo(targetView, "Opacity", 0.0f);
1282             }
1283             overShootingShadowAnimation.Play();
1284         }
1285
1286         private void StopOverShootingShadowAnimation()
1287         {
1288             if (overShootingShadowAnimation == null || overShootingShadowAnimation.State != Animation.States.Playing)
1289                 return;
1290
1291             overShootingShadowAnimation.Stop(Animation.EndActions.Cancel);
1292             OnOverShootingShadowAnimationFinished(null, null);
1293             overShootingShadowAnimation.Clear();
1294         }
1295
1296         private void OnOverShootingShadowAnimationFinished(object sender, EventArgs e)
1297         {
1298             if (ScrollingDirection == Direction.Horizontal)
1299             {
1300                 base.Remove(leftOverShootingShadowView);
1301                 base.Remove(rightOverShootingShadowView);
1302
1303                 leftOverShootingShadowView.Size = new Size(0.0f, SizeHeight);
1304                 rightOverShootingShadowView.Size = new Size(0.0f, SizeHeight);
1305             }
1306             else
1307             {
1308                 base.Remove(topOverShootingShadowView);
1309                 base.Remove(bottomOverShootingShadowView);
1310
1311                 topOverShootingShadowView.Size = new Size(SizeWidth, 0.0f);
1312                 bottomOverShootingShadowView.Size = new Size(SizeWidth, 0.0f);
1313             }
1314
1315             // after animation finished, height/width & opacity of vertical shadow both are 0, so it is invisible.
1316             isOverShootingShadowShown = false;
1317         }
1318
1319         private void OnScrollOutOfBound(ScrollOutOfBoundEventArgs.Direction direction, float displacement)
1320         {
1321             ScrollOutOfBoundEventArgs args = new ScrollOutOfBoundEventArgs(direction, displacement);
1322             ScrollOutOfBound?.Invoke(this, args);
1323         }
1324
1325         private void OnPanGestureDetected(object source, PanGestureDetector.DetectedEventArgs e)
1326         {
1327             OnPanGesture(e.PanGesture);
1328         }
1329
1330         private void OnPanGesture(PanGesture panGesture)
1331         {
1332             if (SnapToPage && scrollAnimation != null && scrollAnimation.State == Animation.States.Playing)
1333             {
1334                 return;
1335             }
1336
1337             if (panGesture.State == Gesture.StateType.Started)
1338             {
1339                 readyToNotice = false;
1340                 //Interrupt touching when panning is started
1341                 this.InterceptTouchEvent += OnInterruptTouchingChildTouched;
1342                 AttachOverShootingShadowView();
1343                 Debug.WriteLineIf(LayoutDebugScrollableBase, "Gesture Start");
1344                 if (scrolling && !SnapToPage)
1345                 {
1346                     StopScroll();
1347                 }
1348                 totalDisplacementForPan = 0.0f;
1349                 OnScrollDragStarted();
1350             }
1351             else if (panGesture.State == Gesture.StateType.Continuing)
1352             {
1353                 if (ScrollingDirection == Direction.Horizontal)
1354                 {
1355                     // if vertical shadow is shown, does not scroll.
1356                     if (!isOverShootingShadowShown)
1357                     {
1358                         ScrollBy(panGesture.Displacement.X, false);
1359                     }
1360                     totalDisplacementForPan += panGesture.Displacement.X;
1361                     DragOverShootingShadow(totalDisplacementForPan, panGesture.Displacement.X);
1362                 }
1363                 else
1364                 {
1365                     // if vertical shadow is shown, does not scroll.
1366                     if (!isOverShootingShadowShown)
1367                     {
1368                         ScrollBy(panGesture.Displacement.Y, false);
1369                     }
1370                     totalDisplacementForPan += panGesture.Displacement.Y;
1371                     DragOverShootingShadow(totalDisplacementForPan, panGesture.Displacement.Y);
1372                 }
1373                 Debug.WriteLineIf(LayoutDebugScrollableBase, "OnPanGestureDetected Continue totalDisplacementForPan:" + totalDisplacementForPan);
1374             }
1375             else if (panGesture.State == Gesture.StateType.Finished || panGesture.State == Gesture.StateType.Cancelled)
1376             {
1377                 PlayOverShootingShadowAnimation();
1378                 OnScrollDragEnded();
1379                 StopScroll(); // Will replace previous animation so will stop existing one.
1380
1381                 if (scrollAnimation == null)
1382                 {
1383                     scrollAnimation = new Animation();
1384                     scrollAnimation.Finished += ScrollAnimationFinished;
1385                 }
1386
1387                 float panVelocity = (ScrollingDirection == Direction.Horizontal) ? panGesture.Velocity.X : panGesture.Velocity.Y;
1388
1389                 if (SnapToPage)
1390                 {
1391                     PageSnap(panVelocity);
1392                 }
1393                 else
1394                 {
1395                     if (panVelocity == 0)
1396                     {
1397                         float currentScrollPosition = (ScrollingDirection == Direction.Horizontal ? ContentContainer.CurrentPosition.X : ContentContainer.CurrentPosition.Y);
1398                         scrollAnimation.DefaultAlphaFunction = new AlphaFunction(AlphaFunction.BuiltinFunctions.Linear);
1399                         scrollAnimation.Duration = 0;
1400                         scrollAnimation.AnimateTo(ContentContainer, (ScrollingDirection == Direction.Horizontal) ? "PositionX" : "PositionY", currentScrollPosition);
1401                         scrollAnimation.Play();
1402                     }
1403                     else
1404                     {
1405                         Decelerating(panVelocity, scrollAnimation);
1406                     }
1407                 }
1408
1409                 totalDisplacementForPan = 0;
1410                 scrolling = true;
1411                 readyToNotice = true;
1412                 OnScrollAnimationStarted();
1413             }
1414         }
1415
1416         internal void BaseRemove(View view)
1417         {
1418             base.Remove(view);
1419         }
1420
1421         internal override bool OnAccessibilityPan(PanGesture gestures)
1422         {
1423             if (SnapToPage && scrollAnimation != null && scrollAnimation.State == Animation.States.Playing)
1424             {
1425                 return false;
1426             }
1427
1428             OnPanGesture(gestures);
1429             return true;
1430         }
1431
1432         private float CustomScrollAlphaFunction(float progress)
1433         {
1434             if (panAnimationDelta == 0)
1435             {
1436                 return 1.0f;
1437             }
1438             else
1439             {
1440                 // Parameter "progress" is normalized value. We need to multiply target duration to calculate distance.
1441                 // Can get real distance using equation of deceleration (check Decelerating function)
1442                 // After get real distance, normalize it
1443                 float realDuration = progress * panAnimationDuration;
1444                 float realDistance = velocityOfLastPan * ((float)Math.Pow(decelerationRate, realDuration) - 1) / logValueOfDeceleration;
1445                 float result = Math.Min(realDistance / Math.Abs(panAnimationDelta), 1.0f);
1446                 return result;
1447             }
1448         }
1449
1450         /// <summary>
1451         /// you can override it to custom your decelerating
1452         /// </summary>
1453         /// <param name="velocity">Velocity of current pan.</param>
1454         /// <param name="animation">Scroll animation.</param>
1455         [EditorBrowsable(EditorBrowsableState.Never)]
1456         protected virtual void Decelerating(float velocity, Animation animation)
1457         {
1458             // Decelerating using deceleration equation ===========
1459             //
1460             // V   : velocity (pixel per millisecond)
1461             // V0  : initial velocity
1462             // d   : deceleration rate,
1463             // t   : time
1464             // X   : final position after decelerating
1465             // log : natural logarithm
1466             //
1467             // V(t) = V0 * d pow t;
1468             // X(t) = V0 * (d pow t - 1) / log d;  <-- Integrate the velocity function
1469             // X(∞) = V0 * d / (1 - d); <-- Result using infinite T can be final position because T is tending to infinity.
1470             //
1471             // Because of final T is tending to infinity, we should use threshold value to finish.
1472             // Final T = log(-threshold * log d / |V0| ) / log d;
1473
1474             velocityOfLastPan = Math.Abs(velocity);
1475
1476             float currentScrollPosition = -(ScrollingDirection == Direction.Horizontal ? ContentContainer.CurrentPosition.X : ContentContainer.CurrentPosition.Y);
1477             panAnimationDelta = (velocityOfLastPan * decelerationRate) / (1 - decelerationRate);
1478             panAnimationDelta = velocity > 0 ? -panAnimationDelta : panAnimationDelta;
1479
1480             float destination = -(panAnimationDelta + currentScrollPosition);
1481             float adjustDestination = AdjustTargetPositionOfScrollAnimation(destination);
1482             float maxPosition = ScrollAvailableArea != null ? ScrollAvailableArea.Y : maxScrollDistance;
1483             float minPosition = ScrollAvailableArea != null ? ScrollAvailableArea.X : 0;
1484
1485             if (destination < -maxPosition || destination > minPosition)
1486             {
1487                 panAnimationDelta = velocity > 0 ? (currentScrollPosition - minPosition) : (maxPosition - currentScrollPosition);
1488                 destination = velocity > 0 ? minPosition : -maxPosition;
1489
1490                 if (panAnimationDelta == 0)
1491                 {
1492                     panAnimationDuration = 0.0f;
1493                 }
1494                 else
1495                 {
1496                     panAnimationDuration = (float)Math.Log((panAnimationDelta * logValueOfDeceleration / velocityOfLastPan + 1), decelerationRate);
1497                 }
1498
1499                 Debug.WriteLineIf(LayoutDebugScrollableBase, "\n" +
1500                     "OverRange======================= \n" +
1501                     "[decelerationRate] " + decelerationRate + "\n" +
1502                     "[logValueOfDeceleration] " + logValueOfDeceleration + "\n" +
1503                     "[Velocity] " + velocityOfLastPan + "\n" +
1504                     "[CurrentPosition] " + currentScrollPosition + "\n" +
1505                     "[CandidateDelta] " + panAnimationDelta + "\n" +
1506                     "[Destination] " + destination + "\n" +
1507                     "[Duration] " + panAnimationDuration + "\n" +
1508                     "================================ \n"
1509                 );
1510             }
1511             else
1512             {
1513                 panAnimationDuration = (float)Math.Log(-DecelerationThreshold * logValueOfDeceleration / velocityOfLastPan) / logValueOfDeceleration;
1514
1515                 if (adjustDestination != destination)
1516                 {
1517                     destination = adjustDestination;
1518                     panAnimationDelta = destination + currentScrollPosition;
1519                     velocityOfLastPan = Math.Abs(panAnimationDelta * logValueOfDeceleration / ((float)Math.Pow(decelerationRate, panAnimationDuration) - 1));
1520                     panAnimationDuration = (float)Math.Log(-DecelerationThreshold * logValueOfDeceleration / velocityOfLastPan) / logValueOfDeceleration;
1521                 }
1522
1523                 Debug.WriteLineIf(LayoutDebugScrollableBase, "\n" +
1524                     "================================ \n" +
1525                     "[decelerationRate] " + decelerationRate + "\n" +
1526                     "[logValueOfDeceleration] " + logValueOfDeceleration + "\n" +
1527                     "[Velocity] " + velocityOfLastPan + "\n" +
1528                     "[CurrentPosition] " + currentScrollPosition + "\n" +
1529                     "[CandidateDelta] " + panAnimationDelta + "\n" +
1530                     "[Destination] " + destination + "\n" +
1531                     "[Duration] " + panAnimationDuration + "\n" +
1532                     "================================ \n"
1533                 );
1534             }
1535
1536             finalTargetPosition = destination;
1537
1538             customScrollAlphaFunction = new UserAlphaFunctionDelegate(CustomScrollAlphaFunction);
1539             animation.DefaultAlphaFunction = new AlphaFunction(customScrollAlphaFunction);
1540             GC.KeepAlive(customScrollAlphaFunction);
1541             animation.Duration = (int)panAnimationDuration;
1542             animation.AnimateTo(ContentContainer, (ScrollingDirection == Direction.Horizontal) ? "PositionX" : "PositionY", destination);
1543             animation.Play();
1544         }
1545
1546         private void ScrollAnimationFinished(object sender, EventArgs e)
1547         {
1548             OnScrollAnimationEnded();
1549         }
1550
1551         /// <summary>
1552         /// Adjust scrolling position by own scrolling rules.
1553         /// Override this function when developer wants to change destination of flicking.(e.g. always snap to center of item)
1554         /// </summary>
1555         /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
1556         [EditorBrowsable(EditorBrowsableState.Never)]
1557         protected virtual float AdjustTargetPositionOfScrollAnimation(float position)
1558         {
1559             return position;
1560         }
1561
1562         /// <summary>
1563         /// Scroll position given to ScrollTo.
1564         /// This is the position in the opposite direction to the position of ContentContainer.
1565         /// </summary>
1566         /// <since_tizen> 8 </since_tizen>
1567         public Position ScrollPosition
1568         {
1569             get
1570             {
1571                 return new Position(-ContentContainer.Position);
1572             }
1573         }
1574
1575         /// <summary>
1576         /// Current scroll position in the middle of ScrollTo animation.
1577         /// This is the position in the opposite direction to the current position of ContentContainer.
1578         /// </summary>
1579         /// <since_tizen> 8 </since_tizen>
1580         public Position ScrollCurrentPosition
1581         {
1582             get
1583             {
1584                 return new Position(-ContentContainer.CurrentPosition);
1585             }
1586         }
1587
1588         /// <summary>
1589         /// Remove all children in ContentContainer.
1590         /// </summary>
1591         /// <param name="dispose">If true, removed child is disposed.</param>
1592         [EditorBrowsable(EditorBrowsableState.Never)]
1593         public void RemoveAllChildren(bool dispose = false)
1594         {
1595             RecursiveRemoveChildren(ContentContainer, dispose);
1596         }
1597
1598         private void RecursiveRemoveChildren(View parent, bool dispose)
1599         {
1600             if (parent == null)
1601             {
1602                 return;
1603             }
1604             int maxChild = (int)parent.GetChildCount();
1605             for (int i = maxChild - 1; i >= 0; --i)
1606             {
1607                 View child = parent.GetChildAt((uint)i);
1608                 if (child == null)
1609                 {
1610                     continue;
1611                 }
1612                 RecursiveRemoveChildren(child, dispose);
1613                 parent.Remove(child);
1614                 if (dispose)
1615                 {
1616                     child.Dispose();
1617                 }
1618             }
1619         }
1620
1621     }
1622
1623 } // namespace