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