[NUI] Fix the propertyNotification to be disposed in ScrollableBase
[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     [global::System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1001: Types that own disposable fields should be disposable.", Justification = "Scroll event is temporarily used for notifying scroll position update, so position will not be disposed during the event processing.")]
31     public class ScrollEventArgs : EventArgs
32     {
33         // Position class is derived class of Disposable class and they will be implicitly disposed by DisposeQueue,
34         // so that there will be no memory leak.
35         private Position position;
36         private Position scrollPosition;
37
38         /// <summary>
39         /// Default constructor.
40         /// </summary>
41         /// <param name="position">Current container position</param>
42         /// <since_tizen> 8 </since_tizen>
43         public ScrollEventArgs(Position position)
44         {
45             this.position = position;
46             this.scrollPosition = new Position(-position);
47         }
48
49         /// <summary>
50         /// Current position of ContentContainer.
51         /// </summary>
52         /// <since_tizen> 8 </since_tizen>
53         public Position Position
54         {
55             get
56             {
57                 return position;
58             }
59         }
60         /// <summary>
61         /// Current scroll position of scrollableBase pan.
62         /// This is the position in the opposite direction to the current position of ContentContainer.
63         /// </summary>
64         [EditorBrowsable(EditorBrowsableState.Never)]
65         public Position ScrollPosition
66         {
67             get
68             {
69                 return scrollPosition;
70             }
71         }
72     }
73
74     /// <summary>
75     /// ScrollOutofBoundEventArgs is to record scroll out-of-bound event arguments which will be sent to user.
76     /// </summary>
77     [EditorBrowsable(EditorBrowsableState.Never)]
78     public class ScrollOutOfBoundEventArgs : EventArgs
79     {
80         /// <summary>
81         /// The direction to be touched.
82         /// </summary>
83         [EditorBrowsable(EditorBrowsableState.Never)]
84         public enum Direction
85         {
86             /// <summary>
87             /// Upwards.
88             /// </summary>
89             [EditorBrowsable(EditorBrowsableState.Never)]
90             Up,
91
92             /// <summary>
93             /// Downwards.
94             /// </summary>
95             [EditorBrowsable(EditorBrowsableState.Never)]
96             Down,
97
98             /// <summary>
99             /// Left bound.
100             /// </summary>
101             [EditorBrowsable(EditorBrowsableState.Never)]
102             Left,
103
104             /// <summary>
105             /// Right bound.
106             /// </summary>
107             [EditorBrowsable(EditorBrowsableState.Never)]
108             Right,
109         }
110
111         /// <summary>
112         /// Constructor.
113         /// </summary>
114         /// <param name="direction">Current pan direction</param>
115         /// <param name="displacement">Current total displacement</param>
116         [EditorBrowsable(EditorBrowsableState.Never)]
117         public ScrollOutOfBoundEventArgs(Direction direction, float displacement)
118         {
119             PanDirection = direction;
120             Displacement = displacement;
121         }
122
123         /// <summary>
124         /// Current pan direction of ContentContainer.
125         /// </summary>
126         [EditorBrowsable(EditorBrowsableState.Never)]
127         public Direction PanDirection
128         {
129             get;
130         }
131
132         /// <summary>
133         /// Current total displacement of ContentContainer.
134         /// if its value is greater than 0, it is at the top/left;
135         /// if less than 0, it is at the bottom/right.
136         /// </summary>
137         [EditorBrowsable(EditorBrowsableState.Never)]
138         public float Displacement
139         {
140             get;
141         }
142     }
143
144     /// <summary>
145     /// This class provides a View that can scroll a single View with a layout. This View can be a nest of Views.
146     /// </summary>
147     /// <since_tizen> 8 </since_tizen>
148     public partial class ScrollableBase : Control
149     {
150         static bool LayoutDebugScrollableBase = false; // Debug flag
151         static bool focusDebugScrollableBase = false; // Debug flag
152         private Direction mScrollingDirection = Direction.Vertical;
153         private bool mScrollEnabled = true;
154         private int mScrollDuration = 125;
155         private int mPageWidth = 0;
156         private float mPageFlickThreshold = 0.4f;
157         private float mScrollingEventThreshold = 0.001f;
158         private bool fadeScrollbar = true;
159
160         private class ScrollableBaseCustomLayout : AbsoluteLayout
161         {
162             protected override void OnMeasure(MeasureSpecification widthMeasureSpec, MeasureSpecification heightMeasureSpec)
163             {
164                 MeasuredSize.StateType childWidthState = MeasuredSize.StateType.MeasuredSizeOK;
165                 MeasuredSize.StateType childHeightState = MeasuredSize.StateType.MeasuredSizeOK;
166
167                 Direction scrollingDirection = Direction.Vertical;
168                 ScrollableBase scrollableBase = this.Owner as ScrollableBase;
169                 if (scrollableBase != null)
170                 {
171                     scrollingDirection = scrollableBase.ScrollingDirection;
172                 }
173
174                 float totalWidth = 0.0f;
175                 float totalHeight = 0.0f;
176
177                 // measure child, should be a single scrolling child
178                 foreach (LayoutItem childLayout in LayoutChildren)
179                 {
180                     if (childLayout != null && childLayout.Owner.Name == "ContentContainer")
181                     {
182                         // Get size of child
183                         // Use an Unspecified MeasureSpecification mode so scrolling child is not restricted to it's parents size in Height (for vertical scrolling)
184                         // or Width for horizontal scrolling
185                         if (scrollingDirection == Direction.Vertical)
186                         {
187                             MeasureSpecification unrestrictedMeasureSpec = new MeasureSpecification(heightMeasureSpec.Size, MeasureSpecification.ModeType.Unspecified);
188                             MeasureChildWithMargins(childLayout, widthMeasureSpec, new LayoutLength(0), unrestrictedMeasureSpec, new LayoutLength(0)); // Height unrestricted by parent
189                         }
190                         else
191                         {
192                             MeasureSpecification unrestrictedMeasureSpec = new MeasureSpecification(widthMeasureSpec.Size, MeasureSpecification.ModeType.Unspecified);
193                             MeasureChildWithMargins(childLayout, unrestrictedMeasureSpec, new LayoutLength(0), heightMeasureSpec, new LayoutLength(0)); // Width unrestricted by parent
194                         }
195
196                         totalWidth = (childLayout.MeasuredWidth.Size + (childLayout.Padding.Start + childLayout.Padding.End)).AsDecimal();
197                         totalHeight = (childLayout.MeasuredHeight.Size + (childLayout.Padding.Top + childLayout.Padding.Bottom)).AsDecimal();
198
199                         if (childLayout.MeasuredWidth.State == MeasuredSize.StateType.MeasuredSizeTooSmall)
200                         {
201                             childWidthState = MeasuredSize.StateType.MeasuredSizeTooSmall;
202                         }
203                         if (childLayout.MeasuredHeight.State == MeasuredSize.StateType.MeasuredSizeTooSmall)
204                         {
205                             childHeightState = MeasuredSize.StateType.MeasuredSizeTooSmall;
206                         }
207                     }
208                 }
209
210                 MeasuredSize widthSizeAndState = ResolveSizeAndState(new LayoutLength(totalWidth), widthMeasureSpec, MeasuredSize.StateType.MeasuredSizeOK);
211                 MeasuredSize heightSizeAndState = ResolveSizeAndState(new LayoutLength(totalHeight), heightMeasureSpec, MeasuredSize.StateType.MeasuredSizeOK);
212                 totalWidth = widthSizeAndState.Size.AsDecimal();
213                 totalHeight = heightSizeAndState.Size.AsDecimal();
214
215                 // Ensure layout respects it's given minimum size
216                 totalWidth = Math.Max(totalWidth, SuggestedMinimumWidth.AsDecimal());
217                 totalHeight = Math.Max(totalHeight, SuggestedMinimumHeight.AsDecimal());
218
219                 widthSizeAndState.State = childWidthState;
220                 heightSizeAndState.State = childHeightState;
221
222                 SetMeasuredDimensions(ResolveSizeAndState(new LayoutLength(totalWidth), widthMeasureSpec, childWidthState),
223                     ResolveSizeAndState(new LayoutLength(totalHeight), heightMeasureSpec, childHeightState));
224
225                 // Size of ScrollableBase is changed. Change Page width too.
226                 if (scrollableBase != null)
227                 {
228                     scrollableBase.mPageWidth = (int)MeasuredWidth.Size.AsRoundedValue();
229                     scrollableBase.OnScrollingChildRelayout(null, null);
230                 }
231             }
232         } //  ScrollableBaseCustomLayout
233
234         /// <summary>
235         /// The direction axis to scroll.
236         /// </summary>
237         /// <since_tizen> 8 </since_tizen>
238         public enum Direction
239         {
240             /// <summary>
241             /// Horizontal axis.
242             /// </summary>
243             /// <since_tizen> 8 </since_tizen>
244             Horizontal,
245
246             /// <summary>
247             /// Vertical axis.
248             /// </summary>
249             /// <since_tizen> 8 </since_tizen>
250             Vertical
251         }
252
253         /// <summary>
254         /// Scrolling direction mode.
255         /// Default is Vertical scrolling.
256         /// </summary>
257         /// <since_tizen> 8 </since_tizen>
258         public Direction ScrollingDirection
259         {
260             get
261             {
262                 return (Direction)GetValue(ScrollingDirectionProperty);
263             }
264             set
265             {
266                 SetValue(ScrollingDirectionProperty, value);
267                 NotifyPropertyChanged();
268             }
269         }
270         private Direction InternalScrollingDirection
271         {
272             get
273             {
274                 return mScrollingDirection;
275             }
276             set
277             {
278                 if (value != mScrollingDirection)
279                 {
280                     //Reset scroll position and stop scroll animation
281                     ScrollTo(0, false);
282
283                     mScrollingDirection = value;
284                     mPanGestureDetector.ClearAngles();
285                     mPanGestureDetector.AddDirection(value == Direction.Horizontal ?
286                         PanGestureDetector.DirectionHorizontal : PanGestureDetector.DirectionVertical);
287
288                     ContentContainer.WidthSpecification = ScrollingDirection == Direction.Vertical ? LayoutParamPolicies.MatchParent : LayoutParamPolicies.WrapContent;
289                     ContentContainer.HeightSpecification = ScrollingDirection == Direction.Vertical ? LayoutParamPolicies.WrapContent : LayoutParamPolicies.MatchParent;
290                     SetScrollbar();
291                 }
292             }
293         }
294
295         /// <summary>
296         /// Enable or disable scrolling.
297         /// </summary>
298         /// <since_tizen> 8 </since_tizen>
299         public bool ScrollEnabled
300         {
301             get
302             {
303                 return (bool)GetValue(ScrollEnabledProperty);
304             }
305             set
306             {
307                 SetValue(ScrollEnabledProperty, value);
308                 NotifyPropertyChanged();
309             }
310         }
311         private bool InternalScrollEnabled
312         {
313             get
314             {
315                 return mScrollEnabled;
316             }
317             set
318             {
319                 if (value != mScrollEnabled)
320                 {
321                     mScrollEnabled = value;
322                     if (mScrollEnabled)
323                     {
324                         mPanGestureDetector.Detected += OnPanGestureDetected;
325                     }
326                     else
327                     {
328                         mPanGestureDetector.Detected -= OnPanGestureDetected;
329                     }
330                 }
331             }
332         }
333
334         /// <summary>
335         /// Gets scrollable status.
336         /// </summary>
337         [EditorBrowsable(EditorBrowsableState.Never)]
338         protected override bool AccessibilityIsScrollable()
339         {
340             return true;
341         }
342
343         /// <summary>
344         /// Pages mode, enables moving to the next or return to current page depending on pan displacement.
345         /// Default is false.
346         /// </summary>
347         /// <since_tizen> 8 </since_tizen>
348         public bool SnapToPage
349         {
350             get
351             {
352                 return (bool)GetValue(SnapToPageProperty);
353             }
354             set
355             {
356                 SetValue(SnapToPageProperty, value);
357                 NotifyPropertyChanged();
358             }
359         }
360         private bool InternalSnapToPage { set; get; } = false;
361
362         /// <summary>
363         /// Get current page.
364         /// Working property with SnapToPage property.
365         /// </summary>
366         /// <since_tizen> 8 </since_tizen>
367         public int CurrentPage { get; private set; } = 0;
368
369         /// <summary>
370         /// Duration of scroll animation.
371         /// Default value is 125ms.
372         /// </summary>
373         /// <since_tizen> 8 </since_tizen>
374         public int ScrollDuration
375         {
376             get
377             {
378                 return (int)GetValue(ScrollDurationProperty);
379             }
380             set
381             {
382                 SetValue(ScrollDurationProperty, value);
383                 NotifyPropertyChanged();
384             }
385         }
386         private int InternalScrollDuration
387         {
388             set
389             {
390                 mScrollDuration = value >= 0 ? value : mScrollDuration;
391             }
392             get
393             {
394                 return mScrollDuration;
395             }
396         }
397
398         /// <summary>
399         /// Scroll Available area.
400         /// </summary>
401         /// <since_tizen> 8 </since_tizen>
402         public Vector2 ScrollAvailableArea
403         {
404             get
405             {
406                 return GetValue(ScrollAvailableAreaProperty) as Vector2;
407             }
408             set
409             {
410                 SetValue(ScrollAvailableAreaProperty, value);
411                 NotifyPropertyChanged();
412             }
413         }
414         private Vector2 InternalScrollAvailableArea { set; get; }
415
416         /// <summary>
417         /// An event emitted when user starts dragging ScrollableBase, user can subscribe or unsubscribe to this event handler.<br />
418         /// </summary>
419         /// <since_tizen> 8 </since_tizen>
420         public event EventHandler<ScrollEventArgs> ScrollDragStarted;
421
422         /// <summary>
423         /// An event emitted when user stops dragging ScrollableBase, user can subscribe or unsubscribe to this event handler.<br />
424         /// </summary>
425         /// <since_tizen> 8 </since_tizen>
426         public event EventHandler<ScrollEventArgs> ScrollDragEnded;
427
428         /// <summary>
429         /// An event emitted when the scrolling slide animation starts, user can subscribe or unsubscribe to this event handler.<br />
430         /// </summary>
431         /// <since_tizen> 8 </since_tizen>
432         public event EventHandler<ScrollEventArgs> ScrollAnimationStarted;
433
434         /// <summary>
435         /// An event emitted when the scrolling slide animation ends, user can subscribe or unsubscribe to this event handler.<br />
436         /// </summary>
437         /// <since_tizen> 8 </since_tizen>
438         public event EventHandler<ScrollEventArgs> ScrollAnimationEnded;
439
440         /// <summary>
441         /// An event emitted when scrolling, user can subscribe or unsubscribe to this event handler.<br />
442         /// </summary>
443         /// <since_tizen> 8 </since_tizen>
444         public event EventHandler<ScrollEventArgs> Scrolling;
445
446         /// <summary>
447         /// An event emitted when scrolling out of bound, user can subscribe or unsubscribe to this event handler.<br />
448         /// </summary>
449         [EditorBrowsable(EditorBrowsableState.Never)]
450         public event EventHandler<ScrollOutOfBoundEventArgs> ScrollOutOfBound;
451
452         /// <summary>
453         /// Scrollbar for ScrollableBase.
454         /// </summary>
455         /// <since_tizen> 8 </since_tizen>
456         public ScrollbarBase Scrollbar
457         {
458             get
459             {
460                 return GetValue(ScrollbarProperty) as ScrollbarBase;
461             }
462             set
463             {
464                 SetValue(ScrollbarProperty, value);
465                 NotifyPropertyChanged();
466             }
467         }
468         private ScrollbarBase InternalScrollbar
469         {
470             get
471             {
472                 return scrollBar;
473             }
474             set
475             {
476                 if (scrollBar)
477                 {
478                     base.Remove(scrollBar);
479                 }
480                 scrollBar = value;
481
482                 if (scrollBar != null)
483                 {
484                     scrollBar.Name = "ScrollBar";
485                     base.Add(scrollBar);
486
487                     if (hideScrollbar)
488                     {
489                         scrollBar.Hide();
490                     }
491                     else
492                     {
493                         scrollBar.Show();
494                     }
495
496                     SetScrollbar();
497                 }
498             }
499         }
500
501         /// <summary>
502         /// Always hide Scrollbar.
503         /// </summary>
504         /// <since_tizen> 8 </since_tizen>
505         public bool HideScrollbar
506         {
507             get
508             {
509                 return (bool)GetValue(HideScrollbarProperty);
510             }
511             set
512             {
513                 SetValue(HideScrollbarProperty, value);
514                 NotifyPropertyChanged();
515             }
516         }
517         private bool InternalHideScrollbar
518         {
519             get
520             {
521                 return hideScrollbar;
522             }
523             set
524             {
525                 hideScrollbar = value;
526
527                 if (scrollBar)
528                 {
529                     if (value)
530                     {
531                         scrollBar.Hide();
532                     }
533                     else
534                     {
535                         scrollBar.Show();
536                         if (fadeScrollbar)
537                         {
538                             scrollBar.Opacity = 1.0f;
539                             scrollBar.FadeOut();
540                         }
541                     }
542                 }
543             }
544         }
545
546         /// <summary>
547         /// The boolean flag for automatic fading Scrollbar.
548         /// Scrollbar will be faded out when scroll stay in certain position longer than the threshold.
549         /// Scrollbar will be faded in scroll position changes.
550         /// </summary>
551         [EditorBrowsable(EditorBrowsableState.Never)]
552         public bool FadeScrollbar
553         {
554             get => (bool)GetValue(FadeScrollbarProperty);
555             set => SetValue(FadeScrollbarProperty, value);
556         }
557
558         private bool InternalFadeScrollbar
559         {
560             get
561             {
562                 return fadeScrollbar;
563             }
564             set
565             {
566                 fadeScrollbar = value;
567
568                 if (scrollBar != null && !hideScrollbar)
569                 {
570                     if (value)
571                     {
572                         scrollBar.FadeOut();
573                     }
574                     else
575                     {
576                         scrollBar.Opacity = 1.0f;
577                         // Removing fadeout timer and animation.
578                         scrollBar.FadeIn();
579                     }
580                 }
581             }
582         }
583
584         /// <summary>
585         /// Container which has content of ScrollableBase.
586         /// </summary>
587         /// <since_tizen> 8 </since_tizen>
588         public View ContentContainer { get; private set; }
589
590         /// <summary>
591         /// Set the layout on this View. Replaces any existing Layout.
592         /// </summary>
593         /// <since_tizen> 8 </since_tizen>
594         public new LayoutItem Layout
595         {
596             get
597             {
598                 return GetValue(LayoutProperty) as LayoutItem;
599             }
600             set
601             {
602                 SetValue(LayoutProperty, value);
603                 NotifyPropertyChanged();
604             }
605         }
606         private LayoutItem InternalLayout
607         {
608             get
609             {
610                 return ContentContainer.Layout;
611             }
612             set
613             {
614                 ContentContainer.Layout = value;
615             }
616         }
617
618         /// <summary>
619         /// List of children of Container.
620         /// </summary>
621         /// <since_tizen> 8 </since_tizen>
622         public new List<View> Children
623         {
624             get
625             {
626                 return ContentContainer.Children;
627             }
628         }
629
630         /// <summary>
631         /// Deceleration rate of scrolling by finger.
632         /// Rate should be bigger than 0 and smaller than 1.
633         /// Default value is 0.998f;
634         /// </summary>
635         /// <since_tizen> 8 </since_tizen>
636         public float DecelerationRate
637         {
638             get
639             {
640                 return (float)GetValue(DecelerationRateProperty);
641             }
642             set
643             {
644                 SetValue(DecelerationRateProperty, value);
645                 NotifyPropertyChanged();
646             }
647         }
648         private float InternalDecelerationRate
649         {
650             get
651             {
652                 return decelerationRate;
653             }
654             set
655             {
656                 decelerationRate = (value < 1 && value > 0) ? value : decelerationRate;
657                 logValueOfDeceleration = (float)Math.Log(value);
658             }
659         }
660
661         /// <summary>
662         /// Threshold not to go infinite at the end of scrolling animation.
663         /// </summary>
664         [EditorBrowsable(EditorBrowsableState.Never)]
665         public float DecelerationThreshold
666         {
667             get
668             {
669                 return (float)GetValue(DecelerationThresholdProperty);
670             }
671             set
672             {
673                 SetValue(DecelerationThresholdProperty, value);
674                 NotifyPropertyChanged();
675             }
676         }
677         private float InternalDecelerationThreshold { get; set; } = 0.1f;
678
679         /// <summary>
680         /// Scrolling event will be thrown when this amount of scroll position is changed.
681         /// If this threshold becomes smaller, the tracking detail increases but the scrolling range that can be tracked becomes smaller.
682         /// If large sized ContentContainer is required, please use larger threshold value.
683         /// Default ScrollingEventThreshold value is 0.001f.
684         /// </summary>
685         [EditorBrowsable(EditorBrowsableState.Never)]
686         public float ScrollingEventThreshold
687         {
688             get
689             {
690                 return (float)GetValue(ScrollingEventThresholdProperty);
691             }
692             set
693             {
694                 SetValue(ScrollingEventThresholdProperty, value);
695                 NotifyPropertyChanged();
696             }
697         }
698         private float InternalScrollingEventThreshold
699         {
700             get
701             {
702                 return mScrollingEventThreshold;
703             }
704             set
705             {
706                 if (mScrollingEventThreshold != value && value > 0)
707                 {
708                     ContentContainer.RemovePropertyNotification(propertyNotification);
709                     propertyNotification = ContentContainer.AddPropertyNotification("position", PropertyCondition.Step(value));
710                     propertyNotification.Notified += OnPropertyChanged;
711                     mScrollingEventThreshold = value;
712                 }
713             }
714         }
715
716         /// <summary>
717         /// Page will be changed when velocity of panning is over threshold.
718         /// The unit of threshold is pixel per millisecond.
719         /// </summary>
720         /// <since_tizen> 8 </since_tizen>
721         public float PageFlickThreshold
722         {
723             get
724             {
725                 return (float)GetValue(PageFlickThresholdProperty);
726             }
727             set
728             {
729                 SetValue(PageFlickThresholdProperty, value);
730                 NotifyPropertyChanged();
731             }
732         }
733         private float InternalPageFlickThreshold
734         {
735             get
736             {
737                 return mPageFlickThreshold;
738             }
739             set
740             {
741                 mPageFlickThreshold = value >= 0f ? value : mPageFlickThreshold;
742             }
743         }
744
745         /// <summary>
746         /// Padding for the ScrollableBase
747         /// </summary>
748         [EditorBrowsable(EditorBrowsableState.Never)]
749         public new Extents Padding
750         {
751             get
752             {
753                 return GetValue(PaddingProperty) as Extents;
754             }
755             set
756             {
757                 SetValue(PaddingProperty, value);
758                 NotifyPropertyChanged();
759             }
760         }
761         private Extents InternalPadding
762         {
763             get
764             {
765                 return ContentContainer.Padding;
766             }
767             set
768             {
769                 ContentContainer.Padding = value;
770             }
771         }
772
773         /// <summary>
774         /// Alphafunction for scroll animation.
775         /// </summary>
776         [EditorBrowsable(EditorBrowsableState.Never)]
777         public AlphaFunction ScrollAlphaFunction
778         {
779             get
780             {
781                 return GetValue(ScrollAlphaFunctionProperty) as AlphaFunction;
782             }
783             set
784             {
785                 SetValue(ScrollAlphaFunctionProperty, value);
786                 NotifyPropertyChanged();
787             }
788         }
789         private AlphaFunction InternalScrollAlphaFunction { get; set; } = new AlphaFunction(AlphaFunction.BuiltinFunctions.Linear);
790
791         private bool hideScrollbar = true;
792         private float maxScrollDistance;
793         private float childTargetPosition = 0.0f;
794         private PanGestureDetector mPanGestureDetector;
795         private ScrollbarBase scrollBar;
796         private bool scrolling = false;
797         private float ratioOfScreenWidthToCompleteScroll = 0.5f;
798         private float totalDisplacementForPan = 0.0f;
799         private Size previousContainerSize = new Size();
800         private Size previousSize = new Size();
801         private PropertyNotification propertyNotification;
802         private float noticeAnimationEndBeforePosition = 0.0f;
803         private bool readyToNotice = false;
804
805         /// <summary>
806         /// Notice before animation is finished.
807         /// </summary>
808         [EditorBrowsable(EditorBrowsableState.Never)]
809         // Let's consider more whether this needs to be set as protected.
810         public float NoticeAnimationEndBeforePosition
811         {
812             get
813             {
814                 return (float)GetValue(NoticeAnimationEndBeforePositionProperty);
815             }
816             set
817             {
818                 SetValue(NoticeAnimationEndBeforePositionProperty, value);
819                 NotifyPropertyChanged();
820             }
821         }
822         private float InternalNoticeAnimationEndBeforePosition
823         {
824             get => noticeAnimationEndBeforePosition;
825             set => noticeAnimationEndBeforePosition = value;
826         }
827
828         /// <summary>
829         /// Step scroll move distance.
830         /// Key focus originally moves focusable objects, but in ScrollableBase,
831         /// if focusable object is too far or un-exist and ScrollableBase is focusable,
832         /// it can scroll move itself by key input.
833         /// this value decide how long distance will it moves in one step.
834         /// if any value is not set, step will be moved quater size of ScrollableBase length.
835         /// </summary>
836         [EditorBrowsable(EditorBrowsableState.Never)]
837         public float StepScrollDistance
838         {
839             get
840             {
841                 return (float)GetValue(StepScrollDistanceProperty);
842             }
843             set
844             {
845                 SetValue(StepScrollDistanceProperty, value);
846                 NotifyPropertyChanged();
847             }
848         }
849         private float stepScrollDistance = 0f;
850
851
852         // Let's consider more whether this needs to be set as protected.
853         private float finalTargetPosition;
854
855         private Animation scrollAnimation;
856         // Declare user alpha function delegate
857         [UnmanagedFunctionPointer(CallingConvention.StdCall)]
858         private delegate float UserAlphaFunctionDelegate(float progress);
859         private UserAlphaFunctionDelegate customScrollAlphaFunction;
860         private float velocityOfLastPan = 0.0f;
861         private float panAnimationDuration = 0.0f;
862         private float panAnimationDelta = 0.0f;
863         private float logValueOfDeceleration = 0.0f;
864         private float decelerationRate = 0.0f;
865
866         private View topOverShootingShadowView;
867         private View bottomOverShootingShadowView;
868         private View leftOverShootingShadowView;
869         private View rightOverShootingShadowView;
870         private const int overShootingShadowScaleHeightLimit = 64 * 3;
871         private const int overShootingShadowAnimationDuration = 300;
872         private Animation overShootingShadowAnimation;
873         private bool isOverShootingShadowShown = false;
874         private float startShowShadowDisplacement;
875
876         /// <summary>
877         /// Default Constructor
878         /// </summary>
879         /// <since_tizen> 8 </since_tizen>
880         public ScrollableBase() : base()
881         {
882             DecelerationRate = 0.998f;
883
884             base.Layout = new ScrollableBaseCustomLayout();
885             mPanGestureDetector = new PanGestureDetector();
886             mPanGestureDetector.Attach(this);
887             mPanGestureDetector.AddDirection(PanGestureDetector.DirectionVertical);
888             if (mPanGestureDetector.GetMaximumTouchesRequired() < 2) mPanGestureDetector.SetMaximumTouchesRequired(2);
889             mPanGestureDetector.Detected += OnPanGestureDetected;
890
891             ClippingMode = ClippingModeType.ClipToBoundingBox;
892
893             //Default Scrolling child
894             ContentContainer = new View()
895             {
896                 Name = "ContentContainer",
897                 WidthSpecification = ScrollingDirection == Direction.Vertical ? LayoutParamPolicies.MatchParent : LayoutParamPolicies.WrapContent,
898                 HeightSpecification = ScrollingDirection == Direction.Vertical ? LayoutParamPolicies.WrapContent : LayoutParamPolicies.MatchParent,
899             };
900             // Check if children's sizes change to update Scrollbar
901             ContentContainer.Relayout += OnScrollingChildRelayout;
902             propertyNotification = ContentContainer.AddPropertyNotification("position", PropertyCondition.Step(mScrollingEventThreshold));
903             propertyNotification.Notified += OnPropertyChanged;
904             base.Add(ContentContainer);
905             // Check if ScrollableBase's size changes to update Scrollbar
906             base.Relayout += OnScrollingChildRelayout;
907
908             Scrollbar = new Scrollbar();
909
910             //Show vertical shadow on the top (or bottom) of the scrollable when panning down (or up).
911             topOverShootingShadowView = new View
912             {
913                 BackgroundImage = FrameworkInformation.ResourcePath + "nui_component_default_scroll_over_shooting_top.png",
914                 Opacity = 1.0f,
915                 SizeHeight = 0.0f,
916                 PositionUsesPivotPoint = true,
917                 ParentOrigin = NUI.ParentOrigin.TopCenter,
918                 PivotPoint = NUI.PivotPoint.TopCenter,
919             };
920             bottomOverShootingShadowView = new View
921             {
922                 BackgroundImage = FrameworkInformation.ResourcePath + "nui_component_default_scroll_over_shooting_bottom.png",
923                 Opacity = 1.0f,
924                 SizeHeight = 0.0f,
925                 PositionUsesPivotPoint = true,
926                 ParentOrigin = NUI.ParentOrigin.BottomCenter,
927                 PivotPoint = NUI.PivotPoint.BottomCenter,
928             };
929             //Show horizontal shadow on the left (or right) of the scrollable when panning down (or up).
930             leftOverShootingShadowView = new View
931             {
932                 BackgroundImage = FrameworkInformation.ResourcePath + "nui_component_default_scroll_over_shooting_left.png",
933                 Opacity = 1.0f,
934                 SizeWidth = 0.0f,
935                 PositionUsesPivotPoint = true,
936                 ParentOrigin = NUI.ParentOrigin.CenterLeft,
937                 PivotPoint = NUI.PivotPoint.CenterLeft,
938             };
939             rightOverShootingShadowView = new View
940             {
941                 BackgroundImage = FrameworkInformation.ResourcePath + "nui_component_default_scroll_over_shooting_right.png",
942                 Opacity = 1.0f,
943                 SizeWidth = 0.0f,
944                 PositionUsesPivotPoint = true,
945                 ParentOrigin = NUI.ParentOrigin.CenterRight,
946                 PivotPoint = NUI.PivotPoint.CenterRight,
947             };
948
949             AccessibilityManager.Instance.SetAccessibilityAttribute(this, AccessibilityManager.AccessibilityAttribute.Trait, "ScrollableBase");
950
951             SetKeyboardNavigationSupport(true);
952         }
953
954         private bool OnInterruptTouchingChildTouched(object source, View.TouchEventArgs args)
955         {
956             if (args.Touch.GetState(0) == PointStateType.Down)
957             {
958                 if (scrolling && !SnapToPage)
959                 {
960                     StopScroll();
961                 }
962             }
963             return true;
964         }
965
966         private void OnPropertyChanged(object source, PropertyNotification.NotifyEventArgs args)
967         {
968             OnScroll();
969         }
970
971         /// <summary>
972         /// Called after a child has been added to the owning view.
973         /// </summary>
974         /// <param name="view">The child which has been added.</param>
975         /// <since_tizen> 8 </since_tizen>
976         public override void Add(View view)
977         {
978             ContentContainer.Add(view);
979         }
980
981         /// <summary>
982         /// Called after a child has been removed from the owning view.
983         /// </summary>
984         /// <param name="view">The child which has been removed.</param>
985         /// <since_tizen> 8 </since_tizen>
986         public override void Remove(View view)
987         {
988             if (SnapToPage && CurrentPage == Children.IndexOf(view) && CurrentPage == Children.Count - 1 && Children.Count > 1)
989             {
990                 // Target View is current page and also last child.
991                 // CurrentPage should be changed to previous page.
992                 ScrollToIndex(CurrentPage - 1);
993             }
994
995             ContentContainer.Remove(view);
996         }
997
998         private void OnScrollingChildRelayout(object source, EventArgs args)
999         {
1000             // Size is changed. Calculate maxScrollDistance.
1001             bool isSizeChanged = previousContainerSize.Width != ContentContainer.Size.Width || previousContainerSize.Height != ContentContainer.Size.Height ||
1002                 previousSize.Width != Size.Width || previousSize.Height != Size.Height;
1003
1004             if (isSizeChanged)
1005             {
1006                 maxScrollDistance = CalculateMaximumScrollDistance();
1007                 if (!ReviseContainerPositionIfNeed())
1008                 {
1009                     UpdateScrollbar();
1010                 }
1011             }
1012
1013             previousContainerSize = new Size(ContentContainer.Size);
1014             previousSize = new Size(Size);
1015         }
1016
1017         private bool ReviseContainerPositionIfNeed()
1018         {
1019             bool isHorizontal = ScrollingDirection == Direction.Horizontal;
1020             float currentPosition = isHorizontal ? ContentContainer.CurrentPosition.X : ContentContainer.CurrentPosition.Y;
1021
1022             if (Math.Abs(currentPosition) > maxScrollDistance)
1023             {
1024                 StopScroll();
1025                 var targetPosition = BoundScrollPosition(-maxScrollDistance);
1026                 if (isHorizontal) ContentContainer.PositionX = targetPosition;
1027                 else ContentContainer.PositionY = targetPosition;
1028                 return true;
1029             }
1030
1031             return false;
1032         }
1033
1034         /// <summary>
1035         /// The composition of a Scrollbar can vary depending on how you use ScrollableBase.
1036         /// Set the composition that will go into the ScrollableBase according to your ScrollableBase.
1037         /// </summary>
1038         /// <since_tizen> 8 </since_tizen>
1039         [EditorBrowsable(EditorBrowsableState.Never)]
1040         protected virtual void SetScrollbar()
1041         {
1042             if (Scrollbar)
1043             {
1044                 bool isHorizontal = ScrollingDirection == Direction.Horizontal;
1045                 float contentLength = isHorizontal ? ContentContainer.Size.Width : ContentContainer.Size.Height;
1046                 float viewportLength = isHorizontal ? Size.Width : Size.Height;
1047                 float currentPosition = isHorizontal ? ContentContainer.CurrentPosition.X : ContentContainer.CurrentPosition.Y;
1048                 Scrollbar.Initialize(contentLength, viewportLength, -currentPosition, isHorizontal);
1049             }
1050         }
1051
1052         /// Update scrollbar position and size.
1053         [EditorBrowsable(EditorBrowsableState.Never)]
1054         protected virtual void UpdateScrollbar()
1055         {
1056             if (Scrollbar)
1057             {
1058                 bool isHorizontal = ScrollingDirection == Direction.Horizontal;
1059                 float contentLength = isHorizontal ? ContentContainer.Size.Width : ContentContainer.Size.Height;
1060                 float viewportLength = isHorizontal ? Size.Width : Size.Height;
1061                 float currentPosition = isHorizontal ? ContentContainer.CurrentPosition.X : ContentContainer.CurrentPosition.Y;
1062                 Scrollbar.Update(contentLength, viewportLength, -currentPosition);
1063
1064                 if (!hideScrollbar && fadeScrollbar)
1065                 {
1066                     Scrollbar.FadeOut();
1067                 }
1068             }
1069         }
1070
1071         /// <summary>
1072         /// Scrolls to the item at the specified index.
1073         /// </summary>
1074         /// <param name="index">Index of item.</param>
1075         /// <since_tizen> 8 </since_tizen>
1076         public void ScrollToIndex(int index)
1077         {
1078             if (ContentContainer.ChildCount - 1 < index || index < 0)
1079             {
1080                 return;
1081             }
1082
1083             if (SnapToPage)
1084             {
1085                 CurrentPage = index;
1086             }
1087
1088             float targetPosition = Math.Min(ScrollingDirection == Direction.Vertical ? Children[index].Position.Y : Children[index].Position.X, maxScrollDistance);
1089             AnimateChildTo(ScrollDuration, -targetPosition);
1090         }
1091
1092         internal void ScrollToChild(View child, bool anim = false)
1093         {
1094             if (null == FindDescendantByID(child.ID)) return;
1095
1096             bool isHorizontal = (ScrollingDirection == Direction.Horizontal);
1097
1098             float viewScreenPosition = (isHorizontal? ScreenPosition.X : ScreenPosition.Y);
1099             float childScreenPosition = (isHorizontal? child.ScreenPosition.X : child.ScreenPosition.Y);
1100             float scrollPosition = (isHorizontal? ScrollPosition.X : ScrollPosition.Y);
1101             float viewSize = (isHorizontal? SizeWidth : SizeHeight);
1102             float childSize = (isHorizontal? child.SizeWidth : child.SizeHeight);
1103
1104             if (viewScreenPosition > childScreenPosition ||
1105                 viewScreenPosition + viewSize < childScreenPosition + childSize)
1106             {// if object is outside
1107                 float targetPosition;
1108                 float dist = viewScreenPosition - childScreenPosition;
1109                 if (dist > 0)
1110                 {// if object is upper side
1111                     targetPosition = scrollPosition - dist;
1112                 }
1113                 else
1114                 {// if object is down side
1115                     targetPosition = scrollPosition - dist + childSize - viewSize;
1116                 }
1117                 ScrollTo(targetPosition, anim);
1118             }
1119         }
1120
1121         private void OnScrollDragStarted()
1122         {
1123             ScrollEventArgs eventArgs = new ScrollEventArgs(ContentContainer.CurrentPosition);
1124             ScrollDragStarted?.Invoke(this, eventArgs);
1125
1126             if (!hideScrollbar && fadeScrollbar)
1127             {
1128                 scrollBar?.FadeIn();
1129             }
1130         }
1131
1132         private void OnScrollDragEnded()
1133         {
1134             ScrollEventArgs eventArgs = new ScrollEventArgs(ContentContainer.CurrentPosition);
1135             ScrollDragEnded?.Invoke(this, eventArgs);
1136
1137             if (!hideScrollbar && fadeScrollbar)
1138             {
1139                 scrollBar?.FadeOut();
1140             }
1141         }
1142
1143         private void OnScrollAnimationStarted()
1144         {
1145             ScrollEventArgs eventArgs = new ScrollEventArgs(ContentContainer.CurrentPosition);
1146             ScrollAnimationStarted?.Invoke(this, eventArgs);
1147
1148             if (!hideScrollbar && fadeScrollbar)
1149             {
1150                 scrollBar?.FadeIn();
1151             }
1152         }
1153
1154         private void OnScrollAnimationEnded()
1155         {
1156             scrolling = false;
1157             this.InterceptTouchEvent -= OnInterruptTouchingChildTouched;
1158
1159             ScrollEventArgs eventArgs = new ScrollEventArgs(ContentContainer.CurrentPosition);
1160             ScrollAnimationEnded?.Invoke(this, eventArgs);
1161
1162             if (!hideScrollbar && fadeScrollbar)
1163             {
1164                 scrollBar?.FadeOut();
1165             }
1166         }
1167
1168         private void OnScroll()
1169         {
1170             ScrollEventArgs eventArgs = new ScrollEventArgs(ContentContainer.CurrentPosition);
1171             Scrolling?.Invoke(this, eventArgs);
1172
1173             bool isHorizontal = ScrollingDirection == Direction.Horizontal;
1174             float contentLength = isHorizontal ? ContentContainer.Size.Width : ContentContainer.Size.Height;
1175             float currentPosition = isHorizontal ? ContentContainer.CurrentPosition.X : ContentContainer.CurrentPosition.Y;
1176
1177             scrollBar?.Update(contentLength, Math.Abs(currentPosition));
1178             CheckPreReachedTargetPosition();
1179         }
1180
1181         private void CheckPreReachedTargetPosition()
1182         {
1183             // Check whether we reached pre-reached target position
1184             if (readyToNotice &&
1185                 ContentContainer.CurrentPosition.Y <= finalTargetPosition + NoticeAnimationEndBeforePosition &&
1186                 ContentContainer.CurrentPosition.Y >= finalTargetPosition - NoticeAnimationEndBeforePosition)
1187             {
1188                 //Notice first
1189                 readyToNotice = false;
1190                 OnPreReachedTargetPosition(finalTargetPosition);
1191             }
1192         }
1193
1194         /// <summary>
1195         /// This helps developer who wants to know before scroll is reaching target position.
1196         /// </summary>
1197         /// <param name="targetPosition">Index of item.</param>
1198         /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
1199         [EditorBrowsable(EditorBrowsableState.Never)]
1200         protected virtual void OnPreReachedTargetPosition(float targetPosition)
1201         {
1202
1203         }
1204
1205         private void StopScroll()
1206         {
1207             if (scrollAnimation != null)
1208             {
1209                 if (scrollAnimation.State == Animation.States.Playing)
1210                 {
1211                     Debug.WriteLineIf(LayoutDebugScrollableBase, "StopScroll Animation Playing");
1212                     scrollAnimation.Stop(Animation.EndActions.Cancel);
1213                     OnScrollAnimationEnded();
1214                 }
1215                 scrollAnimation.Clear();
1216             }
1217         }
1218
1219         private void AnimateChildTo(int duration, float axisPosition)
1220         {
1221             Debug.WriteLineIf(LayoutDebugScrollableBase, "AnimationTo Animation Duration:" + duration + " Destination:" + axisPosition);
1222             finalTargetPosition = axisPosition;
1223
1224             StopScroll(); // Will replace previous animation so will stop existing one.
1225
1226             if (scrollAnimation == null)
1227             {
1228                 scrollAnimation = new Animation();
1229                 scrollAnimation.Finished += ScrollAnimationFinished;
1230             }
1231
1232             scrollAnimation.Duration = duration;
1233             scrollAnimation.DefaultAlphaFunction = new AlphaFunction(AlphaFunction.BuiltinFunctions.EaseOutSquare);
1234             scrollAnimation.AnimateTo(ContentContainer, (ScrollingDirection == Direction.Horizontal) ? "PositionX" : "PositionY", axisPosition, ScrollAlphaFunction);
1235             scrolling = true;
1236             OnScrollAnimationStarted();
1237             scrollAnimation.Play();
1238         }
1239
1240         /// <summary>
1241         /// Scroll to specific position with or without animation.
1242         /// </summary>
1243         /// <param name="position">Destination.</param>
1244         /// <param name="animate">Scroll with or without animation</param>
1245         /// <since_tizen> 8 </since_tizen>
1246         public void ScrollTo(float position, bool animate)
1247         {
1248             StopScroll();
1249             float currentPositionX = ContentContainer.CurrentPosition.X != 0 ? ContentContainer.CurrentPosition.X : ContentContainer.Position.X;
1250             float currentPositionY = ContentContainer.CurrentPosition.Y != 0 ? ContentContainer.CurrentPosition.Y : ContentContainer.Position.Y;
1251             float delta = ScrollingDirection == Direction.Horizontal ? currentPositionX : currentPositionY;
1252             // The argument position is the new pan position. So the new position of ScrollableBase becomes (-position).
1253             // To move ScrollableBase's position to (-position), it moves by (-position - currentPosition).
1254             delta = -position - delta;
1255
1256             ScrollBy(delta, animate);
1257         }
1258
1259         private float BoundScrollPosition(float targetPosition)
1260         {
1261             if (ScrollAvailableArea != null)
1262             {
1263                 float minScrollPosition = ScrollAvailableArea.X;
1264                 float maxScrollPosition = ScrollAvailableArea.Y;
1265
1266                 targetPosition = Math.Min(-minScrollPosition, targetPosition);
1267                 targetPosition = Math.Max(-maxScrollPosition, targetPosition);
1268             }
1269             else
1270             {
1271                 targetPosition = Math.Min(0, targetPosition);
1272                 targetPosition = Math.Max(-maxScrollDistance, targetPosition);
1273             }
1274
1275             return targetPosition;
1276         }
1277
1278         private void ScrollBy(float displacement, bool animate)
1279         {
1280             if (GetChildCount() == 0 || maxScrollDistance < 0)
1281             {
1282                 return;
1283             }
1284
1285             float childCurrentPosition = (ScrollingDirection == Direction.Horizontal) ? ContentContainer.PositionX : ContentContainer.PositionY;
1286
1287             Debug.WriteLineIf(LayoutDebugScrollableBase, "ScrollBy childCurrentPosition:" + childCurrentPosition +
1288                 " displacement:" + displacement,
1289                 " maxScrollDistance:" + maxScrollDistance);
1290
1291             childTargetPosition = childCurrentPosition + displacement; // child current position + gesture displacement
1292
1293             Debug.WriteLineIf(LayoutDebugScrollableBase, "ScrollBy currentAxisPosition:" + childCurrentPosition + "childTargetPosition:" + childTargetPosition);
1294
1295             if (animate)
1296             {
1297                 // Calculate scroll animation duration
1298                 float scrollDistance = Math.Abs(displacement);
1299                 readyToNotice = true;
1300
1301                 AnimateChildTo(ScrollDuration, BoundScrollPosition(AdjustTargetPositionOfScrollAnimation(BoundScrollPosition(childTargetPosition))));
1302             }
1303             else
1304             {
1305                 StopScroll();
1306                 finalTargetPosition = BoundScrollPosition(childTargetPosition);
1307
1308                 // Set position of scrolling child without an animation
1309                 if (ScrollingDirection == Direction.Horizontal)
1310                 {
1311                     ContentContainer.PositionX = finalTargetPosition;
1312                 }
1313                 else
1314                 {
1315                     ContentContainer.PositionY = finalTargetPosition;
1316                 }
1317             }
1318         }
1319
1320         /// <summary>
1321         /// you can override it to clean-up your own resources.
1322         /// </summary>
1323         /// <param name="type">DisposeTypes</param>
1324         /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API.
1325         [EditorBrowsable(EditorBrowsableState.Never)]
1326         protected override void Dispose(DisposeTypes type)
1327         {
1328             if (disposed)
1329             {
1330                 return;
1331             }
1332
1333             StopOverShootingShadowAnimation();
1334             StopScroll();
1335
1336             if (mPanGestureDetector != null)
1337             {
1338                 mPanGestureDetector.Detected -= OnPanGestureDetected;
1339                 mPanGestureDetector.Dispose();
1340                 mPanGestureDetector = null;
1341             }
1342
1343             if (propertyNotification != null)
1344             {
1345                 propertyNotification.Notified -= OnPropertyChanged;
1346                 Interop.Handle.RemovePropertyNotifications(propertyNotification.SwigCPtr);
1347                 propertyNotification.Dispose();
1348                 propertyNotification = null;
1349             }
1350
1351             if (type == DisposeTypes.Explicit)
1352             {
1353
1354             }
1355             base.Dispose(type);
1356         }
1357
1358         private float CalculateMaximumScrollDistance()
1359         {
1360             float scrollingChildLength = 0;
1361             float scrollerLength = 0;
1362             if (ScrollingDirection == Direction.Horizontal)
1363             {
1364                 Debug.WriteLineIf(LayoutDebugScrollableBase, "Horizontal");
1365
1366                 scrollingChildLength = ContentContainer.Size.Width;
1367                 scrollerLength = Size.Width;
1368             }
1369             else
1370             {
1371                 Debug.WriteLineIf(LayoutDebugScrollableBase, "Vertical");
1372                 scrollingChildLength = ContentContainer.Size.Height;
1373                 scrollerLength = Size.Height;
1374             }
1375
1376             Debug.WriteLineIf(LayoutDebugScrollableBase, "ScrollBy maxScrollDistance:" + (scrollingChildLength - scrollerLength) +
1377                 " parent length:" + scrollerLength +
1378                 " scrolling child length:" + scrollingChildLength);
1379
1380             return Math.Max(scrollingChildLength - scrollerLength, 0);
1381         }
1382
1383         private void PageSnap(float velocity)
1384         {
1385             float destination;
1386
1387             Debug.WriteLineIf(LayoutDebugScrollableBase, "PageSnap with pan candidate totalDisplacement:" + totalDisplacementForPan +
1388                 " currentPage[" + CurrentPage + "]");
1389
1390             //Increment current page if total displacement enough to warrant a page change.
1391             if (Math.Abs(totalDisplacementForPan) > (mPageWidth * ratioOfScreenWidthToCompleteScroll))
1392             {
1393                 if (totalDisplacementForPan < 0)
1394                 {
1395                     CurrentPage = Math.Min(Math.Max(Children.Count - 1, 0), ++CurrentPage);
1396                 }
1397                 else
1398                 {
1399                     CurrentPage = Math.Max(0, --CurrentPage);
1400                 }
1401             }
1402             else if (Math.Abs(velocity) > PageFlickThreshold)
1403             {
1404                 if (velocity < 0)
1405                 {
1406                     CurrentPage = Math.Min(Math.Max(Children.Count - 1, 0), ++CurrentPage);
1407                 }
1408                 else
1409                 {
1410                     CurrentPage = Math.Max(0, --CurrentPage);
1411                 }
1412             }
1413
1414             // Animate to new page or reposition to current page
1415             if (ScrollingDirection == Direction.Horizontal)
1416                 destination = -(Children[CurrentPage].Position.X + Children[CurrentPage].CurrentSize.Width / 2 - CurrentSize.Width / 2); // set to middle of current page
1417             else
1418                 destination = -(Children[CurrentPage].Position.Y + Children[CurrentPage].CurrentSize.Height / 2 - CurrentSize.Height / 2);
1419
1420             AnimateChildTo(ScrollDuration, destination);
1421         }
1422
1423         /// <summary>
1424         /// Enable/Disable overshooting effect. default is disabled.
1425         /// </summary>
1426         [EditorBrowsable(EditorBrowsableState.Never)]
1427         public bool EnableOverShootingEffect
1428         {
1429             get
1430             {
1431                 return (bool)GetValue(EnableOverShootingEffectProperty);
1432             }
1433             set
1434             {
1435                 SetValue(EnableOverShootingEffectProperty, value);
1436                 NotifyPropertyChanged();
1437             }
1438         }
1439         private bool InternalEnableOverShootingEffect { get; set; } = false;
1440
1441         private void AttachOverShootingShadowView()
1442         {
1443             if (!EnableOverShootingEffect)
1444                 return;
1445
1446             // stop animation if necessary.
1447             StopOverShootingShadowAnimation();
1448
1449             if (ScrollingDirection == Direction.Horizontal)
1450             {
1451                 base.Add(leftOverShootingShadowView);
1452                 base.Add(rightOverShootingShadowView);
1453
1454                 leftOverShootingShadowView.Size = new Size(0.0f, SizeHeight);
1455                 leftOverShootingShadowView.Opacity = 1.0f;
1456                 leftOverShootingShadowView.RaiseToTop();
1457
1458                 rightOverShootingShadowView.Size = new Size(0.0f, SizeHeight);
1459                 rightOverShootingShadowView.Opacity = 1.0f;
1460                 rightOverShootingShadowView.RaiseToTop();
1461             }
1462             else
1463             {
1464                 base.Add(topOverShootingShadowView);
1465                 base.Add(bottomOverShootingShadowView);
1466
1467                 topOverShootingShadowView.Size = new Size(SizeWidth, 0.0f);
1468                 topOverShootingShadowView.Opacity = 1.0f;
1469                 topOverShootingShadowView.RaiseToTop();
1470
1471                 bottomOverShootingShadowView.Size = new Size(SizeWidth, 0.0f);
1472                 bottomOverShootingShadowView.Opacity = 1.0f;
1473                 bottomOverShootingShadowView.RaiseToTop();
1474             }
1475
1476             // at the beginning, height or width of overshooting shadow is 0, so it is invisible.
1477             isOverShootingShadowShown = false;
1478         }
1479
1480         private void DragOverShootingShadow(float totalPanDisplacement, float panDisplacement)
1481         {
1482             if (!EnableOverShootingEffect)
1483                 return;
1484
1485             if (totalPanDisplacement > 0) // downwards
1486             {
1487                 // check if reaching at the top / left.
1488                 if ((int)finalTargetPosition != 0)
1489                 {
1490                     isOverShootingShadowShown = false;
1491                     return;
1492                 }
1493
1494                 // save start displacement, and re-calculate displacement.
1495                 if (!isOverShootingShadowShown)
1496                 {
1497                     startShowShadowDisplacement = totalPanDisplacement;
1498                 }
1499                 isOverShootingShadowShown = true;
1500
1501                 float newDisplacement = (int)totalPanDisplacement < (int)startShowShadowDisplacement ? 0 : totalPanDisplacement - startShowShadowDisplacement;
1502
1503                 if (ScrollingDirection == Direction.Horizontal)
1504                 {
1505                     // scale limit of height is 60%.
1506                     float heightScale = newDisplacement / overShootingShadowScaleHeightLimit;
1507                     leftOverShootingShadowView.SizeHeight = heightScale > 0.6f ? SizeHeight * 0.4f : SizeHeight * (1.0f - heightScale);
1508
1509                     // scale limit of width is 300%.
1510                     leftOverShootingShadowView.SizeWidth = newDisplacement > overShootingShadowScaleHeightLimit ? overShootingShadowScaleHeightLimit : newDisplacement;
1511
1512                     // trigger event
1513                     ScrollOutOfBoundEventArgs.Direction scrollDirection = panDisplacement > 0 ?
1514                        ScrollOutOfBoundEventArgs.Direction.Right : ScrollOutOfBoundEventArgs.Direction.Left;
1515                     OnScrollOutOfBound(scrollDirection, totalPanDisplacement);
1516                 }
1517                 else
1518                 {
1519                     // scale limit of width is 60%.
1520                     float widthScale = newDisplacement / overShootingShadowScaleHeightLimit;
1521                     topOverShootingShadowView.SizeWidth = widthScale > 0.6f ? SizeWidth * 0.4f : SizeWidth * (1.0f - widthScale);
1522
1523                     // scale limit of height is 300%.
1524                     topOverShootingShadowView.SizeHeight = newDisplacement > overShootingShadowScaleHeightLimit ? overShootingShadowScaleHeightLimit : newDisplacement;
1525
1526                     // trigger event
1527                     ScrollOutOfBoundEventArgs.Direction scrollDirection = panDisplacement > 0 ?
1528                        ScrollOutOfBoundEventArgs.Direction.Down : ScrollOutOfBoundEventArgs.Direction.Up;
1529                     OnScrollOutOfBound(scrollDirection, totalPanDisplacement);
1530                 }
1531             }
1532             else if (totalPanDisplacement < 0) // upwards
1533             {
1534                 // check if reaching at the bottom.
1535                 if (-(int)finalTargetPosition != (int)maxScrollDistance)
1536                 {
1537                     isOverShootingShadowShown = false;
1538                     return;
1539                 }
1540
1541                 // save start displacement, and re-calculate displacement.
1542                 if (!isOverShootingShadowShown)
1543                 {
1544                     startShowShadowDisplacement = totalPanDisplacement;
1545                 }
1546                 isOverShootingShadowShown = true;
1547
1548                 float newDisplacement = (int)startShowShadowDisplacement < (int)totalPanDisplacement ? 0 : startShowShadowDisplacement - totalPanDisplacement;
1549
1550                 if (ScrollingDirection == Direction.Horizontal)
1551                 {
1552                     // scale limit of height is 60%.
1553                     float heightScale = newDisplacement / overShootingShadowScaleHeightLimit;
1554                     rightOverShootingShadowView.SizeHeight = heightScale > 0.6f ? SizeHeight * 0.4f : SizeHeight * (1.0f - heightScale);
1555
1556                     // scale limit of width is 300%.
1557                     rightOverShootingShadowView.SizeWidth = newDisplacement > overShootingShadowScaleHeightLimit ? overShootingShadowScaleHeightLimit : newDisplacement;
1558
1559                     // trigger event
1560                     ScrollOutOfBoundEventArgs.Direction scrollDirection = panDisplacement > 0 ?
1561                        ScrollOutOfBoundEventArgs.Direction.Right : ScrollOutOfBoundEventArgs.Direction.Left;
1562                     OnScrollOutOfBound(scrollDirection, totalPanDisplacement);
1563                 }
1564                 else
1565                 {
1566                     // scale limit of width is 60%.
1567                     float widthScale = newDisplacement / overShootingShadowScaleHeightLimit;
1568                     bottomOverShootingShadowView.SizeWidth = widthScale > 0.6f ? SizeWidth * 0.4f : SizeWidth * (1.0f - widthScale);
1569
1570                     // scale limit of height is 300%.
1571                     bottomOverShootingShadowView.SizeHeight = newDisplacement > overShootingShadowScaleHeightLimit ? overShootingShadowScaleHeightLimit : newDisplacement;
1572
1573                     // trigger event
1574                     ScrollOutOfBoundEventArgs.Direction scrollDirection = panDisplacement > 0 ?
1575                        ScrollOutOfBoundEventArgs.Direction.Down : ScrollOutOfBoundEventArgs.Direction.Up;
1576                     OnScrollOutOfBound(scrollDirection, totalPanDisplacement);
1577                 }
1578             }
1579             else
1580             {
1581                 // if total displacement is 0, shadow would become invisible.
1582                 isOverShootingShadowShown = false;
1583             }
1584         }
1585
1586         private void PlayOverShootingShadowAnimation()
1587         {
1588             if (!EnableOverShootingEffect)
1589                 return;
1590
1591             // stop animation if necessary.
1592             StopOverShootingShadowAnimation();
1593
1594             if (overShootingShadowAnimation == null)
1595             {
1596                 overShootingShadowAnimation = new Animation(overShootingShadowAnimationDuration);
1597                 overShootingShadowAnimation.Finished += OnOverShootingShadowAnimationFinished;
1598             }
1599
1600             if (ScrollingDirection == Direction.Horizontal)
1601             {
1602                 View targetView = totalDisplacementForPan < 0 ? rightOverShootingShadowView : leftOverShootingShadowView;
1603                 overShootingShadowAnimation.AnimateTo(targetView, "SizeHeight", SizeHeight);
1604                 overShootingShadowAnimation.AnimateTo(targetView, "SizeWidth", 0.0f);
1605                 overShootingShadowAnimation.AnimateTo(targetView, "Opacity", 0.0f);
1606             }
1607             else
1608             {
1609                 View targetView = totalDisplacementForPan < 0 ? bottomOverShootingShadowView : topOverShootingShadowView;
1610                 overShootingShadowAnimation.AnimateTo(targetView, "SizeWidth", SizeWidth);
1611                 overShootingShadowAnimation.AnimateTo(targetView, "SizeHeight", 0.0f);
1612                 overShootingShadowAnimation.AnimateTo(targetView, "Opacity", 0.0f);
1613             }
1614             overShootingShadowAnimation.Play();
1615         }
1616
1617         private void StopOverShootingShadowAnimation()
1618         {
1619             if (overShootingShadowAnimation == null || overShootingShadowAnimation.State != Animation.States.Playing)
1620                 return;
1621
1622             overShootingShadowAnimation.Stop(Animation.EndActions.Cancel);
1623             OnOverShootingShadowAnimationFinished(null, null);
1624             overShootingShadowAnimation.Clear();
1625         }
1626
1627         private void OnOverShootingShadowAnimationFinished(object sender, EventArgs e)
1628         {
1629             if (ScrollingDirection == Direction.Horizontal)
1630             {
1631                 base.Remove(leftOverShootingShadowView);
1632                 base.Remove(rightOverShootingShadowView);
1633
1634                 leftOverShootingShadowView.Size = new Size(0.0f, SizeHeight);
1635                 rightOverShootingShadowView.Size = new Size(0.0f, SizeHeight);
1636             }
1637             else
1638             {
1639                 base.Remove(topOverShootingShadowView);
1640                 base.Remove(bottomOverShootingShadowView);
1641
1642                 topOverShootingShadowView.Size = new Size(SizeWidth, 0.0f);
1643                 bottomOverShootingShadowView.Size = new Size(SizeWidth, 0.0f);
1644             }
1645
1646             // after animation finished, height/width & opacity of vertical shadow both are 0, so it is invisible.
1647             isOverShootingShadowShown = false;
1648         }
1649
1650         private void OnScrollOutOfBound(ScrollOutOfBoundEventArgs.Direction direction, float displacement)
1651         {
1652             ScrollOutOfBoundEventArgs args = new ScrollOutOfBoundEventArgs(direction, displacement);
1653             ScrollOutOfBound?.Invoke(this, args);
1654         }
1655
1656         private void OnPanGestureDetected(object source, PanGestureDetector.DetectedEventArgs e)
1657         {
1658             e.Handled = OnPanGesture(e.PanGesture);
1659         }
1660
1661         private bool OnPanGesture(PanGesture panGesture)
1662         {
1663             bool handled = true;
1664             if (SnapToPage && scrollAnimation != null && scrollAnimation.State == Animation.States.Playing)
1665             {
1666                 return handled;
1667             }
1668             if (panGesture.State == Gesture.StateType.Started)
1669             {
1670                 readyToNotice = false;
1671                 AttachOverShootingShadowView();
1672                 Debug.WriteLineIf(LayoutDebugScrollableBase, "Gesture Start");
1673                 if (scrolling && !SnapToPage)
1674                 {
1675                     StopScroll();
1676                 }
1677                 totalDisplacementForPan = 0.0f;
1678
1679                 // check if gesture need to propagation
1680                 var checkDisplacement = (ScrollingDirection == Direction.Horizontal) ? panGesture.Displacement.X : panGesture.Displacement.Y;
1681                 var checkChildCurrentPosition = (ScrollingDirection == Direction.Horizontal) ? ContentContainer.PositionX : ContentContainer.PositionY;
1682                 var checkChildTargetPosition = checkChildCurrentPosition + checkDisplacement;
1683                 var checkFinalTargetPosition = BoundScrollPosition(checkChildTargetPosition);
1684                 handled = !((int)checkFinalTargetPosition == 0 || -(int)checkFinalTargetPosition == (int)maxScrollDistance);
1685                 // If you propagate a gesture event, return;
1686                 if(!handled)
1687                 {
1688                     return handled;
1689                 }
1690
1691                 //Interrupt touching when panning is started
1692                 this.InterceptTouchEvent += OnInterruptTouchingChildTouched;
1693                 OnScrollDragStarted();
1694             }
1695             else if (panGesture.State == Gesture.StateType.Continuing)
1696             {
1697                 if (ScrollingDirection == Direction.Horizontal)
1698                 {
1699                     // if vertical shadow is shown, does not scroll.
1700                     if (!isOverShootingShadowShown)
1701                     {
1702                         ScrollBy(panGesture.Displacement.X, false);
1703                     }
1704                     totalDisplacementForPan += panGesture.Displacement.X;
1705                     DragOverShootingShadow(totalDisplacementForPan, panGesture.Displacement.X);
1706                 }
1707                 else
1708                 {
1709                     // if vertical shadow is shown, does not scroll.
1710                     if (!isOverShootingShadowShown)
1711                     {
1712                         ScrollBy(panGesture.Displacement.Y, false);
1713                     }
1714                     totalDisplacementForPan += panGesture.Displacement.Y;
1715                     DragOverShootingShadow(totalDisplacementForPan, panGesture.Displacement.Y);
1716                 }
1717                 Debug.WriteLineIf(LayoutDebugScrollableBase, "OnPanGestureDetected Continue totalDisplacementForPan:" + totalDisplacementForPan);
1718
1719             }
1720             else if (panGesture.State == Gesture.StateType.Finished || panGesture.State == Gesture.StateType.Cancelled)
1721             {
1722                 PlayOverShootingShadowAnimation();
1723                 OnScrollDragEnded();
1724                 StopScroll(); // Will replace previous animation so will stop existing one.
1725
1726                 if (scrollAnimation == null)
1727                 {
1728                     scrollAnimation = new Animation();
1729                     scrollAnimation.Finished += ScrollAnimationFinished;
1730                 }
1731
1732                 float panVelocity = (ScrollingDirection == Direction.Horizontal) ? panGesture.Velocity.X : panGesture.Velocity.Y;
1733
1734                 if (SnapToPage)
1735                 {
1736                     PageSnap(panVelocity);
1737                 }
1738                 else
1739                 {
1740                     if (panVelocity == 0)
1741                     {
1742                         float currentScrollPosition = (ScrollingDirection == Direction.Horizontal ? ContentContainer.CurrentPosition.X : ContentContainer.CurrentPosition.Y);
1743                         scrollAnimation.DefaultAlphaFunction = new AlphaFunction(AlphaFunction.BuiltinFunctions.Linear);
1744                         scrollAnimation.Duration = 0;
1745                         scrollAnimation.AnimateTo(ContentContainer, (ScrollingDirection == Direction.Horizontal) ? "PositionX" : "PositionY", currentScrollPosition);
1746                         scrollAnimation.Play();
1747                     }
1748                     else
1749                     {
1750                         Decelerating(panVelocity, scrollAnimation);
1751                     }
1752                 }
1753
1754                 totalDisplacementForPan = 0;
1755                 scrolling = true;
1756                 readyToNotice = true;
1757                 OnScrollAnimationStarted();
1758             }
1759             return handled;
1760         }
1761
1762         internal void BaseRemove(View view)
1763         {
1764             base.Remove(view);
1765         }
1766
1767         internal override bool OnAccessibilityPan(PanGesture gestures)
1768         {
1769             if (SnapToPage && scrollAnimation != null && scrollAnimation.State == Animation.States.Playing)
1770             {
1771                 return false;
1772             }
1773
1774             OnPanGesture(gestures);
1775             return true;
1776         }
1777
1778         private float CustomScrollAlphaFunction(float progress)
1779         {
1780             if (panAnimationDelta == 0)
1781             {
1782                 return 1.0f;
1783             }
1784             else
1785             {
1786                 // Parameter "progress" is normalized value. We need to multiply target duration to calculate distance.
1787                 // Can get real distance using equation of deceleration (check Decelerating function)
1788                 // After get real distance, normalize it
1789                 float realDuration = progress * panAnimationDuration;
1790                 float realDistance = velocityOfLastPan * ((float)Math.Pow(decelerationRate, realDuration) - 1) / logValueOfDeceleration;
1791                 float result = Math.Min(realDistance / Math.Abs(panAnimationDelta), 1.0f);
1792
1793                 // This is hot-fix for if the velocity has very small value, result is not updated even progress done.
1794                 if (progress > 0.99) result = 1.0f;
1795
1796                 return result;
1797             }
1798         }
1799
1800         /// <summary>
1801         /// you can override it to custom your decelerating
1802         /// </summary>
1803         /// <param name="velocity">Velocity of current pan.</param>
1804         /// <param name="animation">Scroll animation.</param>
1805         [EditorBrowsable(EditorBrowsableState.Never)]
1806         protected virtual void Decelerating(float velocity, Animation animation)
1807         {
1808             if (animation == null) throw new ArgumentNullException(nameof(animation));
1809             // Decelerating using deceleration equation ===========
1810             //
1811             // V   : velocity (pixel per millisecond)
1812             // V0  : initial velocity
1813             // d   : deceleration rate,
1814             // t   : time
1815             // X   : final position after decelerating
1816             // log : natural logarithm
1817             //
1818             // V(t) = V0 * d pow t;
1819             // X(t) = V0 * (d pow t - 1) / log d;  <-- Integrate the velocity function
1820             // X(∞) = V0 * d / (1 - d); <-- Result using infinite T can be final position because T is tending to infinity.
1821             //
1822             // Because of final T is tending to infinity, we should use threshold value to finish.
1823             // Final T = log(-threshold * log d / |V0| ) / log d;
1824
1825             velocityOfLastPan = Math.Abs(velocity);
1826
1827             float currentScrollPosition = -(ScrollingDirection == Direction.Horizontal ? ContentContainer.CurrentPosition.X : ContentContainer.CurrentPosition.Y);
1828             panAnimationDelta = (velocityOfLastPan * decelerationRate) / (1 - decelerationRate);
1829             panAnimationDelta = velocity > 0 ? -panAnimationDelta : panAnimationDelta;
1830
1831             float destination = -(panAnimationDelta + currentScrollPosition);
1832             float adjustDestination = AdjustTargetPositionOfScrollAnimation(destination);
1833             float maxPosition = ScrollAvailableArea != null ? ScrollAvailableArea.Y : maxScrollDistance;
1834             float minPosition = ScrollAvailableArea != null ? ScrollAvailableArea.X : 0;
1835
1836             if (destination < -maxPosition || destination > minPosition)
1837             {
1838                 panAnimationDelta = velocity > 0 ? (currentScrollPosition - minPosition) : (maxPosition - currentScrollPosition);
1839                 destination = velocity > 0 ? minPosition : -maxPosition;
1840
1841                 if (panAnimationDelta == 0)
1842                 {
1843                     panAnimationDuration = 0.0f;
1844                 }
1845                 else
1846                 {
1847                     panAnimationDuration = (float)Math.Log((panAnimationDelta * logValueOfDeceleration / velocityOfLastPan + 1), decelerationRate);
1848                 }
1849
1850                 Debug.WriteLineIf(LayoutDebugScrollableBase, "\n" +
1851                     "OverRange======================= \n" +
1852                     "[decelerationRate] " + decelerationRate + "\n" +
1853                     "[logValueOfDeceleration] " + logValueOfDeceleration + "\n" +
1854                     "[Velocity] " + velocityOfLastPan + "\n" +
1855                     "[CurrentPosition] " + currentScrollPosition + "\n" +
1856                     "[CandidateDelta] " + panAnimationDelta + "\n" +
1857                     "[Destination] " + destination + "\n" +
1858                     "[Duration] " + panAnimationDuration + "\n" +
1859                     "================================ \n"
1860                 );
1861             }
1862             else
1863             {
1864                 panAnimationDuration = (float)Math.Log(-DecelerationThreshold * logValueOfDeceleration / velocityOfLastPan) / logValueOfDeceleration;
1865
1866                 if (adjustDestination != destination)
1867                 {
1868                     destination = adjustDestination;
1869                     panAnimationDelta = destination + currentScrollPosition;
1870                     velocityOfLastPan = Math.Abs(panAnimationDelta * logValueOfDeceleration / ((float)Math.Pow(decelerationRate, panAnimationDuration) - 1));
1871                     panAnimationDuration = (float)Math.Log(-DecelerationThreshold * logValueOfDeceleration / velocityOfLastPan) / logValueOfDeceleration;
1872                 }
1873
1874                 Debug.WriteLineIf(LayoutDebugScrollableBase, "\n" +
1875                     "================================ \n" +
1876                     "[decelerationRate] " + decelerationRate + "\n" +
1877                     "[logValueOfDeceleration] " + logValueOfDeceleration + "\n" +
1878                     "[Velocity] " + velocityOfLastPan + "\n" +
1879                     "[CurrentPosition] " + currentScrollPosition + "\n" +
1880                     "[CandidateDelta] " + panAnimationDelta + "\n" +
1881                     "[Destination] " + destination + "\n" +
1882                     "[Duration] " + panAnimationDuration + "\n" +
1883                     "================================ \n"
1884                 );
1885             }
1886
1887             finalTargetPosition = destination;
1888
1889             customScrollAlphaFunction = new UserAlphaFunctionDelegate(CustomScrollAlphaFunction);
1890             animation.DefaultAlphaFunction = new AlphaFunction(customScrollAlphaFunction);
1891             GC.KeepAlive(customScrollAlphaFunction);
1892             animation.Duration = (int)panAnimationDuration;
1893             animation.AnimateTo(ContentContainer, (ScrollingDirection == Direction.Horizontal) ? "PositionX" : "PositionY", destination);
1894             animation.Play();
1895         }
1896
1897         private void ScrollAnimationFinished(object sender, EventArgs e)
1898         {
1899             OnScrollAnimationEnded();
1900         }
1901
1902         /// <summary>
1903         /// Adjust scrolling position by own scrolling rules.
1904         /// Override this function when developer wants to change destination of flicking.(e.g. always snap to center of item)
1905         /// </summary>
1906         /// This may be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API
1907         [EditorBrowsable(EditorBrowsableState.Never)]
1908         protected virtual float AdjustTargetPositionOfScrollAnimation(float position)
1909         {
1910             return position;
1911         }
1912
1913         /// <summary>
1914         /// Scroll position given to ScrollTo.
1915         /// This is the position in the opposite direction to the position of ContentContainer.
1916         /// </summary>
1917         /// <since_tizen> 8 </since_tizen>
1918         public Position ScrollPosition
1919         {
1920             get
1921             {
1922                 return new Position(-ContentContainer.Position);
1923             }
1924         }
1925
1926         /// <summary>
1927         /// Current scroll position in the middle of ScrollTo animation.
1928         /// This is the position in the opposite direction to the current position of ContentContainer.
1929         /// </summary>
1930         /// <since_tizen> 8 </since_tizen>
1931         public Position ScrollCurrentPosition
1932         {
1933             get
1934             {
1935                 return new Position(-ContentContainer.CurrentPosition);
1936             }
1937         }
1938
1939         /// <summary>
1940         /// Remove all children in ContentContainer.
1941         /// </summary>
1942         /// <param name="dispose">If true, removed child is disposed.</param>
1943         [EditorBrowsable(EditorBrowsableState.Never)]
1944         public void RemoveAllChildren(bool dispose = false)
1945         {
1946             RecursiveRemoveChildren(ContentContainer, dispose);
1947         }
1948
1949         private void RecursiveRemoveChildren(View parent, bool dispose)
1950         {
1951             if (parent == null)
1952             {
1953                 return;
1954             }
1955             int maxChild = (int)parent.GetChildCount();
1956             for (int i = maxChild - 1; i >= 0; --i)
1957             {
1958                 View child = parent.GetChildAt((uint)i);
1959                 if (child == null)
1960                 {
1961                     continue;
1962                 }
1963                 RecursiveRemoveChildren(child, dispose);
1964                 parent.Remove(child);
1965                 if (dispose)
1966                 {
1967                     child.Dispose();
1968                 }
1969             }
1970         }
1971
1972         internal bool IsChildNearlyVisble(View child, float offset = 0)
1973         {
1974             if (ScreenPosition.X - offset < child.ScreenPosition.X + child.SizeWidth &&
1975                 ScreenPosition.X + SizeWidth + offset > child.ScreenPosition.X &&
1976                 ScreenPosition.Y - offset < child.ScreenPosition.Y + child.SizeHeight &&
1977                 ScreenPosition.Y + SizeHeight + offset > child.ScreenPosition.Y)
1978             {
1979                 return true;
1980             }
1981             else
1982             {
1983                 return false;
1984             }
1985         }
1986
1987         /// <inheritdoc/>
1988         [EditorBrowsable(EditorBrowsableState.Never)]
1989         public override View GetNextFocusableView(View currentFocusedView, View.FocusDirection direction, bool loopEnabled)
1990         {
1991             bool isHorizontal = (ScrollingDirection == Direction.Horizontal);
1992             float targetPosition = -(ScrollingDirection == Direction.Horizontal ? ContentContainer.CurrentPosition.X : ContentContainer.CurrentPosition.Y);
1993             float stepDistance = (stepScrollDistance != 0? stepScrollDistance : (isHorizontal ? Size.Width * 0.25f :  Size.Height * 0.25f));
1994
1995             bool forward = ((isHorizontal && direction == View.FocusDirection.Right) ||
1996                             (!isHorizontal && direction == View.FocusDirection.Down) ||
1997                             (direction == View.FocusDirection.Clockwise));
1998             bool backward = ((isHorizontal && direction == View.FocusDirection.Left) ||
1999                              (!isHorizontal && direction == View.FocusDirection.Up) ||
2000                              (direction == View.FocusDirection.CounterClockwise));
2001
2002             View nextFocusedView = FocusManager.Instance.GetNearestFocusableActor(this, currentFocusedView, direction);
2003
2004             // Move out focus from ScrollableBase.
2005             // FIXME: Forward, Backward is unimplemented other components.
2006             if (direction == View.FocusDirection.Forward ||
2007                 direction == View.FocusDirection.Backward ||
2008                 (nextFocusedView == null &&
2009                 ((forward && maxScrollDistance - targetPosition < 0.1f) ||
2010                  (backward && targetPosition < 0.1f))))
2011             {
2012                 var next = FocusManager.Instance.GetNearestFocusableActor(this.Parent, this, direction);
2013                 Debug.WriteLineIf(focusDebugScrollableBase, $"Focus move [{direction}] out from ScrollableBase! Next focus target {next}:{next?.ID}");
2014                 return next;
2015             }
2016
2017             if (focusDebugScrollableBase)
2018             {
2019                 global::System.Text.StringBuilder debugMessage = new global::System.Text.StringBuilder("=========================================================\n");
2020                 debugMessage.Append($"GetNextFocusableView On: {this}:{this.ID}\n");
2021                 debugMessage.Append($"----------------Current: {currentFocusedView}:{currentFocusedView?.ID}\n");
2022                 debugMessage.Append($"-------------------Next: {nextFocusedView}:{nextFocusedView?.ID}\n");
2023                 debugMessage.Append($"--------------Direction: {direction}\n");
2024                 debugMessage.Append("=========================================================");
2025                 Debug.WriteLineIf(focusDebugScrollableBase, debugMessage);
2026             }
2027
2028             if (nextFocusedView != null)
2029             {
2030                 if (null != FindDescendantByID(nextFocusedView.ID))
2031                 {
2032                     if (IsChildNearlyVisble(nextFocusedView, stepDistance) == true)
2033                     {
2034                         ScrollToChild(nextFocusedView, true);
2035                         return nextFocusedView;
2036                     }
2037                 }
2038             }
2039
2040             if (forward || backward)
2041             {
2042                 // Fallback to current focus or scrollableBase till next focus visible in scrollable.
2043                 if (null != currentFocusedView && null != FindDescendantByID(currentFocusedView.ID))
2044                 {
2045                     nextFocusedView = currentFocusedView;
2046                 }
2047                 else
2048                 {
2049                     Debug.WriteLineIf(focusDebugScrollableBase, "current focus view is not decendant. return ScrollableBase!");
2050                     return this;
2051                 }
2052
2053                 if (forward)
2054                 {
2055                     targetPosition += stepDistance;
2056                     targetPosition = targetPosition > maxScrollDistance ? maxScrollDistance : targetPosition;
2057
2058                 }
2059                 else if (backward)
2060                 {
2061                     targetPosition -= stepDistance;
2062                     targetPosition = targetPosition < 0 ? 0 : targetPosition;
2063                 }
2064
2065                 ScrollTo(targetPosition, true);
2066
2067                 Debug.WriteLineIf(focusDebugScrollableBase, $"ScrollTo :({targetPosition})");
2068             }
2069
2070             Debug.WriteLineIf(focusDebugScrollableBase, $"return end : {nextFocusedView}:{nextFocusedView?.ID}");
2071             return nextFocusedView;
2072         }
2073
2074         /// <inheritdoc/>
2075         [EditorBrowsable(EditorBrowsableState.Never)]
2076         protected override bool AccessibilityScrollToChild(View child)
2077         {
2078             if (child == null)
2079             {
2080                 return false;
2081             }
2082
2083             if (ScrollingDirection == Direction.Horizontal)
2084             {
2085                 if (child.ScreenPosition.X + child.Size.Width <= this.ScreenPosition.X)
2086                 {
2087                     if (SnapToPage)
2088                     {
2089                         PageSnap(PageFlickThreshold + 1);
2090                     }
2091                     else
2092                     {
2093                         ScrollTo((float)(child.ScreenPosition.X - ContentContainer.ScreenPosition.X), false);
2094                     }
2095                 }
2096                 else if (child.ScreenPosition.X >= this.ScreenPosition.X + this.Size.Width)
2097                 {
2098                     if (SnapToPage)
2099                     {
2100                         PageSnap(-(PageFlickThreshold + 1));
2101                     }
2102                     else
2103                     {
2104                         ScrollTo((float)(child.ScreenPosition.X + child.Size.Width - ContentContainer.ScreenPosition.X - this.Size.Width), false);
2105                     }
2106                 }
2107             }
2108             else
2109             {
2110                 if (child.ScreenPosition.Y + child.Size.Height <= this.ScreenPosition.Y)
2111                 {
2112                     if (SnapToPage)
2113                     {
2114                         PageSnap(PageFlickThreshold + 1);
2115                     }
2116                     else
2117                     {
2118                         ScrollTo((float)(child.ScreenPosition.Y - ContentContainer.ScreenPosition.Y), false);
2119                     }
2120                 }
2121                 else if (child.ScreenPosition.Y >= this.ScreenPosition.Y + this.Size.Height)
2122                 {
2123                     if (SnapToPage)
2124                     {
2125                         PageSnap(-(PageFlickThreshold + 1));
2126                     }
2127                     else
2128                     {
2129                         ScrollTo((float)(child.ScreenPosition.Y + child.Size.Height - ContentContainer.ScreenPosition.Y - this.Size.Height), false);
2130                     }
2131                 }
2132             }
2133
2134             return true;
2135         }
2136     }
2137
2138 } // namespace