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