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