Add some logs to find out cause of once happened scrollview issue #2
[platform/core/uifw/dali-toolkit.git] / base / dali-toolkit / internal / controls / scrollable / scroll-view / scroll-view-impl.cpp
1 /*
2  * Copyright (c) 2014 Samsung Electronics Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17
18 // INTERNAL INCLUDES
19 #include <dali/public-api/events/mouse-wheel-event.h>
20
21 #include <dali-toolkit/public-api/controls/scrollable/scroll-view/scroll-view-constraints.h>
22 #include <dali-toolkit/public-api/controls/scrollable/scroll-component-impl.h>
23 #include <dali-toolkit/internal/controls/scrollable/scroll-view/scroll-view-impl.h>
24 #include <dali-toolkit/internal/controls/scrollable/scroll-view/scroll-view-effect-impl.h>
25 #include <dali-toolkit/internal/controls/scrollable/scroll-view/scroll-overshoot-indicator-impl.h>
26 #include <dali/integration-api/debug.h>
27
28 #define ENABLED_SCROLL_STATE_LOGGING
29
30 #ifdef ENABLED_SCROLL_STATE_LOGGING
31 #define DALI_LOG_SCROLL_STATE(format, args...) Dali::Integration::Log::LogMessage(Dali::Integration::Log::DebugInfo, "%s:%d " format, __PRETTY_FUNCTION__, __LINE__, ## args)
32 #else
33 #define DALI_LOG_SCROLL_STATE(format, args...)
34 #endif
35
36 // TODO: Change to two class system:
37 // 1. DraggableActor (is an actor which can be dragged anywhere/scaled/rotated, can be set to range using the ruler)
38 // 2. ScrollView (contains a draggable actor that can a) be dragged in the negative X, and Y domain, b) has a hitArea for touches)
39 // TODO: Rotation
40 // TODO: Asymetrical scaling
41 // TODO: external components (page and status overlays).
42 // TODO: Orientation.
43 // TODO: upgrade Vector2/3 to support returning Unit vectors, normals, & cross product (dot product is already provided)
44
45 using namespace Dali;
46
47 namespace
48 {
49
50 const int DEFAULT_REFRESH_INTERVAL_MILLISECONDS = 50;                                     ///< Refresh rate TODO: Animation should have an update signal (and see item-view-impl)
51 const float FLICK_SPEED_THRESHOLD = 500.0f;                                               ///< Flick threshold in pixels/ms
52 const float FREE_FLICK_SPEED_THRESHOLD = 200.0f;                                          ///< Free-Flick threshold in pixels/ms
53 const float AUTOLOCK_AXIS_MINIMUM_DISTANCE2 = 100.0f;                                     ///< Auto-lock axis after minimum distance squared.
54 const float FLICK_ORTHO_ANGLE_RANGE = 60.0f;                                              ///< degrees. (if >45, then supports diagonal flicking)
55 const unsigned int MAXIMUM_NUMBER_OF_VALUES = 5;                                          ///< Number of values to use for weighted pan calculation.
56 const Vector2 DEFAULT_MOUSE_WHEEL_SCROLL_DISTANCE_STEP_PROPORTION = Vector2(0.17f, 0.1f); ///< The step of horizontal scroll distance in the proportion of stage size for each mouse wheel event received.
57 const unsigned long MINIMUM_TIME_BETWEEN_DOWN_AND_UP_FOR_RESET( 150u );
58 const float DEFAULT_OVERSHOOT_ANIMATION_DURATION = 0.35f;  // time in seconds
59 const Vector2 OVERSCROLL_CLAMP(1.0f, 1.0f);                // maximum overscroll allowed in pixels when overshoot indicator is being used
60 const float TOUCH_DOWN_TIMER_INTERVAL = 100.0f;
61 const float DEFAULT_SCROLL_UPDATE_DISTANCE( 30.0f );                               ///< Default distance to travel in pixels for scroll update signal
62
63 // predefined effect values
64 const Vector3 ANGLE_CAROUSEL_ROTATE(Math::PI * 0.5f, Math::PI * 0.5f, 0.0f);
65 const Vector3 ANGLE_CUBE_PAGE_ROTATE(Math::PI * 0.2f, Math::PI * 0.2f, 0.0f);  ///< Cube page rotates as if it has ten sides with the camera positioned inside
66 const Vector2 ANGLE_CUSTOM_CUBE_SWING(-Math::PI * 0.45f, -Math::PI * 0.45f);  ///< outer cube pages swing 90 degrees as they pan offscreen
67 const Vector2 ANGLE_SPIRAL_SWING_IN(Math::PI * 0.5f, Math::PI * 0.5f);
68 const Vector2 ANGLE_SPIRAL_SWING_OUT(Math::PI * 0.35f, Math::PI * 0.35f);
69 const Vector2 ANGLE_OUTER_CUBE_SWING(Math::PI * 0.5f, Math::PI * 0.5f);  ///< outer cube pages swing 90 degrees as they pan offscreen
70
71 // Helpers ////////////////////////////////////////////////////////////////////////////////////////
72
73 // TODO: GetAngle for Vector2 can be moved.
74 // GetAngle for Vector3 needs to be measured against a normal/plane.
75
76 /**
77  * @param[in] vector The 3D vector to be measured
78  * @return angle in radians from 0 to 2PI
79  */
80 float GetAngle(const Vector3& vector)
81 {
82   return atan2(vector.y, vector.x) + Math::PI;
83 }
84
85 /**
86  * @param[in] vector The 2D vector to be measured
87  * @return angle in radians from 0 to 2PI
88  */
89 float GetAngle(const Vector2& vector)
90 {
91   return atan2(vector.y, vector.x) + Math::PI;
92 }
93
94 /**
95  * Find the vector (distance) from (a) to (b)
96  * in domain (start) to (end)
97  * (\ / start)               (\ / end)
98  *   |-a                 b<----|
99  *
100  * @note assumes both (a) and (b) are already with the domain
101  * (start) to (end)
102  *
103  * @param[in] a the current point
104  * @param[in] b the target point
105  * @param[in] start the start of the domain
106  * @param[in] end the end of the domain
107  * @param[in] bias whether to only take the right direction or the left direction,
108  * or the shortest direction.
109  * @return the shortest direction and distance
110  */
111 float VectorInDomain(float a, float b, float start, float end, Dali::Toolkit::DirectionBias bias)
112 {
113   if(bias == Dali::Toolkit::DirectionBiasNone)
114   {
115     return ShortestDistanceInDomain( a, b, start, end );
116   }
117   //  (a-start + end-b)
118   float size = end-start;
119   float vect = b-a;
120
121   if(vect > 0)
122   {
123     // +ve vector
124     if(bias == Dali::Toolkit::DirectionBiasRight) // going right, take the vector.
125     {
126       return vect;
127     }
128     else
129     {
130       float aRight = a+size;
131       return b-aRight;
132     }
133   }
134   else
135   {
136     // -ve vector
137     if(bias == Dali::Toolkit::DirectionBiasLeft) // going left, take the vector.
138     {
139       return vect;
140     }
141     else
142     {
143       float aLeft = a-size;
144       return b-aLeft;
145     }
146   }
147 }
148
149 /**
150  * Returns the position of the anchor within actor
151  *
152  * @param actor The Actor
153  * @param anchor The Anchor point of interest.
154  * @return The position of the Anchor
155  */
156 Vector3 GetPositionOfAnchor(Actor &actor, const Vector3 &anchor)
157 {
158   Vector3 childPosition = actor.GetCurrentPosition();
159   Vector3 childAnchor = - actor.GetCurrentAnchorPoint() + anchor;
160   Vector3 childSize = actor.GetCurrentSize();
161
162   return childPosition + childAnchor * childSize;
163 }
164
165 // AlphaFunctions /////////////////////////////////////////////////////////////////////////////////
166
167 float FinalDefaultAlphaFunction(float offset)
168 {
169   return offset * 0.5f;
170 }
171
172 /**
173  * ConstantDecelerationAlphaFunction
174  * Newtoninan distance for constant deceleration
175  * v = 1 - t, s = t - 1/2 t^2
176  * when t = 0, s = 0.0 (min distance)
177  * when t = 1, s = 0.5 (max distance)
178  * progress = s / (max-min) = 2t - t^2
179  *
180  * @param[in] offset The input progress
181  * @return The output progress
182  */
183 float ConstantDecelerationAlphaFunction(float progress)
184 {
185   return progress * 2.0f - progress * progress;
186 }
187
188 // Internal Constraints ///////////////////////////////////////////////////////////////////////////
189
190 /**
191  * Internal Relative position Constraint
192  * Generates the relative position value of the scroll view
193  * based on the absolute position, and it's relation to the
194  * scroll domain. This is a value from 0.0f to 1.0f in each
195  * scroll position axis.
196  */
197 Vector3 InternalRelativePositionConstraint(const Vector3&    current,
198                                            const PropertyInput& scrollPositionProperty,
199                                            const PropertyInput& scrollMinProperty,
200                                            const PropertyInput& scrollMaxProperty,
201                                            const PropertyInput& scrollSizeProperty)
202 {
203   Vector3 position = -scrollPositionProperty.GetVector3();
204   const Vector3& min = scrollMinProperty.GetVector3();
205   const Vector3& max = scrollMaxProperty.GetVector3();
206   const Vector3& size = scrollSizeProperty.GetVector3();
207
208   position.x = WrapInDomain(position.x, min.x, max.x);
209   position.y = WrapInDomain(position.y, min.y, max.y);
210
211   Vector3 relativePosition;
212   Vector3 domainSize = (max - min) - size;
213
214   relativePosition.x = domainSize.x > Math::MACHINE_EPSILON_1 ? fabsf((position.x - min.x) / domainSize.x) : 0.0f;
215   relativePosition.y = domainSize.y > Math::MACHINE_EPSILON_1 ? fabsf((position.y - min.y) / domainSize.y) : 0.0f;
216
217   return relativePosition;
218 }
219
220 } // unnamed namespace
221
222 namespace Dali
223 {
224
225 namespace Toolkit
226 {
227
228 namespace Internal
229 {
230
231 namespace
232 {
233
234 /**
235  * Returns whether to lock scrolling to a particular axis
236  *
237  * @param[in] panDelta Distance panned since gesture started
238  * @param[in] currentLockAxis The current lock axis value
239  * @param[in] lockGradient How quickly to lock to a particular axis
240  *
241  * @return The new axis lock state
242  */
243 ScrollView::LockAxis GetLockAxis(const Vector2& panDelta, ScrollView::LockAxis currentLockAxis, float lockGradient)
244 {
245   if(panDelta.LengthSquared() > AUTOLOCK_AXIS_MINIMUM_DISTANCE2 &&
246       currentLockAxis == ScrollView::LockPossible)
247   {
248     float dx = fabsf(panDelta.x);
249     float dy = fabsf(panDelta.y);
250     if(dx * lockGradient >= dy)
251     {
252       // 0.36:1 gradient to the horizontal (deviate < 20 degrees)
253       currentLockAxis = ScrollView::LockVertical;
254     }
255     else if(dy * lockGradient > dx)
256     {
257       // 0.36:1 gradient to the vertical (deviate < 20 degrees)
258       currentLockAxis = ScrollView::LockHorizontal;
259     }
260     else
261     {
262       currentLockAxis = ScrollView::LockNone;
263     }
264   }
265   return currentLockAxis;
266 }
267
268 /**
269  * Internal Pre-Position Property Constraint.
270  *
271  * Generates position property based on current position + gesture displacement.
272  * Or generates position property based on positionX/Y.
273  * Note: This is the position prior to any clamping at scroll boundaries.
274  * TODO: Scale & Rotation Transforms.
275  */
276 struct InternalPrePositionConstraint
277 {
278   InternalPrePositionConstraint(const Vector2& initialPanMask,
279                                 bool axisAutoLock,
280                                 float axisAutoLockGradient,
281                                 ScrollView::LockAxis initialLockAxis,
282                                 const Vector2& maxOvershoot,
283                                 const RulerDomain& domainX, const RulerDomain& domainY)
284   : mInitialPanMask(initialPanMask),
285     mDomainMin( -domainX.min, -domainY.min ),
286     mDomainMax( -domainX.max, -domainY.max ),
287     mMaxOvershoot(maxOvershoot),
288     mAxisAutoLockGradient(axisAutoLockGradient),
289     mLockAxis(initialLockAxis),
290     mAxisAutoLock(axisAutoLock),
291     mWasPanning(false),
292     mClampX( domainX.enabled ),
293     mClampY( domainY.enabled )
294   {
295   }
296
297   Vector3 operator()(const Vector3&    current,
298                      const PropertyInput& gesturePositionProperty,
299                      const PropertyInput& gestureDisplacementProperty,
300                      const PropertyInput& sizeProperty)
301   {
302     Vector3 scrollPostPosition = current;
303     Vector2 panPosition = gesturePositionProperty.GetVector2();
304
305     if(!mWasPanning)
306     {
307       mLocalStart = gesturePositionProperty.GetVector2() - gestureDisplacementProperty.GetVector2();
308       mPrePosition = current;
309       mCurrentPanMask = mInitialPanMask;
310       mWasPanning = true;
311     }
312
313     // Calculate Deltas...
314     Vector2 currentPosition = gesturePositionProperty.GetVector2();
315     Vector2 panDelta( currentPosition - mLocalStart );
316
317     // Axis Auto Lock - locks the panning to the horizontal or vertical axis if the pan
318     // appears mostly horizontal or mostly vertical respectively...
319     if( mAxisAutoLock )
320     {
321       mLockAxis = GetLockAxis(panDelta, mLockAxis, mAxisAutoLockGradient);
322       if( mLockAxis == ScrollView::LockVertical )
323       {
324         mCurrentPanMask.y = 0.0f;
325       }
326       else if( mLockAxis == ScrollView::LockHorizontal )
327       {
328         mCurrentPanMask.x = 0.0f;
329       }
330     }
331
332     // Restrict deltas based on ruler enable/disable and axis-lock state...
333     panDelta *= mCurrentPanMask;
334
335     // Perform Position transform based on input deltas...
336     scrollPostPosition = mPrePosition;
337     scrollPostPosition.GetVectorXY() += panDelta;
338
339     // if no wrapping then clamp preposition to maximum overshoot amount
340     const Vector3& size = sizeProperty.GetVector3();
341     if( mClampX )
342     {
343       float newXPosition = Clamp(scrollPostPosition.x, (mDomainMax.x + size.x) - mMaxOvershoot.x, mDomainMin.x + mMaxOvershoot.x );
344       if( (newXPosition < scrollPostPosition.x - Math::MACHINE_EPSILON_1)
345               || (newXPosition > scrollPostPosition.x + Math::MACHINE_EPSILON_1) )
346       {
347         mPrePosition.x = newXPosition;
348         mLocalStart.x = panPosition.x;
349       }
350       scrollPostPosition.x = newXPosition;
351     }
352     if( mClampY )
353     {
354       float newYPosition = Clamp(scrollPostPosition.y, (mDomainMax.y + size.y) - mMaxOvershoot.y, mDomainMin.y + mMaxOvershoot.y );
355       if( (newYPosition < scrollPostPosition.y - Math::MACHINE_EPSILON_1)
356               || (newYPosition > scrollPostPosition.y + Math::MACHINE_EPSILON_1) )
357       {
358         mPrePosition.y = newYPosition;
359         mLocalStart.y = panPosition.y;
360       }
361       scrollPostPosition.y = newYPosition;
362     }
363
364     return scrollPostPosition;
365   }
366
367   Vector3 mPrePosition;
368   Vector2 mLocalStart;
369   Vector2 mInitialPanMask;              ///< Initial pan mask (based on ruler settings)
370   Vector2 mCurrentPanMask;              ///< Current pan mask that can be altered by axis lock mode.
371   Vector2 mDomainMin;
372   Vector2 mDomainMax;
373   Vector2 mMaxOvershoot;
374
375   float mAxisAutoLockGradient;          ///< Set by ScrollView
376   ScrollView::LockAxis mLockAxis;
377
378   bool mAxisAutoLock:1;                   ///< Set by ScrollView
379   bool mWasPanning:1;
380   bool mClampX:1;
381   bool mClampY:1;
382 };
383
384 /**
385  * Internal Position Property Constraint.
386  *
387  * Generates position property based on pre-position
388  * Note: This is the position after clamping.
389  * (uses result of InternalPrePositionConstraint)
390  */
391 struct InternalPositionConstraint
392 {
393   InternalPositionConstraint(const RulerDomain& domainX, const RulerDomain& domainY, bool wrap)
394   : mDomainMin( -domainX.min, -domainY.min ),
395     mDomainMax( -domainX.max, -domainY.max ),
396     mClampX( domainX.enabled ),
397     mClampY( domainY.enabled ),
398     mWrap( wrap )
399   {
400   }
401
402   Vector3 operator()(const Vector3&    current,
403                      const PropertyInput& scrollPositionProperty,
404                      const PropertyInput& scrollMinProperty,
405                      const PropertyInput& scrollMaxProperty,
406                      const PropertyInput& scrollSizeProperty)
407   {
408     Vector3 position = scrollPositionProperty.GetVector3();
409     const Vector2& size = scrollSizeProperty.GetVector3().GetVectorXY();
410     const Vector3& min = scrollMinProperty.GetVector3();
411     const Vector3& max = scrollMaxProperty.GetVector3();
412
413     if( mWrap )
414     {
415       position.x = -WrapInDomain(-position.x, min.x, max.x);
416       position.y = -WrapInDomain(-position.y, min.y, max.y);
417     }
418     else
419     {
420       // clamp post position to domain
421       position.x = mClampX ? Clamp(position.x, mDomainMax.x + size.x, mDomainMin.x ) : position.x;
422       position.y = mClampY ? Clamp(position.y, mDomainMax.y + size.y, mDomainMin.y ) : position.y;
423     }
424
425     return position;
426   }
427
428   Vector2 mDomainMin;
429   Vector2 mDomainMax;
430   bool mClampX;
431   bool mClampY;
432   bool mWrap;
433
434 };
435
436 /**
437  * This constraint updates the X overshoot property using the difference
438  * mPropertyPrePosition.x and mPropertyPosition.x, returning a relative value between 0.0f and 1.0f
439  */
440 struct OvershootXConstraint
441 {
442   OvershootXConstraint(float maxOvershoot) : mMaxOvershoot(maxOvershoot) {}
443
444   float operator()(const float&    current,
445       const PropertyInput& scrollPrePositionProperty,
446       const PropertyInput& scrollPostPositionProperty,
447       const PropertyInput& canScrollProperty)
448   {
449     if( canScrollProperty.GetBoolean() )
450     {
451       const Vector3& scrollPrePosition = scrollPrePositionProperty.GetVector3();
452       const Vector3& scrollPostPosition = scrollPostPositionProperty.GetVector3();
453       float newOvershoot = scrollPrePosition.x - scrollPostPosition.x;
454       return (newOvershoot > 0.0f ? std::min(newOvershoot, mMaxOvershoot) : std::max(newOvershoot, -mMaxOvershoot)) / mMaxOvershoot;
455     }
456     return 0.0f;
457   }
458
459   float mMaxOvershoot;
460 };
461
462 /**
463  * This constraint updates the Y overshoot property using the difference
464  * mPropertyPrePosition.y and mPropertyPosition.y, returning a relative value between 0.0f and 1.0f
465  */
466 struct OvershootYConstraint
467 {
468   OvershootYConstraint(float maxOvershoot) : mMaxOvershoot(maxOvershoot) {}
469
470   float operator()(const float&    current,
471       const PropertyInput& scrollPrePositionProperty,
472       const PropertyInput& scrollPostPositionProperty,
473       const PropertyInput& canScrollProperty)
474   {
475     if( canScrollProperty.GetBoolean() )
476     {
477       const Vector3& scrollPrePosition = scrollPrePositionProperty.GetVector3();
478       const Vector3& scrollPostPosition = scrollPostPositionProperty.GetVector3();
479       float newOvershoot = scrollPrePosition.y - scrollPostPosition.y;
480       return (newOvershoot > 0.0f ? std::min(newOvershoot, mMaxOvershoot) : std::max(newOvershoot, -mMaxOvershoot)) / mMaxOvershoot;
481     }
482     return 0.0f;
483   }
484
485   float mMaxOvershoot;
486 };
487
488 /**
489  * When panning, this constraint updates the X property, otherwise
490  * it has no effect on the X property.
491  */
492 float InternalXConstraint(const float&    current,
493                           const PropertyInput& scrollPosition)
494 {
495   return scrollPosition.GetVector3().x;
496 }
497
498 /**
499  * When panning, this constraint updates the Y property, otherwise
500  * it has no effect on the Y property.
501  */
502 float InternalYConstraint(const float&    current,
503                           const PropertyInput& scrollPosition)
504 {
505   return scrollPosition.GetVector3().y;
506 }
507
508 /**
509  * Internal Position-Delta Property Constraint.
510  *
511  * Generates position-delta property based on scroll-position + scroll-offset properties.
512  */
513 Vector3 InternalPositionDeltaConstraint(const Vector3&    current,
514                                         const PropertyInput& scrollPositionProperty,
515                                         const PropertyInput& scrollOffsetProperty)
516 {
517   const Vector3& scrollPosition = scrollPositionProperty.GetVector3();
518   const Vector3& scrollOffset = scrollOffsetProperty.GetVector3();
519
520   return scrollPosition + scrollOffset;
521 }
522
523 /**
524  * Internal Final Position Constraint
525  * The position of content is:
526  * of scroll-position + f(scroll-overshoot)
527  * where f(...) function defines how overshoot
528  * should affect final-position.
529  */
530 struct InternalFinalConstraint
531 {
532   InternalFinalConstraint(AlphaFunction functionX,
533                           AlphaFunction functionY)
534   : mFunctionX(functionX),
535     mFunctionY(functionY)
536   {
537   }
538
539   Vector3 operator()(const Vector3&    current,
540                      const PropertyInput& scrollPositionProperty,
541                      const PropertyInput& scrollOvershootXProperty,
542                      const PropertyInput& scrollOvershootYProperty)
543   {
544     const float& overshootx = scrollOvershootXProperty.GetFloat();
545     const float& overshooty = scrollOvershootYProperty.GetFloat();
546     Vector3 offset( mFunctionX(overshootx),
547                     mFunctionY(overshooty),
548                     0.0f);
549
550     return scrollPositionProperty.GetVector3() - offset;
551   }
552
553   AlphaFunction mFunctionX;
554   AlphaFunction mFunctionY;
555 };
556
557
558 BaseHandle Create()
559 {
560   return Toolkit::ScrollView::New();
561 }
562
563 TypeRegistration typeRegistration( typeid(Toolkit::ScrollView), typeid(Toolkit::Scrollable), Create );
564
565 SignalConnectorType signalConnector1( typeRegistration, Toolkit::ScrollView::SIGNAL_SNAP_STARTED, &ScrollView::DoConnectSignal );
566
567 }
568
569
570 ///////////////////////////////////////////////////////////////////////////////////////////////////
571 // ScrollView
572 ///////////////////////////////////////////////////////////////////////////////////////////////////
573
574 Dali::Toolkit::ScrollView ScrollView::New()
575 {
576   // Create the implementation
577   ScrollViewPtr scrollView(new ScrollView());
578
579   // Pass ownership to CustomActor via derived handle
580   Dali::Toolkit::ScrollView handle(*scrollView);
581
582   // Second-phase init of the implementation
583   // This can only be done after the CustomActor connection has been made...
584   scrollView->Initialize();
585
586   return handle;
587 }
588
589 ScrollView::ScrollView()
590 : ScrollBase(),
591   mTouchDownTime(0u),
592   mGestureStackDepth(0),
593   mRotationDelta(0.0f),
594   mScrollStateFlags(0),
595   mScrollPreRotation(0.0f),
596   mScrollPostRotation(0.0f),
597   mMinTouchesForPanning(1),
598   mMaxTouchesForPanning(1),
599   mLockAxis(LockPossible),
600   mScrollUpdateDistance(DEFAULT_SCROLL_UPDATE_DISTANCE),
601   mOvershootDelay(1.0f),
602   mMaxOvershoot(Toolkit::ScrollView::DEFAULT_MAX_OVERSHOOT, Toolkit::ScrollView::DEFAULT_MAX_OVERSHOOT),
603   mUserMaxOvershoot(Toolkit::ScrollView::DEFAULT_MAX_OVERSHOOT, Toolkit::ScrollView::DEFAULT_MAX_OVERSHOOT),
604   mSnapOvershootDuration(Toolkit::ScrollView::DEFAULT_SNAP_OVERSHOOT_DURATION),
605   mSnapOvershootAlphaFunction(AlphaFunctions::EaseOut),
606   mSnapDuration(Toolkit::ScrollView::DEFAULT_SLOW_SNAP_ANIMATION_DURATION),
607   mSnapAlphaFunction(AlphaFunctions::EaseOut),
608   mFlickDuration(Toolkit::ScrollView::DEFAULT_FAST_SNAP_ANIMATION_DURATION),
609   mFlickAlphaFunction(AlphaFunctions::EaseOut),
610   mAxisAutoLockGradient(Toolkit::ScrollView::DEFAULT_AXIS_AUTO_LOCK_GRADIENT),
611   mFrictionCoefficient(Toolkit::ScrollView::DEFAULT_FRICTION_COEFFICIENT),
612   mFlickSpeedCoefficient(Toolkit::ScrollView::DEFAULT_FLICK_SPEED_COEFFICIENT),
613   mMaxFlickSpeed(Toolkit::ScrollView::DEFAULT_MAX_FLICK_SPEED),
614   mInAccessibilityPan(false),
615   mInitialized(false),
616   mScrolling(false),
617   mScrollInterrupted(false),
618   mPanning(false),
619   mSensitive(true),
620   mTouchDownTimeoutReached(false),
621   mActorAutoSnapEnabled(false),
622   mAutoResizeContainerEnabled(false),
623   mWrapMode(false),
624   mAxisAutoLock(false),
625   mAlterChild(false),
626   mDefaultMaxOvershoot(true)
627 {
628   SetRequiresMouseWheelEvents(true);
629 }
630
631 void ScrollView::OnInitialize()
632 {
633   Actor self = Self();
634
635   // Internal Actor, used to hide actors from enumerations.
636   // Also actors added to Internal actor appear as overlays e.g. ScrollBar components.
637   mInternalActor = Actor::New();
638   mInternalActor.SetDrawMode(DrawMode::OVERLAY);
639   self.Add(mInternalActor);
640   mInternalActor.ApplyConstraint( Constraint::New<Vector3>( Actor::SIZE, ParentSource( Actor::SIZE ), EqualToConstraint() ) );
641   mInternalActor.SetParentOrigin(ParentOrigin::CENTER);
642   mInternalActor.SetAnchorPoint(AnchorPoint::CENTER);
643
644   mAlterChild = true;
645
646   // Register Scroll Properties.
647   RegisterProperties();
648
649   mScrollPostPosition = mScrollPrePosition = Vector3::ZERO;
650   mScrollPostScale = mScrollPreScale = Vector3::ONE;
651   mScrollPostRotation = mScrollPreRotation = 0.0f;
652
653   mMouseWheelScrollDistanceStep = Stage::GetCurrent().GetSize() * DEFAULT_MOUSE_WHEEL_SCROLL_DISTANCE_STEP_PROPORTION;
654
655   mInitialized = true;
656
657   mGestureStackDepth = 0;
658
659   EnableGestureDetection( Gesture::Type( Gesture::Pan ) );
660
661   // For pan, default to only 1 touch required, ignoring touches outside this range.
662   SetTouchesRequiredForPanning(1, 1, false);
663
664   // By default we'll allow the user to freely drag the scroll view,
665   // while disabling the other rulers.
666   RulerPtr ruler = new DefaultRuler();
667   RulerPtr rulerDisabled = new DefaultRuler();
668   rulerDisabled->Disable();
669   mRulerX = ruler;
670   mRulerY = ruler;
671   mRulerScaleX = rulerDisabled;
672   mRulerScaleY = rulerDisabled;
673   mRulerRotation = rulerDisabled;
674
675   EnableScrollComponent(Toolkit::Scrollable::OvershootIndicator);
676
677   Vector3 size = GetControlSize();
678   UpdatePropertyDomain(size);
679   SetInternalConstraints();
680 }
681
682 void ScrollView::OnControlStageConnection()
683 {
684   DALI_LOG_SCROLL_STATE("[0x%X]", this);
685
686   if ( mSensitive )
687   {
688     SetScrollSensitive( false );
689     SetScrollSensitive( true );
690   }
691   if(IsScrollComponentEnabled(Toolkit::Scrollable::OvershootIndicator))
692   {
693     // try and make sure property notifications are set
694     EnableScrollComponent(Toolkit::Scrollable::OvershootIndicator);
695   }
696 }
697
698 void ScrollView::OnControlStageDisconnection()
699 {
700   DALI_LOG_SCROLL_STATE("[0x%X]", this);
701
702   StopAnimation();
703 }
704
705 ScrollView::~ScrollView()
706 {
707   DALI_LOG_SCROLL_STATE("[0x%X]", this);
708 }
709
710 AlphaFunction ScrollView::GetScrollSnapAlphaFunction() const
711 {
712   return mSnapAlphaFunction;
713 }
714
715 void ScrollView::SetScrollSnapAlphaFunction(AlphaFunction alpha)
716 {
717   mSnapAlphaFunction = alpha;
718 }
719
720 AlphaFunction ScrollView::GetScrollFlickAlphaFunction() const
721 {
722   return mFlickAlphaFunction;
723 }
724
725 void ScrollView::SetScrollFlickAlphaFunction(AlphaFunction alpha)
726 {
727   mFlickAlphaFunction = alpha;
728 }
729
730 float ScrollView::GetScrollSnapDuration() const
731 {
732   return mSnapDuration;
733 }
734
735 void ScrollView::SetScrollSnapDuration(float time)
736 {
737   mSnapDuration = time;
738 }
739
740 float ScrollView::GetScrollFlickDuration() const
741 {
742   return mFlickDuration;
743 }
744
745 void ScrollView::SetScrollFlickDuration(float time)
746 {
747   mFlickDuration = time;
748 }
749
750 void ScrollView::ApplyEffect(Toolkit::ScrollViewEffect effect)
751 {
752   Dali::Toolkit::ScrollView self = Dali::Toolkit::ScrollView::DownCast(Self());
753
754   // Assertion check to ensure effect doesn't already exist in this scrollview
755   bool effectAlreadyExistsInScrollView(false);
756   for (ScrollViewEffectIter iter = mEffects.begin(); iter != mEffects.end(); ++iter)
757   {
758     if(*iter==effect)
759     {
760       effectAlreadyExistsInScrollView = true;
761       break;
762     }
763   }
764
765   DALI_ASSERT_ALWAYS(!effectAlreadyExistsInScrollView);
766
767   // add effect to effects list
768   mEffects.push_back(effect);
769
770   // invoke Attachment request to ScrollView first
771   GetImpl(effect).Attach(self);
772 }
773
774 Toolkit::ScrollViewEffect ScrollView::ApplyEffect(Toolkit::ScrollView::PageEffect effect)
775 {
776   Toolkit::ScrollViewEffect scrollEffect;
777   switch(effect)
778   {
779     case Toolkit::ScrollView::PageEffectNone:
780     {
781       break;
782     }
783     case Toolkit::ScrollView::PageEffectOuterCube:
784     {
785       Toolkit::ScrollViewCustomEffect customEffect;
786       scrollEffect = customEffect = Toolkit::ScrollViewCustomEffect::New();
787       Vector2 pageSize = Stage::GetCurrent().GetSize();
788       // set the page translation to the slide off distance, also add an extra value to space the pages, having a smaller spacing on translationOut will allow the spacing to reduce over time
789       // the page moving onto screen will start 50.0f further out (1.0f * 50.0f) and the spacing will reduce as its position reaches the centre (0.0f * 50.0f)
790       // the page moving off screen will slowly build a spacing from 0.0f to 20.0f
791       // the spacing from each page is added together for the final spacing between the two pages.
792       customEffect.SetPageTranslation(Vector3(pageSize.x, pageSize.y, 0) + Vector3(50.0f, 50.0f, 0.0f), Vector3(pageSize.x, pageSize.y, 0) + Vector3(20.0f, 20.0f, 0.0f));
793       customEffect.SetSwingAngleOut(ANGLE_CUSTOM_CUBE_SWING.x, Vector3(0.0f, -1.0f, 0.0f));
794       customEffect.SetSwingAnchor(AnchorPoint::CENTER, AnchorPoint::CENTER_LEFT);
795       customEffect.SetOpacityThreshold(0.7f);
796       break;
797     }
798     case Toolkit::ScrollView::PageEffectDepth:
799     {
800       Toolkit::ScrollViewCustomEffect customEffect;
801       scrollEffect = customEffect = Toolkit::ScrollViewCustomEffect::New();
802       break;
803     }
804     case Toolkit::ScrollView::PageEffectInnerCube:
805     {
806       Toolkit::ScrollViewCustomEffect customEffect;
807       scrollEffect = customEffect = Toolkit::ScrollViewCustomEffect::New();
808       customEffect.SetPageSpacing(Vector2(30.0f, 30.0f));
809       customEffect.SetAngledOriginPageRotation(ANGLE_CUBE_PAGE_ROTATE);
810       customEffect.SetSwingAngle(ANGLE_CUBE_PAGE_ROTATE.x, Vector3(0,-1,0));
811       customEffect.SetOpacityThreshold(0.5f);
812       break;
813     }
814     case Toolkit::ScrollView::PageEffectCarousel:
815     {
816       Toolkit::ScrollViewCustomEffect customEffect;
817       scrollEffect = customEffect = Toolkit::ScrollViewCustomEffect::New();
818       customEffect.SetPageTranslation(Vector3(0,0,0), Vector3(-30, 0, 0));
819       customEffect.SetPageSpacing(Vector2(60.0f, 60.0f));
820       customEffect.SetAngledOriginPageRotation(-ANGLE_CUBE_PAGE_ROTATE);
821       customEffect.SetOpacityThreshold(0.2f, 0.6f);
822       break;
823     }
824     case Toolkit::ScrollView::PageEffectSpiral:
825     {
826       Toolkit::ScrollViewCustomEffect customEffect;
827       scrollEffect = customEffect = Toolkit::ScrollViewCustomEffect::New();
828
829       Vector2 pageSize = Stage::GetCurrent().GetSize();
830       customEffect.SetSwingAngle(-ANGLE_SPIRAL_SWING_IN.x, Vector3(0.0f, -1.0f, 0.0f), ANGLE_SPIRAL_SWING_OUT.x, Vector3(0.0f, -1.0f, 0.0f));
831       //customEffect.SetSwingAngleAlphaFunctionOut(AlphaFunctions::EaseOut);
832       customEffect.SetSwingAnchor(AnchorPoint::CENTER_RIGHT);
833       customEffect.SetPageTranslation(Vector3(pageSize.x, pageSize.y, 0) + Vector3(100.0f, 100.0f, 0.0f), Vector3(pageSize.x, pageSize.y, -pageSize.y * 2.0f) * 0.33f);
834       //customEffect.SetPageTranslateAlphaFunctionOut(AlphaFunctions::EaseOut);
835       customEffect.SetOpacityThreshold(0.75f, 0.6f);
836       customEffect.SetOpacityAlphaFunctionIn(AlphaFunctions::EaseInOut);
837       break;
838     }
839     default:
840     {
841       DALI_ASSERT_DEBUG(0 && "unknown scroll view effect");
842     }
843   }
844   RemoveConstraintsFromChildren();
845   if(scrollEffect)
846   {
847     ApplyEffect(scrollEffect);
848   }
849   return scrollEffect;
850 }
851
852 void ScrollView::RemoveEffect(Toolkit::ScrollViewEffect effect)
853 {
854   Dali::Toolkit::ScrollView self = Dali::Toolkit::ScrollView::DownCast(Self());
855
856   // remove effect from effects list
857   bool effectExistedInScrollView(false);
858   for (ScrollViewEffectIter iter = mEffects.begin(); iter != mEffects.end(); ++iter)
859   {
860     if(*iter==effect)
861     {
862       mEffects.erase(iter);
863       effectExistedInScrollView = true;
864       break;
865     }
866   }
867
868   // Assertion check to ensure effect existed.
869   DALI_ASSERT_ALWAYS(effectExistedInScrollView);
870
871   // invoke Detachment request to ScrollView last
872   GetImpl(effect).Detach(self);
873 }
874
875 void ScrollView::RemoveAllEffects()
876 {
877   Dali::Toolkit::ScrollView self = Dali::Toolkit::ScrollView::DownCast(Self());
878
879   for (ScrollViewEffectIter effectIter = mEffects.begin(); effectIter != mEffects.end(); ++effectIter)
880   {
881     Toolkit::ScrollViewEffect effect = *effectIter;
882
883     // invoke Detachment request to ScrollView last
884     GetImpl(effect).Detach(self);
885   }
886
887   mEffects.clear();
888 }
889
890 void ScrollView::ApplyConstraintToChildren(Constraint constraint)
891 {
892   ApplyConstraintToBoundActors(constraint);
893 }
894
895 void ScrollView::RemoveConstraintsFromChildren()
896 {
897   RemoveConstraintsFromBoundActors();
898 }
899
900 const RulerPtr ScrollView::GetRulerX() const
901 {
902   return mRulerX;
903 }
904
905 const RulerPtr ScrollView::GetRulerY() const
906 {
907   return mRulerY;
908 }
909
910 void ScrollView::SetRulerX(RulerPtr ruler)
911 {
912   mRulerX = ruler;
913
914   Vector3 size = GetControlSize();
915   UpdatePropertyDomain(size);
916   UpdateMainInternalConstraint();
917 }
918
919 void ScrollView::SetRulerY(RulerPtr ruler)
920 {
921   mRulerY = ruler;
922
923   Vector3 size = GetControlSize();
924   UpdatePropertyDomain(size);
925   UpdateMainInternalConstraint();
926 }
927
928 void ScrollView::UpdatePropertyDomain(const Vector3& size)
929 {
930   Actor self = Self();
931   Vector3 min = mMinScroll;
932   Vector3 max = mMaxScroll;
933   bool scrollPositionChanged = false;
934   bool domainChanged = false;
935
936   bool canScrollVertical = false;
937   bool canScrollHorizontal = false;
938   UpdateLocalScrollProperties();
939   if(mRulerX->IsEnabled())
940   {
941     const Toolkit::RulerDomain& rulerDomain = mRulerX->GetDomain();
942     if( fabsf(min.x - rulerDomain.min) > Math::MACHINE_EPSILON_10000
943         || fabsf(max.x - rulerDomain.max) > Math::MACHINE_EPSILON_10000 )
944     {
945       domainChanged = true;
946       min.x = rulerDomain.min;
947       max.x = rulerDomain.max;
948
949       // make sure new scroll value is within new domain
950       if( mScrollPrePosition.x < min.x
951           || mScrollPrePosition.x > max.x )
952       {
953         scrollPositionChanged = true;
954         mScrollPrePosition.x = Clamp(mScrollPrePosition.x, -(max.x - size.x), -min.x);
955       }
956     }
957     if( (fabsf(rulerDomain.max - rulerDomain.min) - size.x) > Math::MACHINE_EPSILON_10000 )
958     {
959       canScrollHorizontal = true;
960     }
961   }
962
963   if(mRulerY->IsEnabled())
964   {
965     const Toolkit::RulerDomain& rulerDomain = mRulerY->GetDomain();
966     if( fabsf(min.y - rulerDomain.min) > Math::MACHINE_EPSILON_10000
967         || fabsf(max.y - rulerDomain.max) > Math::MACHINE_EPSILON_10000 )
968     {
969       domainChanged = true;
970       min.y = rulerDomain.min;
971       max.y = rulerDomain.max;
972
973       // make sure new scroll value is within new domain
974       if( mScrollPrePosition.y < min.y
975           || mScrollPrePosition.y > max.y )
976       {
977         scrollPositionChanged = true;
978         mScrollPrePosition.y = Clamp(mScrollPrePosition.y, -(max.y - size.y), -min.y);
979       }
980     }
981     if( (fabsf(rulerDomain.max - rulerDomain.min) - size.y) > Math::MACHINE_EPSILON_10000 )
982     {
983       canScrollVertical = true;
984     }
985   }
986   // avoid setting properties if possible, otherwise this will cause an entire update as well as triggering constraints using each property we update
987   if( self.GetProperty<bool>(mPropertyCanScrollVertical) != canScrollVertical )
988   {
989     self.SetProperty(mPropertyCanScrollVertical, canScrollVertical);
990   }
991   if( self.GetProperty<bool>(mPropertyCanScrollHorizontal) != canScrollHorizontal )
992   {
993     self.SetProperty(mPropertyCanScrollHorizontal, canScrollHorizontal);
994   }
995   if( scrollPositionChanged )
996   {
997     self.SetProperty(mPropertyPrePosition, mScrollPrePosition);
998   }
999   if( domainChanged )
1000   {
1001     mMinScroll = min;
1002     mMaxScroll = max;
1003     self.SetProperty(mPropertyPositionMin, min );
1004     self.SetProperty(mPropertyPositionMax, max );
1005   }
1006 }
1007
1008 void ScrollView::SetRulerScaleX(RulerPtr ruler)
1009 {
1010   mRulerScaleX = ruler;
1011   UpdateMainInternalConstraint();
1012 }
1013
1014 void ScrollView::SetRulerScaleY(RulerPtr ruler)
1015 {
1016   mRulerScaleY = ruler;
1017   UpdateMainInternalConstraint();
1018 }
1019
1020 void ScrollView::SetRulerRotation(RulerPtr ruler)
1021 {
1022   mRulerRotation = ruler;
1023   UpdateMainInternalConstraint();
1024 }
1025
1026 void ScrollView::SetScrollSensitive(bool sensitive)
1027 {
1028   Actor self = Self();
1029   PanGestureDetector panGesture( GetPanGestureDetector() );
1030
1031   DALI_LOG_SCROLL_STATE("[0x%X] sensitive[%d]", this, int(sensitive));
1032
1033   if((!mSensitive) && (sensitive))
1034   {
1035     mSensitive = sensitive;
1036     panGesture.Attach(self);
1037   }
1038   else if((mSensitive) && (!sensitive))
1039   {
1040     // while the scroll view is panning, the state needs to be reset.
1041     bool isPanning = self.GetProperty<bool>( mPropertyPanning );
1042     if ( isPanning )
1043     {
1044       PanGesture cancelGesture( Gesture::Cancelled );
1045       OnPan( cancelGesture );
1046     }
1047
1048     panGesture.Detach(self);
1049     mSensitive = sensitive;
1050
1051     mGestureStackDepth = 0;
1052   }
1053 }
1054
1055 void ScrollView::SetMaxOvershoot(float overshootX, float overshootY)
1056 {
1057   mMaxOvershoot.x = overshootX;
1058   mMaxOvershoot.y = overshootY;
1059   mUserMaxOvershoot = mMaxOvershoot;
1060   mDefaultMaxOvershoot = false;
1061   UpdateMainInternalConstraint();
1062 }
1063
1064 void ScrollView::SetSnapOvershootAlphaFunction(AlphaFunction alpha)
1065 {
1066   mSnapOvershootAlphaFunction = alpha;
1067 }
1068
1069 void ScrollView::SetSnapOvershootDuration(float duration)
1070 {
1071   mSnapOvershootDuration = duration;
1072 }
1073
1074 void ScrollView::SetTouchesRequiredForPanning(unsigned int minTouches, unsigned int maxTouches, bool endOutside)
1075 {
1076   PanGestureDetector panGesture( GetPanGestureDetector() );
1077
1078   mMinTouchesForPanning = minTouches;
1079   mMaxTouchesForPanning = maxTouches;
1080
1081   if(endOutside)
1082   {
1083     panGesture.SetMinimumTouchesRequired(minTouches);
1084     panGesture.SetMaximumTouchesRequired(maxTouches);
1085   }
1086   else
1087   {
1088     panGesture.SetMinimumTouchesRequired(1);
1089     panGesture.SetMaximumTouchesRequired(UINT_MAX);
1090   }
1091 }
1092
1093 void ScrollView::SetActorAutoSnap(bool enable)
1094 {
1095   mActorAutoSnapEnabled = enable;
1096 }
1097
1098 void ScrollView::SetAutoResize(bool enable)
1099 {
1100   mAutoResizeContainerEnabled = enable;
1101   // TODO: This needs a lot of issues to be addressed before working.
1102 }
1103
1104 bool ScrollView::GetWrapMode() const
1105 {
1106   return mWrapMode;
1107 }
1108
1109 void ScrollView::SetWrapMode(bool enable)
1110 {
1111   mWrapMode = enable;
1112   Self().SetProperty(mPropertyWrap, enable);
1113 }
1114
1115 int ScrollView::GetRefreshInterval() const
1116 {
1117   return mScrollUpdateDistance;
1118 }
1119
1120 void ScrollView::SetRefreshInterval(int milliseconds)
1121 {
1122   mScrollUpdateDistance = milliseconds;
1123 }
1124
1125 int ScrollView::GetScrollUpdateDistance() const
1126 {
1127   return mScrollUpdateDistance;
1128 }
1129
1130 void ScrollView::SetScrollUpdateDistance(int distance)
1131 {
1132   mScrollUpdateDistance = distance;
1133 }
1134
1135 bool ScrollView::GetAxisAutoLock() const
1136 {
1137   return mAxisAutoLock;
1138 }
1139
1140 void ScrollView::SetAxisAutoLock(bool enable)
1141 {
1142   mAxisAutoLock = enable;
1143   UpdateMainInternalConstraint();
1144 }
1145
1146 float ScrollView::GetAxisAutoLockGradient() const
1147 {
1148   return mAxisAutoLockGradient;
1149 }
1150
1151 void ScrollView::SetAxisAutoLockGradient(float gradient)
1152 {
1153   DALI_ASSERT_DEBUG( gradient >= 0.0f && gradient <= 1.0f );
1154   mAxisAutoLockGradient = gradient;
1155   UpdateMainInternalConstraint();
1156 }
1157
1158 float ScrollView::GetFrictionCoefficient() const
1159 {
1160   return mFrictionCoefficient;
1161 }
1162
1163 void ScrollView::SetFrictionCoefficient(float friction)
1164 {
1165   DALI_ASSERT_DEBUG( friction > 0.0f );
1166   mFrictionCoefficient = friction;
1167 }
1168
1169 float ScrollView::GetFlickSpeedCoefficient() const
1170 {
1171   return mFlickSpeedCoefficient;
1172 }
1173
1174 void ScrollView::SetFlickSpeedCoefficient(float speed)
1175 {
1176   mFlickSpeedCoefficient = speed;
1177 }
1178
1179 float ScrollView::GetMaxFlickSpeed() const
1180 {
1181   return mMaxFlickSpeed;
1182 }
1183
1184 void ScrollView::SetMaxFlickSpeed(float speed)
1185 {
1186   mMaxFlickSpeed = speed;
1187 }
1188
1189 void ScrollView::SetMouseWheelScrollDistanceStep(Vector2 step)
1190 {
1191   mMouseWheelScrollDistanceStep = step;
1192 }
1193
1194 Vector2 ScrollView::GetMouseWheelScrollDistanceStep() const
1195 {
1196   return mMouseWheelScrollDistanceStep;
1197 }
1198
1199 unsigned int ScrollView::GetCurrentPage() const
1200 {
1201   // in case animation is currently taking place.
1202   Vector3 position = GetPropertyPosition();
1203
1204   Actor self = Self();
1205   unsigned int page = 0;
1206   unsigned int pagesPerVolume = 1;
1207   unsigned int volume = 0;
1208
1209   // if rulerX is enabled, then get page count (columns)
1210   page = mRulerX->GetPageFromPosition(-position.x, mWrapMode);
1211   volume = mRulerY->GetPageFromPosition(-position.y, mWrapMode);
1212   pagesPerVolume = mRulerX->GetTotalPages();
1213
1214   return volume * pagesPerVolume + page;
1215 }
1216
1217 Vector3 ScrollView::GetCurrentScrollPosition() const
1218 {
1219   return -GetPropertyPosition();
1220 }
1221
1222 void ScrollView::SetScrollPosition(const Vector3& position)
1223 {
1224   mScrollPrePosition = position;
1225 }
1226
1227 Vector3 ScrollView::GetCurrentScrollScale() const
1228 {
1229   // in case animation is currently taking place.
1230   return GetPropertyScale();
1231 }
1232
1233 Vector3 ScrollView::GetDomainSize() const
1234 {
1235   Vector3 size = Self().GetCurrentSize();
1236
1237   const RulerDomain& xDomain = GetRulerX()->GetDomain();
1238   const RulerDomain& yDomain = GetRulerY()->GetDomain();
1239
1240   Vector3 domainSize = Vector3( xDomain.max - xDomain.min, yDomain.max - yDomain.min, 0.0f ) - size;
1241   return domainSize;
1242 }
1243
1244 void ScrollView::TransformTo(const Vector3& position, const Vector3& scale, float rotation,
1245                              DirectionBias horizontalBias, DirectionBias verticalBias)
1246 {
1247   TransformTo(position, scale, rotation, mSnapDuration, horizontalBias, verticalBias);
1248 }
1249
1250 void ScrollView::TransformTo(const Vector3& position, const Vector3& scale, float rotation, float duration,
1251                              DirectionBias horizontalBias, DirectionBias verticalBias)
1252 {
1253   // Guard against destruction during signal emission
1254   // Note that Emit() methods are called indirectly e.g. from within ScrollView::AnimateTo()
1255   Toolkit::ScrollView handle( GetOwner() );
1256
1257   Vector3 currentScrollPosition = GetCurrentScrollPosition();
1258   Self().SetProperty( mPropertyScrollStartPagePosition, currentScrollPosition );
1259
1260   if(mScrolling) // are we interrupting a current scroll?
1261   {
1262     // set mScrolling to false, in case user has code that interrogates mScrolling Getter() in complete.
1263     mScrolling = false;
1264     DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignalV2 1 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
1265     mScrollCompletedSignalV2.Emit( currentScrollPosition );
1266   }
1267
1268   Self().SetProperty(mPropertyScrolling, true);
1269   mScrolling = true;
1270
1271   DALI_LOG_SCROLL_STATE("[0x%X] mScrollStartedSignalV2 1 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
1272   mScrollStartedSignalV2.Emit( currentScrollPosition );
1273   bool animating = AnimateTo(-position,
1274                              Vector3::ONE * duration,
1275                              scale,
1276                              Vector3::ONE * duration,
1277                              rotation,
1278                              duration,
1279                              mSnapAlphaFunction,
1280                              true,
1281                              horizontalBias,
1282                              verticalBias,
1283                              Snap);
1284
1285   if(!animating)
1286   {
1287     // if not animating, then this pan has completed right now.
1288     Self().SetProperty(mPropertyScrolling, false);
1289     mScrolling = false;
1290     DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignalV2 2 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
1291     SetScrollUpdateNotification(false);
1292     mScrollCompletedSignalV2.Emit( currentScrollPosition );
1293   }
1294 }
1295
1296 void ScrollView::ScrollTo(const Vector3& position)
1297 {
1298   ScrollTo(position, mSnapDuration );
1299 }
1300
1301 void ScrollView::ScrollTo(const Vector3& position, float duration)
1302 {
1303   ScrollTo(position, duration, DirectionBiasNone, DirectionBiasNone);
1304 }
1305
1306 void ScrollView::ScrollTo(const Vector3& position, float duration,
1307                           DirectionBias horizontalBias, DirectionBias verticalBias)
1308 {
1309   TransformTo(position, mScrollPostScale, mScrollPostRotation, duration, horizontalBias, verticalBias);
1310 }
1311
1312 void ScrollView::ScrollTo(unsigned int page)
1313 {
1314   ScrollTo(page, mSnapDuration);
1315 }
1316
1317 void ScrollView::ScrollTo(unsigned int page, float duration, DirectionBias bias)
1318 {
1319   Vector3 position;
1320   unsigned int volume;
1321   unsigned int libraries;
1322
1323   // The position to scroll to is continuous and linear
1324   // unless a domain has been enabled on the X axis.
1325   // or if WrapMode has been enabled.
1326   bool carryX = mRulerX->GetDomain().enabled | mWrapMode;
1327   bool carryY = mRulerY->GetDomain().enabled | mWrapMode;
1328
1329   position.x = mRulerX->GetPositionFromPage(page, volume, carryX);
1330   position.y = mRulerY->GetPositionFromPage(volume, libraries, carryY);
1331
1332   ScrollTo(position, duration, bias, bias);
1333 }
1334
1335 void ScrollView::ScrollTo(Actor &actor)
1336 {
1337   ScrollTo(actor, mSnapDuration);
1338 }
1339
1340 void ScrollView::ScrollTo(Actor &actor, float duration)
1341 {
1342   DALI_ASSERT_ALWAYS(actor.GetParent() == Self());
1343
1344   Actor self = Self();
1345   Vector3 size = self.GetCurrentSize();
1346   Vector3 position = actor.GetCurrentPosition();
1347   position -= GetPropertyPrePosition();
1348
1349   ScrollTo(Vector3(position.x - size.width * 0.5f, position.y - size.height * 0.5f, 0.0f), duration);
1350 }
1351
1352 Actor ScrollView::FindClosestActor()
1353 {
1354   Actor self = Self();
1355   Vector3 size = self.GetCurrentSize();
1356
1357   return FindClosestActorToPosition(Vector3(size.width * 0.5f,size.height * 0.5f,0.0f));
1358 }
1359
1360 Actor ScrollView::FindClosestActorToPosition(const Vector3& position, FindDirection dirX, FindDirection dirY, FindDirection dirZ)
1361 {
1362   Actor closestChild;
1363   float closestDistance2 = 0.0f;
1364   Vector3 actualPosition = position;
1365
1366   unsigned int numChildren = Self().GetChildCount();
1367
1368   for(unsigned int i = 0; i < numChildren; ++i)
1369   {
1370     Actor child = Self().GetChildAt(i);
1371
1372     if(mInternalActor == child) // ignore internal actor.
1373     {
1374       continue;
1375     }
1376
1377     Vector3 childPosition = GetPositionOfAnchor(child, AnchorPoint::CENTER);
1378
1379     Vector3 delta = childPosition - actualPosition;
1380
1381     // X-axis checking (only find Actors to the [dirX] of actualPosition)
1382     if(dirX > All) // != All,None
1383     {
1384       FindDirection deltaH = delta.x > 0 ? Right : Left;
1385       if(dirX != deltaH)
1386       {
1387         continue;
1388       }
1389     }
1390
1391     // Y-axis checking (only find Actors to the [dirY] of actualPosition)
1392     if(dirY > All) // != All,None
1393     {
1394       FindDirection deltaV = delta.y > 0 ? Down : Up;
1395       if(dirY  != deltaV)
1396       {
1397         continue;
1398       }
1399     }
1400
1401     // Z-axis checking (only find Actors to the [dirZ] of actualPosition)
1402     if(dirZ > All) // != All,None
1403     {
1404       FindDirection deltaV = delta.y > 0 ? In : Out;
1405       if(dirZ  != deltaV)
1406       {
1407         continue;
1408       }
1409     }
1410
1411     // compare child to closest child in terms of distance.
1412     float distance2 = 0.0f;
1413
1414     // distance2 = the Square of the relevant dimensions of delta
1415     if(dirX != None)
1416     {
1417       distance2 += delta.x * delta.x;
1418     }
1419
1420     if(dirY != None)
1421     {
1422       distance2 += delta.y * delta.y;
1423     }
1424
1425     if(dirZ != None)
1426     {
1427       distance2 += delta.z * delta.z;
1428     }
1429
1430     if(closestChild) // Next time.
1431     {
1432       if(distance2 < closestDistance2)
1433       {
1434         closestChild = child;
1435         closestDistance2 = distance2;
1436       }
1437     }
1438     else // First time.
1439     {
1440       closestChild = child;
1441       closestDistance2 = distance2;
1442     }
1443   }
1444
1445   return closestChild;
1446 }
1447
1448 bool ScrollView::ScrollToSnapPoint()
1449 {
1450   Vector2 stationaryVelocity = Vector2(0.0f, 0.0f);
1451   return SnapWithVelocity( stationaryVelocity );
1452 }
1453
1454 void ScrollView::ScaleTo(const Vector3& scale)
1455 {
1456   ScaleTo(scale, mSnapDuration);
1457 }
1458
1459 void ScrollView::ScaleTo(const Vector3& scale, float duration)
1460 {
1461   TransformTo(mScrollPostPosition, scale, mScrollPostRotation, duration);
1462 }
1463
1464
1465 // TODO: In situations where axes are different (X snap, Y free)
1466 // Each axis should really have their own independent animation (time and equation)
1467 // Consider, X axis snapping to nearest grid point (EaseOut over fixed time)
1468 // Consider, Y axis simulating physics to arrive at a point (Physics equation over variable time)
1469 // Currently, the axes have been split however, they both use the same EaseOut equation.
1470 bool ScrollView::SnapWithVelocity(Vector2 velocity)
1471 {
1472   // Animator takes over now, touches are assumed not to interfere.
1473   // And if touches do interfere, then we'll stop animation, update PrePosition
1474   // to current mScroll's properties, and then resume.
1475   // Note: For Flicking this may work a bit different...
1476
1477   float angle = atan2(velocity.y, velocity.x);
1478   float speed2 = velocity.LengthSquared();
1479   AlphaFunction alphaFunction = mSnapAlphaFunction;
1480   Vector3 positionDuration = Vector3::ONE * mSnapDuration;
1481   Vector3 scaleDuration = Vector3::ONE * mSnapDuration;
1482   float rotationDuration = mSnapDuration;
1483   float biasX = 0.5f;
1484   float biasY = 0.5f;
1485   FindDirection horizontal = None;
1486   FindDirection vertical = None;
1487
1488   // orthoAngleRange = Angle tolerance within the Exact N,E,S,W direction
1489   // that will be accepted as a general N,E,S,W flick direction.
1490
1491   const float orthoAngleRange = FLICK_ORTHO_ANGLE_RANGE * M_PI / 180.0f;
1492   const float flickSpeedThreshold2 = FLICK_SPEED_THRESHOLD*FLICK_SPEED_THRESHOLD;
1493
1494   Vector3 positionSnap = mScrollPrePosition;
1495
1496   // Flick logic X Axis
1497
1498   if(mRulerX->IsEnabled() && mLockAxis != LockHorizontal)
1499   {
1500     horizontal = All;
1501
1502     if( speed2 > flickSpeedThreshold2 || // exceeds flick threshold
1503         mInAccessibilityPan ) // With AccessibilityPan its easier to move between snap positions
1504     {
1505       if((angle >= -orthoAngleRange) && (angle < orthoAngleRange)) // Swiping East
1506       {
1507         biasX = 0.0f, horizontal = Left;
1508
1509         // This guards against an error where no movement occurs, due to the flick finishing
1510         // before the update-thread has advanced mScrollPostPosition past the the previous snap point.
1511         positionSnap.x += 1.0f;
1512       }
1513       else if((angle >= M_PI-orthoAngleRange) || (angle < -M_PI+orthoAngleRange)) // Swiping West
1514       {
1515         biasX = 1.0f, horizontal = Right;
1516
1517         // This guards against an error where no movement occurs, due to the flick finishing
1518         // before the update-thread has advanced mScrollPostPosition past the the previous snap point.
1519         positionSnap.x -= 1.0f;
1520       }
1521     }
1522   }
1523
1524   // Flick logic Y Axis
1525
1526   if(mRulerY->IsEnabled() && mLockAxis != LockVertical)
1527   {
1528     vertical = All;
1529
1530     if( speed2 > flickSpeedThreshold2 || // exceeds flick threshold
1531         mInAccessibilityPan ) // With AccessibilityPan its easier to move between snap positions
1532     {
1533       if((angle >= M_PI_2-orthoAngleRange) && (angle < M_PI_2+orthoAngleRange)) // Swiping South
1534       {
1535         biasY = 0.0f, vertical = Up;
1536       }
1537       else if((angle >= -M_PI_2-orthoAngleRange) && (angle < -M_PI_2+orthoAngleRange)) // Swiping North
1538       {
1539         biasY = 1.0f, vertical = Down;
1540       }
1541     }
1542   }
1543
1544   // isFlick: Whether this gesture is a flick or not.
1545   bool isFlick = (horizontal != All || vertical != All);
1546   // isFreeFlick: Whether this gesture is a flick under free panning criteria.
1547   bool isFreeFlick = velocity.LengthSquared() > (FREE_FLICK_SPEED_THRESHOLD*FREE_FLICK_SPEED_THRESHOLD);
1548
1549   if(isFlick || isFreeFlick)
1550   {
1551     positionDuration = Vector3::ONE * mFlickDuration;
1552     alphaFunction = mFlickAlphaFunction;
1553   }
1554
1555   // Calculate next positionSnap ////////////////////////////////////////////////////////////
1556
1557   if(mActorAutoSnapEnabled)
1558   {
1559     Vector3 size = Self().GetCurrentSize();
1560
1561     Actor child = FindClosestActorToPosition( Vector3(size.width * 0.5f,size.height * 0.5f,0.0f), horizontal, vertical );
1562
1563     if(!child && isFlick )
1564     {
1565       // If we conducted a direction limited search and found no actor, then just snap to the closest actor.
1566       child = FindClosestActorToPosition( Vector3(size.width * 0.5f,size.height * 0.5f,0.0f) );
1567     }
1568
1569     if(child)
1570     {
1571       Vector3 position = Self().GetProperty<Vector3>(mPropertyPosition);
1572
1573       // Get center-point of the Actor.
1574       Vector3 childPosition = GetPositionOfAnchor(child, AnchorPoint::CENTER);
1575
1576       if(mRulerX->IsEnabled())
1577       {
1578         positionSnap.x = position.x - childPosition.x + size.width * 0.5f;
1579       }
1580       if(mRulerY->IsEnabled())
1581       {
1582         positionSnap.y = position.y - childPosition.y + size.height * 0.5f;
1583       }
1584     }
1585   }
1586
1587   Vector3 startPosition = positionSnap;
1588   positionSnap.x = -mRulerX->Snap(-positionSnap.x, biasX);  // NOTE: X & Y rulers think in -ve coordinate system.
1589   positionSnap.y = -mRulerY->Snap(-positionSnap.y, biasY);  // That is scrolling RIGHT (e.g. 100.0, 0.0) means moving LEFT.
1590
1591   Vector3 clampDelta(Vector3::ZERO);
1592   ClampPosition(positionSnap);
1593
1594   if( (mRulerX->GetType() == Ruler::Free || mRulerY->GetType() == Ruler::Free)
1595       && isFreeFlick && !mActorAutoSnapEnabled)
1596   {
1597     // Calculate target position based on velocity of flick.
1598
1599     // a = Deceleration (Set to diagonal stage length * friction coefficient)
1600     // u = Initial Velocity (Flick velocity)
1601     // v = 0 (Final Velocity)
1602     // t = Time (Velocity / Deceleration)
1603     Vector2 stageSize = Stage::GetCurrent().GetSize();
1604     float stageLength = Vector3(stageSize.x, stageSize.y, 0.0f).Length();
1605     float a = (stageLength * mFrictionCoefficient);
1606     Vector3 u = Vector3(velocity.x, velocity.y, 0.0f) * mFlickSpeedCoefficient;
1607     float speed = u.Length();
1608     u/= speed;
1609
1610     // TODO: Change this to a decay function. (faster you flick, the slower it should be)
1611     speed = std::min(speed, stageLength * mMaxFlickSpeed );
1612     u*= speed;
1613     alphaFunction = ConstantDecelerationAlphaFunction;
1614
1615     float t = speed / a;
1616
1617     if(mRulerX->IsEnabled() && mRulerX->GetType() == Ruler::Free)
1618     {
1619       positionSnap.x += t*u.x*0.5f;
1620     }
1621
1622     if(mRulerY->IsEnabled() && mRulerY->GetType() == Ruler::Free)
1623     {
1624       positionSnap.y += t*u.y*0.5f;
1625     }
1626
1627     clampDelta = positionSnap;
1628     ClampPosition(positionSnap);
1629     if((positionSnap - startPosition).LengthSquared() > Math::MACHINE_EPSILON_0)
1630     {
1631       clampDelta -= positionSnap;
1632       clampDelta.x = clampDelta.x > 0.0f ? std::min(clampDelta.x, mMaxOvershoot.x) : std::max(clampDelta.x, -mMaxOvershoot.x);
1633       clampDelta.y = clampDelta.y > 0.0f ? std::min(clampDelta.y, mMaxOvershoot.y) : std::max(clampDelta.y, -mMaxOvershoot.y);
1634     }
1635     else
1636     {
1637       clampDelta = Vector3::ZERO;
1638     }
1639
1640     // If Axis is Free and has velocity, then calculate time taken
1641     // to reach target based on velocity in axis.
1642     if(mRulerX->IsEnabled() && mRulerX->GetType() == Ruler::Free)
1643     {
1644       float deltaX = fabsf(startPosition.x - positionSnap.x);
1645
1646       if(fabsf(u.x) > Math::MACHINE_EPSILON_1)
1647       {
1648         positionDuration.x = fabsf(deltaX / u.x);
1649       }
1650       else
1651       {
1652         positionDuration.x = 0;
1653       }
1654     }
1655
1656     if(mRulerY->IsEnabled() && mRulerY->GetType() == Ruler::Free)
1657     {
1658       float deltaY = fabsf(startPosition.y - positionSnap.y);
1659
1660       if(fabsf(u.y) > Math::MACHINE_EPSILON_1)
1661       {
1662         positionDuration.y = fabsf(deltaY / u.y);
1663       }
1664       else
1665       {
1666         positionDuration.y = 0;
1667       }
1668     }
1669   }
1670   positionSnap += clampDelta;
1671
1672   // Scale Snap ///////////////////////////////////////////////////////////////
1673   Vector3 scaleSnap = mScrollPostScale;
1674
1675   scaleSnap.x = mRulerScaleX->Snap(scaleSnap.x);
1676   scaleSnap.y = mRulerScaleY->Snap(scaleSnap.y);
1677
1678   ClampScale(scaleSnap);
1679
1680   // Rotation Snap ////////////////////////////////////////////////////////////
1681   float rotationSnap = mScrollPostRotation;
1682   // TODO: implement rotation snap
1683
1684   bool animating = AnimateTo(positionSnap, positionDuration,
1685                              scaleSnap, scaleDuration,
1686                              rotationSnap, rotationDuration,
1687                              alphaFunction, false,
1688                              DirectionBiasNone, DirectionBiasNone,
1689                              isFlick || isFreeFlick ? Flick : Snap);
1690
1691   return animating;
1692 }
1693
1694 void ScrollView::StopAnimation(void)
1695 {
1696   // Clear Snap animation if exists.
1697   StopAnimation(mSnapAnimation);
1698   StopAnimation(mInternalXAnimation);
1699   StopAnimation(mInternalYAnimation);
1700   mScrollStateFlags = 0;
1701   // remove scroll animation flags
1702   HandleStoppedAnimation();
1703 }
1704
1705 void ScrollView::StopAnimation(Animation& animation)
1706 {
1707   if(animation)
1708   {
1709     animation.Stop();
1710     animation.Reset();
1711   }
1712 }
1713
1714 bool ScrollView::AnimateTo(const Vector3& position, const Vector3& positionDuration,
1715                            const Vector3& scale, const Vector3& scaleDuration,
1716                            float rotation, float rotationDuration,
1717                            AlphaFunction alpha, bool findShortcuts,
1718                            DirectionBias horizontalBias, DirectionBias verticalBias,
1719                            SnapType snapType)
1720 {
1721   // Here we perform an animation on a number of properties (depending on which have changed)
1722   // The animation is applied to all ScrollBases
1723   Actor self = Self();
1724   mScrollTargetPosition = position;
1725   float totalDuration = 0.0f;
1726
1727   bool positionChanged = (mScrollTargetPosition != mScrollPostPosition);
1728   bool scaleChanged = (scale != mScrollPostScale);
1729   bool rotationChanged = fabsf(rotation - mScrollPostRotation) > Math::MACHINE_EPSILON_0;
1730
1731   if(positionChanged)
1732   {
1733     totalDuration = std::max(totalDuration, positionDuration.x);
1734     totalDuration = std::max(totalDuration, positionDuration.y);
1735   }
1736   else
1737   {
1738     // try to animate for a frame, on some occasions update will be changing scroll value while event side thinks it hasnt changed
1739     totalDuration = 0.01f;
1740     positionChanged = true;
1741   }
1742
1743   if(scaleChanged)
1744   {
1745     totalDuration = std::max(totalDuration, scaleDuration.x);
1746     totalDuration = std::max(totalDuration, scaleDuration.y);
1747   }
1748
1749   if(rotationChanged)
1750   {
1751     totalDuration = std::max(totalDuration, rotationDuration);
1752   }
1753   StopAnimation();
1754
1755   // Position Delta ///////////////////////////////////////////////////////
1756   if(positionChanged)
1757   {
1758     if(mWrapMode && findShortcuts)
1759     {
1760       // In Wrap Mode, the shortest distance is a little less intuitive...
1761       const RulerDomain rulerDomainX = mRulerX->GetDomain();
1762       const RulerDomain rulerDomainY = mRulerY->GetDomain();
1763
1764       if(mRulerX->IsEnabled())
1765       {
1766         float dir = VectorInDomain(-mScrollPostPosition.x, -mScrollTargetPosition.x, rulerDomainX.min, rulerDomainX.max, horizontalBias);
1767         mScrollTargetPosition.x = mScrollPostPosition.x + -dir;
1768       }
1769
1770       if(mRulerY->IsEnabled())
1771       {
1772         float dir = VectorInDomain(-mScrollPostPosition.y, -mScrollTargetPosition.y, rulerDomainY.min, rulerDomainY.max, verticalBias);
1773         mScrollTargetPosition.y = mScrollPostPosition.y + -dir;
1774       }
1775     }
1776
1777     // note we have two separate animations for X & Y, this deals with sliding diagonally and hitting
1778     // a horizonal/vertical wall.delay
1779     AnimateInternalXTo(mScrollTargetPosition.x, positionDuration.x, alpha);
1780     AnimateInternalYTo(mScrollTargetPosition.y, positionDuration.y, alpha);
1781
1782     if( !(mScrollStateFlags & SCROLL_ANIMATION_FLAGS) )
1783     {
1784       self.SetProperty(mPropertyPrePosition, mScrollTargetPosition);
1785       mScrollPrePosition = mScrollTargetPosition;
1786     }
1787   }
1788
1789   // Scale Delta ///////////////////////////////////////////////////////
1790   if(scaleChanged)
1791   {
1792     if(totalDuration > Math::MACHINE_EPSILON_1)
1793     {
1794       mSnapAnimation = Animation::New(totalDuration);
1795       mSnapAnimation.FinishedSignal().Connect(this, &ScrollView::OnScrollAnimationFinished);
1796       // TODO: for non-uniform scaling to different bounds e.g. scaling a square to a 4:3 aspect ratio screen with a velocity
1797       // the height will hit first, and then the width, so that would require two different animation times just like position.
1798       mSnapAnimation.AnimateTo( Property(self, mPropertyScale), scale, alpha, TimePeriod(0.0f, scaleDuration.x));
1799
1800       mSnapAnimation.AnimateTo( Property(self, mPropertyTime), totalDuration, AlphaFunctions::Linear );
1801       mSnapAnimation.Play();
1802     }
1803     else
1804     {
1805       self.SetProperty(mPropertyScale, scale);
1806
1807       mScrollPreScale = mScrollPostScale = scale;
1808     }
1809   }
1810   SetScrollUpdateNotification(true);
1811
1812   // Always send a snap event when AnimateTo is called.
1813   Toolkit::ScrollView::SnapEvent snapEvent;
1814   snapEvent.type = snapType;
1815   snapEvent.position = -mScrollTargetPosition;
1816   snapEvent.scale = scale;
1817   snapEvent.rotation = rotation;
1818   snapEvent.duration = totalDuration;
1819
1820   DALI_LOG_SCROLL_STATE("[0x%X] mSnapStartedSignalV2 [%.2f, %.2f]", this, snapEvent.position.x, snapEvent.position.y);
1821   mSnapStartedSignalV2.Emit( snapEvent );
1822
1823   return (mScrollStateFlags & SCROLL_ANIMATION_FLAGS) != 0;
1824 }
1825
1826 void ScrollView::SetOvershootEnabled(bool enabled)
1827 {
1828   if(enabled && !mOvershootIndicator)
1829   {
1830     mOvershootIndicator = ScrollOvershootIndicator::New();
1831   }
1832   if( enabled )
1833   {
1834     mMaxOvershoot = OVERSCROLL_CLAMP;
1835     mOvershootIndicator->AttachToScrollable(*this);
1836   }
1837   else
1838   {
1839     mMaxOvershoot = mUserMaxOvershoot;
1840     mOvershootIndicator->DetachFromScrollable(*this);
1841   }
1842   UpdateMainInternalConstraint();
1843 }
1844
1845 void ScrollView::AddOverlay(Actor actor)
1846 {
1847   mInternalActor.Add( actor );
1848 }
1849
1850 void ScrollView::RemoveOverlay(Actor actor)
1851 {
1852   mInternalActor.Remove( actor );
1853 }
1854
1855 void ScrollView::SetScrollingDirection( Radian direction, Radian threshold )
1856 {
1857   PanGestureDetector panGesture( GetPanGestureDetector() );
1858
1859   // First remove just in case we have some set, then add.
1860   panGesture.RemoveDirection( direction );
1861   panGesture.AddDirection( direction, threshold );
1862 }
1863
1864 void ScrollView::RemoveScrollingDirection( Radian direction )
1865 {
1866   PanGestureDetector panGesture( GetPanGestureDetector() );
1867   panGesture.RemoveDirection( direction );
1868 }
1869
1870 Toolkit::ScrollView::SnapStartedSignalV2& ScrollView::SnapStartedSignal()
1871 {
1872   return mSnapStartedSignalV2;
1873 }
1874
1875 void ScrollView::FindAndUnbindActor(Actor child)
1876 {
1877   UnbindActor(child);
1878 }
1879
1880 Vector3 ScrollView::GetPropertyPrePosition() const
1881 {
1882   Vector3 position = Self().GetProperty<Vector3>(mPropertyPrePosition);
1883   WrapPosition(position);
1884   return position;
1885 }
1886
1887 Vector3 ScrollView::GetPropertyPosition() const
1888 {
1889   Vector3 position = Self().GetProperty<Vector3>(mPropertyPosition);
1890   WrapPosition(position);
1891
1892   return position;
1893 }
1894
1895 Vector3 ScrollView::GetPropertyScale() const
1896 {
1897   return Self().GetProperty<Vector3>(mPropertyScale);
1898 }
1899
1900 void ScrollView::HandleStoppedAnimation()
1901 {
1902   SetScrollUpdateNotification(false);
1903 }
1904
1905 void ScrollView::HandleSnapAnimationFinished()
1906 {
1907   // Emit Signal that scrolling has completed.
1908   mScrolling = false;
1909   Actor self = Self();
1910   self.SetProperty(mPropertyScrolling, false);
1911
1912   Vector3 deltaPosition(mScrollPrePosition);
1913
1914   UpdateLocalScrollProperties();
1915   WrapPosition(mScrollPrePosition);
1916   self.SetProperty(mPropertyPrePosition, mScrollPrePosition);
1917
1918   Vector3 currentScrollPosition = GetCurrentScrollPosition();
1919   DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignalV2 3 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
1920   mScrollCompletedSignalV2.Emit( currentScrollPosition );
1921
1922   mDomainOffset += deltaPosition - mScrollPostPosition;
1923   self.SetProperty(mPropertyDomainOffset, mDomainOffset);
1924   HandleStoppedAnimation();
1925 }
1926
1927 void ScrollView::SetScrollUpdateNotification( bool enabled )
1928 {
1929   Actor self = Self();
1930   if( mScrollXUpdateNotification )
1931   {
1932     // disconnect now to avoid a notification before removed from update thread
1933     mScrollXUpdateNotification.NotifySignal().Disconnect(this, &ScrollView::OnScrollUpdateNotification);
1934     self.RemovePropertyNotification(mScrollXUpdateNotification);
1935     mScrollXUpdateNotification.Reset();
1936   }
1937   if( enabled )
1938   {
1939     mScrollXUpdateNotification = self.AddPropertyNotification(mPropertyPosition, 0, StepCondition(mScrollUpdateDistance, 0.0f));
1940     mScrollXUpdateNotification.NotifySignal().Connect( this, &ScrollView::OnScrollUpdateNotification );
1941   }
1942   if( mScrollYUpdateNotification )
1943   {
1944     // disconnect now to avoid a notification before removed from update thread
1945     mScrollYUpdateNotification.NotifySignal().Disconnect(this, &ScrollView::OnScrollUpdateNotification);
1946     self.RemovePropertyNotification(mScrollYUpdateNotification);
1947     mScrollYUpdateNotification.Reset();
1948   }
1949   if( enabled )
1950   {
1951     mScrollYUpdateNotification = self.AddPropertyNotification(mPropertyPosition, 1, StepCondition(mScrollUpdateDistance, 0.0f));
1952     mScrollYUpdateNotification.NotifySignal().Connect( this, &ScrollView::OnScrollUpdateNotification );
1953   }
1954 }
1955
1956 void ScrollView::OnScrollUpdateNotification(Dali::PropertyNotification& source)
1957 {
1958   // Guard against destruction during signal emission
1959   Toolkit::ScrollView handle( GetOwner() );
1960
1961   Vector3 currentScrollPosition = GetCurrentScrollPosition();
1962   mScrollUpdatedSignalV2.Emit( currentScrollPosition );
1963 }
1964
1965 bool ScrollView::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
1966 {
1967   Dali::BaseHandle handle( object );
1968
1969   bool connected( true );
1970   Toolkit::ScrollView view = Toolkit::ScrollView::DownCast( handle );
1971
1972   if( Toolkit::ScrollView::SIGNAL_SNAP_STARTED == signalName )
1973   {
1974     view.SnapStartedSignal().Connect( tracker, functor );
1975   }
1976   else
1977   {
1978     // signalName does not match any signal
1979     connected = false;
1980   }
1981
1982   return connected;
1983 }
1984
1985 void ScrollView::OnSizeAnimation(Animation& animation, const Vector3& targetSize)
1986 {
1987   // need to update domain properties for new size
1988   UpdatePropertyDomain(targetSize);
1989 }
1990
1991 void ScrollView::OnControlSizeSet( const Vector3& size )
1992 {
1993   // need to update domain properties for new size
1994   if( mDefaultMaxOvershoot )
1995   {
1996     mUserMaxOvershoot.x = size.x * 0.5f;
1997     mUserMaxOvershoot.y = size.y * 0.5f;
1998     if( !IsScrollComponentEnabled(Toolkit::Scrollable::OvershootIndicator) )
1999     {
2000       mMaxOvershoot = mUserMaxOvershoot;
2001     }
2002   }
2003   UpdatePropertyDomain(size);
2004   UpdateMainInternalConstraint();
2005   if( IsScrollComponentEnabled(Toolkit::Scrollable::OvershootIndicator) )
2006   {
2007     mOvershootIndicator->Reset();
2008   }
2009 }
2010
2011 void ScrollView::OnChildAdd(Actor& child)
2012 {
2013   if(mAlterChild)
2014   {
2015     BindActor(child);
2016   }
2017 }
2018
2019 void ScrollView::OnChildRemove(Actor& child)
2020 {
2021   // TODO: Actor needs a RemoveConstraint method to take out an individual constraint.
2022   UnbindActor(child);
2023 }
2024
2025 void ScrollView::OnPropertySet( Property::Index index, Property::Value propertyValue )
2026 {
2027   Actor self = Self();
2028   if( index == mPropertyX )
2029   {
2030     self.GetProperty(mPropertyPrePosition).Get(mScrollPrePosition);
2031     propertyValue.Get(mScrollPrePosition.x);
2032     self.SetProperty(mPropertyPrePosition, mScrollPrePosition);
2033   }
2034   else if( index == mPropertyY )
2035   {
2036     self.GetProperty(mPropertyPrePosition).Get(mScrollPrePosition);
2037     propertyValue.Get(mScrollPrePosition.y);
2038     self.SetProperty(mPropertyPrePosition, mScrollPrePosition);
2039   }
2040   else if( index == mPropertyPrePosition )
2041   {
2042     DALI_LOG_SCROLL_STATE("[0x%X]", this);
2043     propertyValue.Get(mScrollPrePosition);
2044   }
2045 }
2046
2047 void ScrollView::StartTouchDownTimer()
2048 {
2049   if ( !mTouchDownTimer )
2050   {
2051     mTouchDownTimer = Timer::New( TOUCH_DOWN_TIMER_INTERVAL );
2052     mTouchDownTimer.TickSignal().Connect( this, &ScrollView::OnTouchDownTimeout );
2053   }
2054
2055   mTouchDownTimer.Start();
2056 }
2057
2058 void ScrollView::StopTouchDownTimer()
2059 {
2060   if ( mTouchDownTimer )
2061   {
2062     mTouchDownTimer.Stop();
2063   }
2064 }
2065
2066 bool ScrollView::OnTouchDownTimeout()
2067 {
2068   mTouchDownTimeoutReached = true;
2069
2070   if( mScrollStateFlags & (SCROLL_ANIMATION_FLAGS | SNAP_ANIMATION_FLAGS) )
2071   {
2072     StopAnimation();
2073     if( mScrollStateFlags & SCROLL_ANIMATION_FLAGS )
2074     {
2075       mScrollInterrupted = true;
2076       // reset domain offset as scrolling from original plane.
2077       mDomainOffset = Vector3::ZERO;
2078       Self().SetProperty(mPropertyDomainOffset, Vector3::ZERO);
2079
2080       UpdateLocalScrollProperties();
2081       Vector3 currentScrollPosition = GetCurrentScrollPosition();
2082       DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignalV2 4 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
2083       mScrollCompletedSignalV2.Emit( currentScrollPosition );
2084     }
2085   }
2086
2087   return false;
2088 }
2089
2090 bool ScrollView::OnTouchEvent(const TouchEvent& event)
2091 {
2092   if(!mSensitive)
2093   {
2094     // Ignore this touch event, if scrollview is insensitive.
2095     return false;
2096   }
2097
2098   // Ignore events with multiple-touch points
2099   if (event.GetPointCount() != 1)
2100   {
2101     return false;
2102   }
2103
2104   if( event.GetPoint(0).state == TouchPoint::Down )
2105   {
2106     if(mGestureStackDepth==0)
2107     {
2108       mTouchDownTime = event.time;
2109
2110       // This allows time for a pan-gesture to start, to avoid breaking snap-animation behavior with fast flicks.
2111       // If touch-down does not become a pan (after timeout interval), then snap-animation can be interrupted.
2112       StartTouchDownTimer();
2113     }
2114   }
2115   else if( event.GetPoint(0).state == TouchPoint::Up )
2116   {
2117     StopTouchDownTimer();
2118
2119     // if the user touches and releases without enough movement to go
2120     // into a gesture state, then we should snap to nearest point.
2121     // otherwise our scroll could be stopped (interrupted) half way through an animation.
2122     if(mGestureStackDepth==0 && mTouchDownTimeoutReached)
2123     {
2124       unsigned timeDelta( event.time - mTouchDownTime );
2125       if ( timeDelta >= MINIMUM_TIME_BETWEEN_DOWN_AND_UP_FOR_RESET )
2126       {
2127         // Reset the velocity only if down was received a while ago
2128         mLastVelocity = Vector2( 0.0f, 0.0f );
2129       }
2130
2131       UpdateLocalScrollProperties();
2132       // Only finish the transform if scrolling was interrupted on down or if we are scrolling
2133       if ( mScrollInterrupted || mScrolling )
2134       {
2135         FinishTransform();
2136       }
2137     }
2138     mTouchDownTimeoutReached = false;
2139     mScrollInterrupted = false;
2140   }
2141
2142   return true;
2143 }
2144
2145 bool ScrollView::OnMouseWheelEvent(const MouseWheelEvent& event)
2146 {
2147   if(!mSensitive)
2148   {
2149     // Ignore this mouse wheel event, if scrollview is insensitive.
2150     return false;
2151   }
2152
2153   Vector3 targetScrollPosition = GetPropertyPosition();
2154
2155   if(mRulerX->IsEnabled() && !mRulerY->IsEnabled())
2156   {
2157     // If only the ruler in the X axis is enabled, scroll in the X axis.
2158     if(mRulerX->GetType() == Ruler::Free)
2159     {
2160       // Free panning mode
2161       targetScrollPosition.x += event.z * mMouseWheelScrollDistanceStep.x;
2162       ClampPosition(targetScrollPosition);
2163       ScrollTo(-targetScrollPosition);
2164     }
2165     else if(!mScrolling)
2166     {
2167       // Snap mode, only respond to the event when the previous snap animation is finished.
2168       ScrollTo(GetCurrentPage() - event.z);
2169     }
2170   }
2171   else
2172   {
2173     // If the ruler in the Y axis is enabled, scroll in the Y axis.
2174     if(mRulerY->GetType() == Ruler::Free)
2175     {
2176       // Free panning mode
2177       targetScrollPosition.y += event.z * mMouseWheelScrollDistanceStep.y;
2178       ClampPosition(targetScrollPosition);
2179       ScrollTo(-targetScrollPosition);
2180     }
2181     else if(!mScrolling)
2182     {
2183       // Snap mode, only respond to the event when the previous snap animation is finished.
2184       ScrollTo(GetCurrentPage() - event.z * mRulerX->GetTotalPages());
2185     }
2186   }
2187
2188   return true;
2189 }
2190
2191 void ScrollView::ResetScrolling()
2192 {
2193   Actor self = Self();
2194   self.GetProperty(mPropertyPosition).Get(mScrollPostPosition);
2195   mScrollPrePosition = mScrollPostPosition;
2196   self.SetProperty(mPropertyPrePosition, mScrollPostPosition);
2197 }
2198
2199 void ScrollView::UpdateLocalScrollProperties()
2200 {
2201   Actor self = Self();
2202   self.GetProperty(mPropertyPrePosition).Get(mScrollPrePosition);
2203   self.GetProperty(mPropertyPosition).Get(mScrollPostPosition);
2204 }
2205
2206 // private functions
2207
2208 void ScrollView::PreAnimatedScrollSetup()
2209 {
2210   // mPropertyPrePosition is our unclamped property with wrapping
2211   // mPropertyPosition is our final scroll position after clamping
2212
2213   Actor self = Self();
2214
2215   Vector3 deltaPosition(mScrollPostPosition);
2216   WrapPosition(mScrollPostPosition);
2217   mDomainOffset += deltaPosition - mScrollPostPosition;
2218   Self().SetProperty(mPropertyDomainOffset, mDomainOffset);
2219
2220   if( mScrollStateFlags & SCROLL_X_STATE_MASK )
2221   {
2222     // already performing animation on internal x position
2223     StopAnimation(mInternalXAnimation);
2224   }
2225
2226   if( mScrollStateFlags & SCROLL_Y_STATE_MASK )
2227   {
2228     // already performing animation on internal y position
2229     StopAnimation(mInternalYAnimation);
2230   }
2231
2232   mScrollStateFlags = 0;
2233
2234   mScrollPostScale = GetPropertyScale();
2235
2236   // Update Actor position with this wrapped value.
2237   // TODO Rotation
2238
2239   mScrollPreScale = mScrollPostScale;
2240   mScrollPreRotation = mScrollPostRotation;
2241 }
2242
2243 void ScrollView::FinaliseAnimatedScroll()
2244 {
2245   // TODO - common animation finishing code in here
2246 }
2247
2248 void ScrollView::AnimateInternalXTo( float position, float duration, AlphaFunction alpha )
2249 {
2250   StopAnimation(mInternalXAnimation);
2251
2252   if( duration > Math::MACHINE_EPSILON_10 )
2253   {
2254     Actor self = Self();
2255     mInternalXAnimation = Animation::New(duration);
2256     mInternalXAnimation.FinishedSignal().Connect(this, &ScrollView::OnScrollAnimationFinished);
2257     mInternalXAnimation.AnimateTo( Property(self, mPropertyPrePosition, 0), position, alpha, duration);
2258     mInternalXAnimation.Play();
2259
2260     // erase current state flags
2261     mScrollStateFlags &= ~SCROLL_X_STATE_MASK;
2262     // add internal animation state flag
2263     mScrollStateFlags |= AnimatingInternalX;
2264   }
2265 }
2266
2267 void ScrollView::AnimateInternalYTo( float position, float duration, AlphaFunction alpha )
2268 {
2269   StopAnimation(mInternalYAnimation);
2270
2271   if( duration > Math::MACHINE_EPSILON_10 )
2272   {
2273     Actor self = Self();
2274     mInternalYAnimation = Animation::New(duration);
2275     mInternalYAnimation.FinishedSignal().Connect(this, &ScrollView::OnScrollAnimationFinished);
2276     mInternalYAnimation.AnimateTo( Property(self, mPropertyPrePosition, 1), position, alpha, TimePeriod(duration));
2277     mInternalYAnimation.Play();
2278
2279     // erase current state flags
2280     mScrollStateFlags &= ~SCROLL_Y_STATE_MASK;
2281     // add internal animation state flag
2282     mScrollStateFlags |= AnimatingInternalY;
2283   }
2284 }
2285
2286 void ScrollView::OnScrollAnimationFinished( Animation& source )
2287 {
2288   // Guard against destruction during signal emission
2289   // Note that ScrollCompletedSignal is emitted from HandleSnapAnimationFinished()
2290   Toolkit::ScrollView handle( GetOwner() );
2291
2292   bool scrollingFinished = false;
2293
2294   // update our local scroll positions
2295   UpdateLocalScrollProperties();
2296
2297   if( source == mSnapAnimation )
2298   {
2299     // generic snap animation used for scaling and rotation
2300     mSnapAnimation.Reset();
2301   }
2302
2303   if( source == mInternalXAnimation )
2304   {
2305     if( !(mScrollStateFlags & AnimatingInternalY) )
2306     {
2307       scrollingFinished = true;
2308     }
2309     mInternalXAnimation.Reset();
2310     SnapInternalXTo(mScrollPostPosition.x);
2311   }
2312
2313   if( source == mInternalYAnimation )
2314   {
2315     if( !(mScrollStateFlags & AnimatingInternalX) )
2316     {
2317       scrollingFinished = true;
2318     }
2319     mInternalYAnimation.Reset();
2320     SnapInternalYTo(mScrollPostPosition.y);
2321   }
2322
2323   if(scrollingFinished)
2324   {
2325     HandleSnapAnimationFinished();
2326   }
2327 }
2328
2329 void ScrollView::OnSnapInternalPositionFinished( Animation& source )
2330 {
2331   Actor self = Self();
2332   UpdateLocalScrollProperties();
2333   if( source == mInternalXAnimation )
2334   {
2335     // clear internal x animation flags
2336     mScrollStateFlags &= ~SCROLL_X_STATE_MASK;
2337     mInternalXAnimation.Reset();
2338     WrapPosition(mScrollPrePosition);
2339   }
2340   if( source == mInternalYAnimation )
2341   {
2342     mScrollStateFlags &= ~SCROLL_Y_STATE_MASK;
2343     mInternalYAnimation.Reset();
2344     WrapPosition(mScrollPrePosition);
2345   }
2346 }
2347
2348 void ScrollView::SnapInternalXTo(float position)
2349 {
2350   Actor self = Self();
2351
2352   StopAnimation(mInternalXAnimation);
2353
2354   // erase current state flags
2355   mScrollStateFlags &= ~SCROLL_X_STATE_MASK;
2356
2357   // if internal x not equal to inputed parameter, animate it
2358   float duration = std::min(fabsf((position - mScrollPrePosition.x) / mMaxOvershoot.x) * mSnapOvershootDuration, mSnapOvershootDuration);
2359   if( duration > Math::MACHINE_EPSILON_1 )
2360   {
2361     mInternalXAnimation = Animation::New(duration);
2362     mInternalXAnimation.FinishedSignal().Connect(this, &ScrollView::OnSnapInternalPositionFinished);
2363     mInternalXAnimation.AnimateTo(Property(self, mPropertyPrePosition, 0), position);
2364     mInternalXAnimation.Play();
2365
2366     // add internal animation state flag
2367     mScrollStateFlags |= SnappingInternalX;
2368   }
2369 }
2370
2371 void ScrollView::SnapInternalYTo(float position)
2372 {
2373   Actor self = Self();
2374
2375   StopAnimation(mInternalYAnimation);
2376
2377   // erase current state flags
2378   mScrollStateFlags &= ~SCROLL_Y_STATE_MASK;
2379
2380   // if internal y not equal to inputed parameter, animate it
2381   float duration = std::min(fabsf((position - mScrollPrePosition.y) / mMaxOvershoot.y) * mSnapOvershootDuration, mSnapOvershootDuration);
2382   if( duration > Math::MACHINE_EPSILON_1 )
2383   {
2384     mInternalYAnimation = Animation::New(duration);
2385     mInternalYAnimation.FinishedSignal().Connect(this, &ScrollView::OnSnapInternalPositionFinished);
2386     mInternalYAnimation.AnimateTo(Property(self, mPropertyPrePosition, 1), position);
2387     mInternalYAnimation.Play();
2388
2389     // add internal animation state flag
2390     mScrollStateFlags |= SnappingInternalY;
2391   }
2392 }
2393
2394 void ScrollView::GestureStarted()
2395 {
2396   // we handle the first gesture.
2397   // if we're currently doing a gesture and receive another
2398   // we continue and combine the effects of the gesture instead of reseting.
2399   if(mGestureStackDepth++==0)
2400   {
2401     Actor self = Self();
2402     StopTouchDownTimer();
2403     StopAnimation();
2404     mPanDelta = Vector3::ZERO;
2405     mScaleDelta = Vector3::ONE;
2406     mRotationDelta = 0.0f;
2407     mLastVelocity = Vector2(0.0f, 0.0f);
2408     if( !mScrolling )
2409     {
2410       mLockAxis = LockPossible;
2411     }
2412
2413     if( mScrollStateFlags & SCROLL_X_STATE_MASK )
2414     {
2415       StopAnimation(mInternalXAnimation);
2416     }
2417     if( mScrollStateFlags & SCROLL_Y_STATE_MASK )
2418     {
2419       StopAnimation(mInternalYAnimation);
2420     }
2421     mScrollStateFlags = 0;
2422
2423     if(mScrolling) // are we interrupting a current scroll?
2424     {
2425       // set mScrolling to false, in case user has code that interrogates mScrolling Getter() in complete.
2426       mScrolling = false;
2427       // send negative scroll position since scroll internal scroll position works as an offset for actors,
2428       // give applications the position within the domain from the scroll view's anchor position
2429       DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignalV2 5 [%.2f, %.2f]", this, -mScrollPostPosition.x, -mScrollPostPosition.y);
2430       mScrollCompletedSignalV2.Emit( -mScrollPostPosition );
2431     }
2432   }
2433 }
2434
2435 void ScrollView::GestureContinuing(const Vector2& panDelta, const Vector2& scaleDelta, float rotationDelta)
2436 {
2437   mPanDelta.x+= panDelta.x;
2438   mPanDelta.y+= panDelta.y;
2439   mScaleDelta.x*= scaleDelta.x;
2440   mScaleDelta.y*= scaleDelta.y;
2441   mRotationDelta+= rotationDelta;
2442
2443   // Save the velocity, there is a bug in PanGesture
2444   // Whereby the Gesture::Finished's velocity is either:
2445   // NaN (due to time delta of zero between the last two events)
2446   // or 0 (due to position being the same between the last two events)
2447
2448   // Axis Auto Lock - locks the panning to the horizontal or vertical axis if the pan
2449   // appears mostly horizontal or mostly vertical respectively.
2450   if(mAxisAutoLock)
2451   {
2452     mLockAxis = GetLockAxis(mPanDelta.GetVectorXY(), mLockAxis, mAxisAutoLockGradient);
2453   } // end if mAxisAutoLock
2454 }
2455
2456 // TODO: Upgrade to use a more powerful gesture detector (one that supports multiple touches on pan - so works as pan and flick gesture)
2457 // TODO: Reimplement Scaling (pinching 2+ points)
2458 // TODO: Reimplment Rotation (pinching 2+ points)
2459 // BUG: Gesture::Finished doesn't always return velocity on release (due to
2460 // timeDelta between last two events being 0 sometimes, or posiiton being the same)
2461 void ScrollView::OnPan(PanGesture gesture)
2462 {
2463   // Guard against destruction during signal emission
2464   // Note that Emit() methods are called indirectly e.g. from within ScrollView::OnGestureEx()
2465   Actor self( Self() );
2466
2467   if(!mSensitive)
2468   {
2469     // If another callback on the same original signal disables sensitivity,
2470     // this callback will still be called, so we must suppress it.
2471     return;
2472   }
2473
2474   // translate Gesture input to get useful data...
2475   switch(gesture.state)
2476   {
2477     case Gesture::Started:
2478     {
2479       UpdateLocalScrollProperties();
2480       GestureStarted();
2481       mPanning = true;
2482       self.SetProperty( mPropertyPanning, true );
2483       self.SetProperty( mPropertyScrollStartPagePosition, Vector3(gesture.position.x, gesture.position.y, 0.0f) );
2484
2485       UpdateMainInternalConstraint();
2486       break;
2487     }
2488
2489     case Gesture::Continuing:
2490     {
2491       GestureContinuing(gesture.screenDisplacement, Vector2::ZERO, 0.0f);
2492       break;
2493     }
2494
2495     case Gesture::Finished:
2496     case Gesture::Cancelled:
2497     {
2498       UpdateLocalScrollProperties();
2499       mLastVelocity = gesture.velocity;
2500       mPanning = false;
2501       self.SetProperty( mPropertyPanning, false );
2502
2503       if( mScrollMainInternalPrePositionConstraint )
2504       {
2505         self.RemoveConstraint(mScrollMainInternalPrePositionConstraint);
2506       }
2507       break;
2508     }
2509
2510     case Gesture::Possible:
2511     case Gesture::Clear:
2512     {
2513       // Nothing to do, not needed.
2514       break;
2515     }
2516
2517   } // end switch(gesture.state)
2518
2519   OnGestureEx(gesture.state);
2520 }
2521
2522 void ScrollView::OnGestureEx(Gesture::State state)
2523 {
2524   // call necessary signals for application developer
2525
2526   if(state == Gesture::Started)
2527   {
2528     Vector3 currentScrollPosition = GetCurrentScrollPosition();
2529     Self().SetProperty(mPropertyScrolling, true);
2530     mScrolling = true;
2531     DALI_LOG_SCROLL_STATE("[0x%X] mScrollStartedSignalV2 2 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
2532     mScrollStartedSignalV2.Emit( currentScrollPosition );
2533   }
2534   else if( (state == Gesture::Finished) ||
2535            (state == Gesture::Cancelled) ) // Finished/default
2536   {
2537     // when all the gestures have finished, we finish the transform.
2538     // so if a user decides to pan (1 gesture), and then pan+zoom (2 gestures)
2539     // then stop panning (back to 1 gesture), and then stop zooming (0 gestures).
2540     // this is the point we end, and perform necessary snapping.
2541     mGestureStackDepth--;
2542     if(mGestureStackDepth==0)
2543     {
2544       FinishTransform();
2545     }
2546   }
2547 }
2548
2549 void ScrollView::UpdateTransform()
2550 {
2551 // TODO: notify clamps using property notifications (or see if we need this, can deprecate it)
2552 }
2553
2554 void ScrollView::FinishTransform()
2555 {
2556   // at this stage internal x and x scroll position should have followed prescroll position exactly
2557   Actor self = Self();
2558
2559   PreAnimatedScrollSetup();
2560
2561   bool animating = SnapWithVelocity(mLastVelocity * 1000.0f);
2562
2563   if(!animating)
2564   {
2565     // if not animating, then this pan has completed right now.
2566     SetScrollUpdateNotification(false);
2567     mScrolling = false;
2568     Self().SetProperty(mPropertyScrolling, false);
2569     Vector3 currentScrollPosition = GetCurrentScrollPosition();
2570     DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignalV2 6 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
2571     mScrollCompletedSignalV2.Emit( currentScrollPosition );
2572   }
2573 }
2574
2575 Vector3 ScrollView::GetOvershoot(Vector3& position) const
2576 {
2577   Vector3 size = Self().GetCurrentSize();
2578   Vector3 overshoot;
2579
2580   const RulerDomain rulerDomainX = mRulerX->GetDomain();
2581   const RulerDomain rulerDomainY = mRulerY->GetDomain();
2582
2583   if(mRulerX->IsEnabled() && rulerDomainX.enabled)
2584   {
2585     const float left = rulerDomainX.min - position.x;
2586     const float right = size.width - rulerDomainX.max - position.x;
2587     if(left<0)
2588     {
2589       overshoot.x = left;
2590     }
2591     else if(right>0)
2592     {
2593       overshoot.x = right;
2594     }
2595   }
2596
2597   if(mRulerY->IsEnabled() && rulerDomainY.enabled)
2598   {
2599     const float top = rulerDomainY.min - position.y;
2600     const float bottom = size.height - rulerDomainY.max - position.y;
2601     if(top<0)
2602     {
2603       overshoot.y = top;
2604     }
2605     else if(bottom>0)
2606     {
2607       overshoot.y = bottom;
2608     }
2609   }
2610
2611   return overshoot;
2612 }
2613
2614 bool ScrollView::OnAccessibilityPan(PanGesture gesture)
2615 {
2616   // Keep track of whether this is an AccessibilityPan
2617   mInAccessibilityPan = true;
2618   OnPan(gesture);
2619   mInAccessibilityPan = false;
2620
2621   return true;
2622 }
2623
2624 void ScrollView::ClampPosition(Vector3& position) const
2625 {
2626   ClampState3 clamped;
2627   ClampPosition(position, clamped);
2628 }
2629
2630 void ScrollView::ClampPosition(Vector3& position, ClampState3 &clamped) const
2631 {
2632   Vector3 size = Self().GetCurrentSize();
2633
2634   // determine size of viewport relative to current scaled size.
2635   // e.g. if you're zoomed in 200%, then each pixel on screen is only 0.5 pixels on subject.
2636   if(fabsf(mScrollPostScale.x) > Math::MACHINE_EPSILON_0)
2637   {
2638     size.x /= mScrollPostScale.x;
2639   }
2640
2641   if(fabsf(mScrollPostScale.y) > Math::MACHINE_EPSILON_0)
2642   {
2643     size.y /= mScrollPostScale.y;
2644   }
2645
2646   position.x = -mRulerX->Clamp(-position.x, size.width, 1.0f, clamped.x);    // NOTE: X & Y rulers think in -ve coordinate system.
2647   position.y = -mRulerY->Clamp(-position.y, size.height, 1.0f, clamped.y);   // That is scrolling RIGHT (e.g. 100.0, 0.0) means moving LEFT.
2648
2649   clamped.z = NotClamped;
2650 }
2651
2652 void ScrollView::WrapPosition(Vector3& position) const
2653 {
2654   if(mWrapMode)
2655   {
2656     const RulerDomain rulerDomainX = mRulerX->GetDomain();
2657     const RulerDomain rulerDomainY = mRulerY->GetDomain();
2658
2659     if(mRulerX->IsEnabled())
2660     {
2661       position.x = -WrapInDomain(-position.x, rulerDomainX.min, rulerDomainX.max);
2662     }
2663
2664     if(mRulerY->IsEnabled())
2665     {
2666       position.y = -WrapInDomain(-position.y, rulerDomainY.min, rulerDomainY.max);
2667     }
2668   }
2669 }
2670
2671 void ScrollView::ClampScale(Vector3& scale) const
2672 {
2673   ClampState3 clamped;
2674   ClampScale(scale, clamped);
2675 }
2676
2677 void ScrollView::ClampScale(Vector3& scale, ClampState3 &clamped) const
2678 {
2679   scale.x = mRulerScaleX->Clamp(scale.x, 0.0f, 1.0f, clamped.x);
2680   scale.y = mRulerScaleY->Clamp(scale.y, 0.0f, 1.0f, clamped.y);
2681   clamped.z = NotClamped;
2682 }
2683
2684 void ScrollView::UpdateMainInternalConstraint()
2685 {
2686   // TODO: Only update the constraints which have changed, rather than remove all and add all again.
2687   // Requires a dali-core ApplyConstraintAt, or a ReplaceConstraint. The former is probably more flexible.
2688   Actor self = Self();
2689   PanGestureDetector detector( GetPanGestureDetector() );
2690
2691   if(mScrollMainInternalPositionConstraint)
2692   {
2693     self.RemoveConstraint(mScrollMainInternalPositionConstraint);
2694     self.RemoveConstraint(mScrollMainInternalDeltaConstraint);
2695     self.RemoveConstraint(mScrollMainInternalFinalConstraint);
2696     self.RemoveConstraint(mScrollMainInternalRelativeConstraint);
2697     self.RemoveConstraint(mScrollMainInternalXConstraint);
2698     self.RemoveConstraint(mScrollMainInternalYConstraint);
2699   }
2700   if( mScrollMainInternalPrePositionConstraint )
2701   {
2702     self.RemoveConstraint(mScrollMainInternalPrePositionConstraint);
2703   }
2704
2705   // TODO: It's probably better to use a local displacement value as this will give a displacement when scrolling just commences
2706   // but we need to make sure than the gesture system gives displacement since last frame (60Hz), not displacement since last touch event (90Hz).
2707
2708   // 1. First calculate the pre-position (this is the scroll position if no clamping has taken place)
2709   Vector2 initialPanMask = Vector2(mRulerX->IsEnabled() ? 1.0f : 0.0f, mRulerY->IsEnabled() ? 1.0f : 0.0f);
2710
2711   if( mLockAxis == LockVertical )
2712   {
2713     initialPanMask.y = 0.0f;
2714   }
2715   else if( mLockAxis == LockHorizontal )
2716   {
2717     initialPanMask.x = 0.0f;
2718   }
2719   Constraint constraint;
2720
2721   if( mPanning )
2722   {
2723     constraint = Constraint::New<Vector3>( mPropertyPrePosition,
2724                                                       Source( detector, PanGestureDetector::LOCAL_POSITION ),
2725                                                       Source( detector, PanGestureDetector::LOCAL_DISPLACEMENT ),
2726                                                       Source( self, Actor::SIZE ),
2727                                                       InternalPrePositionConstraint( initialPanMask, mAxisAutoLock, mAxisAutoLockGradient, mLockAxis, mMaxOvershoot, mRulerX->GetDomain(), mRulerY->GetDomain() ) );
2728     mScrollMainInternalPrePositionConstraint = self.ApplyConstraint( constraint );
2729   }
2730
2731   // 2. Second calculate the clamped position (actual position)
2732   constraint = Constraint::New<Vector3>( mPropertyPosition,
2733                                          LocalSource( mPropertyPrePosition ),
2734                                          LocalSource( mPropertyPositionMin ),
2735                                          LocalSource( mPropertyPositionMax ),
2736                                          Source( self, Actor::SIZE ),
2737                                          InternalPositionConstraint( mRulerX->GetDomain(),
2738                                                                      mRulerY->GetDomain(), mWrapMode ) );
2739   mScrollMainInternalPositionConstraint = self.ApplyConstraint( constraint );
2740
2741   constraint = Constraint::New<Vector3>( mPropertyPositionDelta,
2742                                          LocalSource( mPropertyPosition ),
2743                                          LocalSource( mPropertyDomainOffset ),
2744                                          InternalPositionDeltaConstraint );
2745   mScrollMainInternalDeltaConstraint = self.ApplyConstraint( constraint );
2746
2747   constraint = Constraint::New<Vector3>( mPropertyFinal,
2748                                          LocalSource( mPropertyPosition ),
2749                                          LocalSource( mPropertyOvershootX ),
2750                                          LocalSource( mPropertyOvershootY ),
2751                                          InternalFinalConstraint( FinalDefaultAlphaFunction,
2752                                                                   FinalDefaultAlphaFunction ) );
2753   mScrollMainInternalFinalConstraint = self.ApplyConstraint( constraint );
2754
2755   constraint = Constraint::New<Vector3>( mPropertyRelativePosition,
2756                                          LocalSource( mPropertyPosition ),
2757                                          LocalSource( mPropertyPositionMin ),
2758                                          LocalSource( mPropertyPositionMax ),
2759                                          LocalSource( Actor::SIZE ),
2760                                          InternalRelativePositionConstraint );
2761   mScrollMainInternalRelativeConstraint = self.ApplyConstraint( constraint );
2762
2763   constraint = Constraint::New<float>( mPropertyX,
2764                                          LocalSource( mPropertyPrePosition ),
2765                                          InternalXConstraint );
2766   mScrollMainInternalXConstraint = self.ApplyConstraint( constraint );
2767
2768   constraint = Constraint::New<float>( mPropertyY,
2769                                          LocalSource( mPropertyPrePosition ),
2770                                          InternalYConstraint );
2771   mScrollMainInternalYConstraint = self.ApplyConstraint( constraint );
2772
2773   // When panning we want to make sure overshoot values are affected by pre position and post position
2774   SetOvershootConstraintsEnabled(!mWrapMode);
2775 }
2776
2777 void ScrollView::SetOvershootConstraintsEnabled(bool enabled)
2778 {
2779   Actor self( Self() );
2780   // remove and reset, it may now be in wrong order with the main internal constraints
2781   if( mScrollMainInternalOvershootXConstraint )
2782   {
2783     self.RemoveConstraint(mScrollMainInternalOvershootXConstraint);
2784     mScrollMainInternalOvershootXConstraint.Reset();
2785     self.RemoveConstraint(mScrollMainInternalOvershootYConstraint);
2786     mScrollMainInternalOvershootYConstraint.Reset();
2787   }
2788   if( enabled )
2789   {
2790     Constraint constraint = Constraint::New<float>( mPropertyOvershootX,
2791                                            LocalSource( mPropertyPrePosition ),
2792                                            LocalSource( mPropertyPosition ),
2793                                            LocalSource( mPropertyCanScrollHorizontal ),
2794                                            OvershootXConstraint(mMaxOvershoot.x) );
2795     mScrollMainInternalOvershootXConstraint = self.ApplyConstraint( constraint );
2796
2797     constraint = Constraint::New<float>( mPropertyOvershootY,
2798                                            LocalSource( mPropertyPrePosition ),
2799                                            LocalSource( mPropertyPosition ),
2800                                            LocalSource( mPropertyCanScrollVertical ),
2801                                            OvershootYConstraint(mMaxOvershoot.y) );
2802     mScrollMainInternalOvershootYConstraint = self.ApplyConstraint( constraint );
2803   }
2804   else
2805   {
2806     self.SetProperty(mPropertyOvershootX, 0.0f);
2807     self.SetProperty(mPropertyOvershootY, 0.0f);
2808   }
2809 }
2810
2811 void ScrollView::SetInternalConstraints()
2812 {
2813   // Internal constraints (applied to target ScrollBase Actor itself) /////////
2814   UpdateMainInternalConstraint();
2815
2816   // User definable constraints to apply to all child actors //////////////////
2817   Actor self = Self();
2818
2819   // LocalSource - The Actors to be moved.
2820   // self - The ScrollView
2821
2822   // Apply some default constraints to ScrollView.
2823   // Movement + Scaling + Wrap function
2824
2825   Constraint constraint;
2826
2827   // MoveScaledActor (scrolling/zooming)
2828   constraint = Constraint::New<Vector3>( Actor::POSITION,
2829                                          Source( self, mPropertyPosition ),
2830                                          Source( self, mPropertyScale ),
2831                                          MoveScaledActorConstraint );
2832   constraint.SetRemoveAction(Constraint::Discard);
2833   ApplyConstraintToBoundActors(constraint);
2834
2835   // ScaleActor (scrolling/zooming)
2836   constraint = Constraint::New<Vector3>( Actor::SCALE,
2837                                          Source( self, mPropertyScale ),
2838                                          ScaleActorConstraint );
2839   constraint.SetRemoveAction(Constraint::Discard);
2840   ApplyConstraintToBoundActors(constraint);
2841
2842   // WrapActor (wrap functionality)
2843   constraint = Constraint::New<Vector3>( Actor::POSITION,
2844                                                  LocalSource( Actor::SCALE ),
2845                                                  LocalSource( Actor::ANCHOR_POINT ),
2846                                                  LocalSource( Actor::SIZE ),
2847                                                  Source( self, mPropertyPositionMin ),
2848                                                  Source( self, mPropertyPositionMax ),
2849                                                  Source( self, mPropertyWrap ),
2850                                                  WrapActorConstraint );
2851   constraint.SetRemoveAction(Constraint::Discard);
2852   ApplyConstraintToBoundActors(constraint);
2853 }
2854
2855 } // namespace Internal
2856
2857 } // namespace Toolkit
2858
2859 } // namespace Dali