[dali_1.2.10] Merge branch 'devel/master'
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / controls / scrollable / scroll-view / scroll-view-impl.cpp
1 /*
2  * Copyright (c) 2015 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   ScrollBase::OnStageConnection( depth );
705
706   DALI_LOG_SCROLL_STATE("[0x%X]", this);
707
708   if ( mSensitive )
709   {
710     SetScrollSensitive( false );
711     SetScrollSensitive( true );
712   }
713   if(IsOvershootEnabled())
714   {
715     // try and make sure property notifications are set
716     EnableScrollOvershoot(true);
717   }
718 }
719
720 void ScrollView::OnStageDisconnection()
721 {
722   DALI_LOG_SCROLL_STATE("[0x%X]", this);
723
724   StopAnimation();
725
726   ScrollBase::OnStageDisconnection();
727 }
728
729 ScrollView::~ScrollView()
730 {
731   DALI_LOG_SCROLL_STATE("[0x%X]", this);
732 }
733
734 AlphaFunction ScrollView::GetScrollSnapAlphaFunction() const
735 {
736   return mSnapAlphaFunction;
737 }
738
739 void ScrollView::SetScrollSnapAlphaFunction(AlphaFunction alpha)
740 {
741   mSnapAlphaFunction = alpha;
742 }
743
744 AlphaFunction ScrollView::GetScrollFlickAlphaFunction() const
745 {
746   return mFlickAlphaFunction;
747 }
748
749 void ScrollView::SetScrollFlickAlphaFunction(AlphaFunction alpha)
750 {
751   mFlickAlphaFunction = alpha;
752 }
753
754 float ScrollView::GetScrollSnapDuration() const
755 {
756   return mSnapDuration;
757 }
758
759 void ScrollView::SetScrollSnapDuration(float time)
760 {
761   mSnapDuration = time;
762 }
763
764 float ScrollView::GetScrollFlickDuration() const
765 {
766   return mFlickDuration;
767 }
768
769 void ScrollView::SetScrollFlickDuration(float time)
770 {
771   mFlickDuration = time;
772 }
773
774 void ScrollView::ApplyEffect(Toolkit::ScrollViewEffect effect)
775 {
776   Dali::Toolkit::ScrollView self = Dali::Toolkit::ScrollView::DownCast(Self());
777
778   // Assertion check to ensure effect doesn't already exist in this scrollview
779   bool effectAlreadyExistsInScrollView(false);
780   for (ScrollViewEffectIter iter = mEffects.begin(); iter != mEffects.end(); ++iter)
781   {
782     if(*iter==effect)
783     {
784       effectAlreadyExistsInScrollView = true;
785       break;
786     }
787   }
788
789   DALI_ASSERT_ALWAYS(!effectAlreadyExistsInScrollView);
790
791   // add effect to effects list
792   mEffects.push_back(effect);
793
794   // invoke Attachment request to ScrollView first
795   GetImpl(effect).Attach(self);
796 }
797
798 void ScrollView::RemoveEffect(Toolkit::ScrollViewEffect effect)
799 {
800   Dali::Toolkit::ScrollView self = Dali::Toolkit::ScrollView::DownCast(Self());
801
802   // remove effect from effects list
803   bool effectExistedInScrollView(false);
804   for (ScrollViewEffectIter iter = mEffects.begin(); iter != mEffects.end(); ++iter)
805   {
806     if(*iter==effect)
807     {
808       mEffects.erase(iter);
809       effectExistedInScrollView = true;
810       break;
811     }
812   }
813
814   // Assertion check to ensure effect existed.
815   DALI_ASSERT_ALWAYS(effectExistedInScrollView);
816
817   // invoke Detachment request to ScrollView last
818   GetImpl(effect).Detach(self);
819 }
820
821 void ScrollView::RemoveAllEffects()
822 {
823   Dali::Toolkit::ScrollView self = Dali::Toolkit::ScrollView::DownCast(Self());
824
825   for (ScrollViewEffectIter effectIter = mEffects.begin(); effectIter != mEffects.end(); ++effectIter)
826   {
827     Toolkit::ScrollViewEffect effect = *effectIter;
828
829     // invoke Detachment request to ScrollView last
830     GetImpl(effect).Detach(self);
831   }
832
833   mEffects.clear();
834 }
835
836 void ScrollView::ApplyConstraintToChildren(Constraint constraint)
837 {
838   ApplyConstraintToBoundActors(constraint);
839 }
840
841 void ScrollView::RemoveConstraintsFromChildren()
842 {
843   RemoveConstraintsFromBoundActors();
844 }
845
846 const RulerPtr ScrollView::GetRulerX() const
847 {
848   return mRulerX;
849 }
850
851 const RulerPtr ScrollView::GetRulerY() const
852 {
853   return mRulerY;
854 }
855
856 void ScrollView::SetRulerX(RulerPtr ruler)
857 {
858   mRulerX = ruler;
859
860   UpdatePropertyDomain();
861   UpdateMainInternalConstraint();
862 }
863
864 void ScrollView::SetRulerY(RulerPtr ruler)
865 {
866   mRulerY = ruler;
867
868   UpdatePropertyDomain();
869   UpdateMainInternalConstraint();
870 }
871
872 void ScrollView::UpdatePropertyDomain()
873 {
874   Actor self = Self();
875   Vector3 size = self.GetTargetSize();
876   Vector2 min = mMinScroll;
877   Vector2 max = mMaxScroll;
878   bool scrollPositionChanged = false;
879   bool domainChanged = false;
880
881   bool canScrollVertical = false;
882   bool canScrollHorizontal = false;
883   UpdateLocalScrollProperties();
884   if(mRulerX->IsEnabled())
885   {
886     const Toolkit::RulerDomain& rulerDomain = mRulerX->GetDomain();
887     if( fabsf(min.x - rulerDomain.min) > Math::MACHINE_EPSILON_100
888         || fabsf(max.x - rulerDomain.max) > Math::MACHINE_EPSILON_100 )
889     {
890       domainChanged = true;
891       min.x = rulerDomain.min;
892       max.x = rulerDomain.max;
893
894       // make sure new scroll value is within new domain
895       if( mScrollPrePosition.x < min.x
896           || mScrollPrePosition.x > max.x )
897       {
898         scrollPositionChanged = true;
899         mScrollPrePosition.x = Clamp(mScrollPrePosition.x, -(max.x - size.x), -min.x);
900       }
901     }
902     if( (fabsf(rulerDomain.max - rulerDomain.min) - size.x) > Math::MACHINE_EPSILON_100 )
903     {
904       canScrollHorizontal = true;
905     }
906   }
907   else if( fabs(min.x) > Math::MACHINE_EPSILON_100
908            || fabs(max.x) > Math::MACHINE_EPSILON_100 )
909   {
910     // need to reset to 0
911     domainChanged = true;
912     min.x = 0.0f;
913     max.x = 0.0f;
914     canScrollHorizontal = false;
915   }
916
917   if(mRulerY->IsEnabled())
918   {
919     const Toolkit::RulerDomain& rulerDomain = mRulerY->GetDomain();
920     if( fabsf(min.y - rulerDomain.min) > Math::MACHINE_EPSILON_100
921         || fabsf(max.y - rulerDomain.max) > Math::MACHINE_EPSILON_100 )
922     {
923       domainChanged = true;
924       min.y = rulerDomain.min;
925       max.y = rulerDomain.max;
926
927       // make sure new scroll value is within new domain
928       if( mScrollPrePosition.y < min.y
929           || mScrollPrePosition.y > max.y )
930       {
931         scrollPositionChanged = true;
932         mScrollPrePosition.y = Clamp(mScrollPrePosition.y, -(max.y - size.y), -min.y);
933       }
934     }
935     if( (fabsf(rulerDomain.max - rulerDomain.min) - size.y) > Math::MACHINE_EPSILON_100 )
936     {
937       canScrollVertical = true;
938     }
939   }
940   else if( fabs(min.y) > Math::MACHINE_EPSILON_100
941            || fabs(max.y) > Math::MACHINE_EPSILON_100 )
942   {
943     // need to reset to 0
944     domainChanged = true;
945     min.y = 0.0f;
946     max.y = 0.0f;
947     canScrollVertical = false;
948   }
949
950   // avoid setting properties if possible, otherwise this will cause an entire update as well as triggering constraints using each property we update
951   if( mCanScrollVertical != canScrollVertical )
952   {
953     mCanScrollVertical = canScrollVertical;
954     self.SetProperty(Toolkit::Scrollable::Property::CAN_SCROLL_VERTICAL, canScrollVertical);
955   }
956   if( mCanScrollHorizontal != canScrollHorizontal )
957   {
958     mCanScrollHorizontal = canScrollHorizontal;
959     self.SetProperty(Toolkit::Scrollable::Property::CAN_SCROLL_HORIZONTAL, canScrollHorizontal);
960   }
961   if( scrollPositionChanged )
962   {
963     DALI_LOG_SCROLL_STATE("[0x%X] Domain Changed, setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y );
964     self.SetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, mScrollPrePosition);
965   }
966   if( domainChanged )
967   {
968     mMinScroll = min;
969     mMaxScroll = max;
970     self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MIN, mMinScroll );
971     self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX, mMaxScroll );
972   }
973 }
974
975 bool ScrollView::GetScrollSensitive()
976 {
977   return mSensitive;
978 }
979
980 void ScrollView::SetScrollSensitive(bool sensitive)
981 {
982   Actor self = Self();
983   PanGestureDetector panGesture( GetPanGestureDetector() );
984
985   DALI_LOG_SCROLL_STATE("[0x%X] sensitive: before:[%d] setting[%d]", this, int(mSensitive), int(sensitive));
986
987   if((!mSensitive) && (sensitive))
988   {
989     mSensitive = sensitive;
990     panGesture.Attach(self);
991   }
992   else if((mSensitive) && (!sensitive))
993   {
994     DALI_LOG_SCROLL_STATE("[0x%X] BEFORE: panning:[%d]", this, int(mPanning));
995
996     // while the scroll view is panning, the state needs to be reset.
997     if ( mPanning )
998     {
999       PanGesture cancelGesture( Gesture::Cancelled );
1000       OnPan( cancelGesture );
1001     }
1002
1003     panGesture.Detach(self);
1004     mSensitive = sensitive;
1005
1006     mGestureStackDepth = 0;
1007     DALI_LOG_SCROLL_STATE("[0x%X] AFTER: panning:[%d]", this, int(mPanning));
1008   }
1009 }
1010
1011 void ScrollView::SetMaxOvershoot(float overshootX, float overshootY)
1012 {
1013   mMaxOvershoot.x = overshootX;
1014   mMaxOvershoot.y = overshootY;
1015   mUserMaxOvershoot = mMaxOvershoot;
1016   mDefaultMaxOvershoot = false;
1017   UpdateMainInternalConstraint();
1018 }
1019
1020 void ScrollView::SetSnapOvershootAlphaFunction(AlphaFunction alpha)
1021 {
1022   mSnapOvershootAlphaFunction = alpha;
1023 }
1024
1025 float ScrollView::GetSnapOvershootDuration()
1026 {
1027   return mSnapOvershootDuration;
1028 }
1029
1030 void ScrollView::SetSnapOvershootDuration(float duration)
1031 {
1032   mSnapOvershootDuration = duration;
1033 }
1034
1035 bool ScrollView::GetActorAutoSnap()
1036 {
1037   return mActorAutoSnapEnabled;
1038 }
1039
1040 void ScrollView::SetActorAutoSnap(bool enable)
1041 {
1042   mActorAutoSnapEnabled = enable;
1043 }
1044
1045 void ScrollView::SetAutoResize(bool enable)
1046 {
1047   mAutoResizeContainerEnabled = enable;
1048   // TODO: This needs a lot of issues to be addressed before working.
1049 }
1050
1051 bool ScrollView::GetWrapMode() const
1052 {
1053   return mWrapMode;
1054 }
1055
1056 void ScrollView::SetWrapMode(bool enable)
1057 {
1058   mWrapMode = enable;
1059   Self().SetProperty(Toolkit::ScrollView::Property::WRAP, enable);
1060 }
1061
1062 int ScrollView::GetScrollUpdateDistance() const
1063 {
1064   return mScrollUpdateDistance;
1065 }
1066
1067 void ScrollView::SetScrollUpdateDistance(int distance)
1068 {
1069   mScrollUpdateDistance = distance;
1070 }
1071
1072 bool ScrollView::GetAxisAutoLock() const
1073 {
1074   return mAxisAutoLock;
1075 }
1076
1077 void ScrollView::SetAxisAutoLock(bool enable)
1078 {
1079   mAxisAutoLock = enable;
1080   UpdateMainInternalConstraint();
1081 }
1082
1083 float ScrollView::GetAxisAutoLockGradient() const
1084 {
1085   return mAxisAutoLockGradient;
1086 }
1087
1088 void ScrollView::SetAxisAutoLockGradient(float gradient)
1089 {
1090   DALI_ASSERT_DEBUG( gradient >= 0.0f && gradient <= 1.0f );
1091   mAxisAutoLockGradient = gradient;
1092   UpdateMainInternalConstraint();
1093 }
1094
1095 float ScrollView::GetFrictionCoefficient() const
1096 {
1097   return mFrictionCoefficient;
1098 }
1099
1100 void ScrollView::SetFrictionCoefficient(float friction)
1101 {
1102   DALI_ASSERT_DEBUG( friction > 0.0f );
1103   mFrictionCoefficient = friction;
1104 }
1105
1106 float ScrollView::GetFlickSpeedCoefficient() const
1107 {
1108   return mFlickSpeedCoefficient;
1109 }
1110
1111 void ScrollView::SetFlickSpeedCoefficient(float speed)
1112 {
1113   mFlickSpeedCoefficient = speed;
1114 }
1115
1116 Vector2 ScrollView::GetMinimumDistanceForFlick() const
1117 {
1118   return mMinFlickDistance;
1119 }
1120
1121 void ScrollView::SetMinimumDistanceForFlick( const Vector2& distance )
1122 {
1123   mMinFlickDistance = distance;
1124 }
1125
1126 float ScrollView::GetMinimumSpeedForFlick() const
1127 {
1128   return mFlickSpeedThreshold;
1129 }
1130
1131 void ScrollView::SetMinimumSpeedForFlick( float speed )
1132 {
1133   mFlickSpeedThreshold = speed;
1134 }
1135
1136 float ScrollView::GetMaxFlickSpeed() const
1137 {
1138   return mMaxFlickSpeed;
1139 }
1140
1141 void ScrollView::SetMaxFlickSpeed(float speed)
1142 {
1143   mMaxFlickSpeed = speed;
1144 }
1145
1146 void ScrollView::SetWheelScrollDistanceStep(Vector2 step)
1147 {
1148   mWheelScrollDistanceStep = step;
1149 }
1150
1151 Vector2 ScrollView::GetWheelScrollDistanceStep() const
1152 {
1153   return mWheelScrollDistanceStep;
1154 }
1155
1156 unsigned int ScrollView::GetCurrentPage() const
1157 {
1158   // in case animation is currently taking place.
1159   Vector2 position = GetPropertyPosition();
1160
1161   Actor self = Self();
1162   unsigned int page = 0;
1163   unsigned int pagesPerVolume = 1;
1164   unsigned int volume = 0;
1165
1166   // if rulerX is enabled, then get page count (columns)
1167   page = mRulerX->GetPageFromPosition(-position.x, mWrapMode);
1168   volume = mRulerY->GetPageFromPosition(-position.y, mWrapMode);
1169   pagesPerVolume = mRulerX->GetTotalPages();
1170
1171   return volume * pagesPerVolume + page;
1172 }
1173
1174 Vector2 ScrollView::GetCurrentScrollPosition() const
1175 {
1176   return -GetPropertyPosition();
1177 }
1178
1179 void ScrollView::TransformTo(const Vector2& position,
1180                              DirectionBias horizontalBias, DirectionBias verticalBias)
1181 {
1182   TransformTo(position, mSnapDuration, mSnapAlphaFunction, horizontalBias, verticalBias);
1183 }
1184
1185 void ScrollView::TransformTo(const Vector2& position, float duration, AlphaFunction alpha,
1186                              DirectionBias horizontalBias, DirectionBias verticalBias)
1187 {
1188   // If this is called while the timer is running, then cancel it
1189   StopTouchDownTimer();
1190
1191   Actor self( Self() );
1192
1193   // Guard against destruction during signal emission
1194   // Note that Emit() methods are called indirectly e.g. from within ScrollView::AnimateTo()
1195   Toolkit::ScrollView handle( GetOwner() );
1196
1197   DALI_LOG_SCROLL_STATE("[0x%X] pos[%.2f,%.2f], duration[%.2f] bias[%d, %d]",
1198     this, position.x, position.y, duration, int(horizontalBias), int(verticalBias));
1199
1200   Vector2 currentScrollPosition = GetCurrentScrollPosition();
1201   self.SetProperty( Toolkit::ScrollView::Property::START_PAGE_POSITION, Vector3(currentScrollPosition) );
1202
1203   if( mScrolling ) // are we interrupting a current scroll?
1204   {
1205     // set mScrolling to false, in case user has code that interrogates mScrolling Getter() in complete.
1206     mScrolling = false;
1207     DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignal 1 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
1208     mScrollCompletedSignal.Emit( currentScrollPosition );
1209   }
1210
1211   if( mPanning ) // are we interrupting a current pan?
1212   {
1213     DALI_LOG_SCROLL_STATE("[0x%X] Interrupting Pan, set to false", this );
1214     mPanning = false;
1215     mGestureStackDepth = 0;
1216     self.SetProperty( Toolkit::ScrollView::Property::PANNING, false );
1217
1218     if( mScrollMainInternalPrePositionConstraint )
1219     {
1220       mScrollMainInternalPrePositionConstraint.Remove();
1221     }
1222   }
1223
1224   self.SetProperty(Toolkit::ScrollView::Property::SCROLLING, true);
1225   mScrolling = true;
1226
1227   DALI_LOG_SCROLL_STATE("[0x%X] mScrollStartedSignal 1 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
1228   mScrollStartedSignal.Emit( currentScrollPosition );
1229   bool animating = AnimateTo(-position,
1230                              Vector2::ONE * duration,
1231                              alpha,
1232                              true,
1233                              horizontalBias,
1234                              verticalBias,
1235                              Snap);
1236
1237   if(!animating)
1238   {
1239     // if not animating, then this pan has completed right now.
1240     self.SetProperty(Toolkit::ScrollView::Property::SCROLLING, false);
1241     mScrolling = false;
1242
1243     // If we have no duration, then in the next update frame, we will be at the position specified as we just set.
1244     // In this scenario, we cannot return the currentScrollPosition as this is out-of-date and should instead return the requested final position
1245     Vector2 completedPosition( currentScrollPosition );
1246     if( duration <= Math::MACHINE_EPSILON_10 )
1247     {
1248       completedPosition = position;
1249     }
1250
1251     DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignal 2 [%.2f, %.2f]", this, completedPosition.x, completedPosition.y);
1252     SetScrollUpdateNotification(false);
1253     mScrollCompletedSignal.Emit( completedPosition );
1254   }
1255 }
1256
1257 void ScrollView::ScrollTo(const Vector2& position)
1258 {
1259   ScrollTo(position, mSnapDuration );
1260 }
1261
1262 void ScrollView::ScrollTo(const Vector2& position, float duration)
1263 {
1264   ScrollTo(position, duration, DirectionBiasNone, DirectionBiasNone);
1265 }
1266
1267 void ScrollView::ScrollTo(const Vector2& position, float duration, AlphaFunction alpha)
1268 {
1269   ScrollTo(position, duration, alpha, DirectionBiasNone, DirectionBiasNone);
1270 }
1271
1272 void ScrollView::ScrollTo(const Vector2& position, float duration,
1273                           DirectionBias horizontalBias, DirectionBias verticalBias)
1274 {
1275   ScrollTo(position, duration, mSnapAlphaFunction, horizontalBias, verticalBias);
1276 }
1277
1278 void ScrollView::ScrollTo(const Vector2& position, float duration, AlphaFunction alpha,
1279                 DirectionBias horizontalBias, DirectionBias verticalBias)
1280 {
1281   DALI_LOG_SCROLL_STATE("[0x%X] position[%.2f, %.2f] duration[%.2f], bias[%d, %d]", this, position.x, position.y, duration, int(horizontalBias), int(verticalBias));
1282   TransformTo(position, duration, alpha, horizontalBias, verticalBias);
1283 }
1284
1285 void ScrollView::ScrollTo(unsigned int page)
1286 {
1287   ScrollTo(page, mSnapDuration);
1288 }
1289
1290 void ScrollView::ScrollTo(unsigned int page, float duration, DirectionBias bias)
1291 {
1292   Vector2 position;
1293   unsigned int volume;
1294   unsigned int libraries;
1295
1296   // The position to scroll to is continuous and linear
1297   // unless a domain has been enabled on the X axis.
1298   // or if WrapMode has been enabled.
1299   bool carryX = mRulerX->GetDomain().enabled | mWrapMode;
1300   bool carryY = mRulerY->GetDomain().enabled | mWrapMode;
1301
1302   position.x = mRulerX->GetPositionFromPage(page, volume, carryX);
1303   position.y = mRulerY->GetPositionFromPage(volume, libraries, carryY);
1304
1305   ScrollTo(position, duration, bias, bias);
1306 }
1307
1308 void ScrollView::ScrollTo(Actor &actor)
1309 {
1310   ScrollTo(actor, mSnapDuration);
1311 }
1312
1313 void ScrollView::ScrollTo(Actor &actor, float duration)
1314 {
1315   DALI_ASSERT_ALWAYS(actor.GetParent() == Self());
1316
1317   Actor self = Self();
1318   Vector3 size = self.GetCurrentSize();
1319   Vector3 position = actor.GetCurrentPosition();
1320   Vector2 prePosition = GetPropertyPrePosition();
1321   position.GetVectorXY() -= prePosition;
1322
1323   ScrollTo(Vector2(position.x - size.width * 0.5f, position.y - size.height * 0.5f), duration);
1324 }
1325
1326 Actor ScrollView::FindClosestActor()
1327 {
1328   Actor self = Self();
1329   Vector3 size = self.GetCurrentSize();
1330
1331   return FindClosestActorToPosition(Vector3(size.width * 0.5f,size.height * 0.5f,0.0f));
1332 }
1333
1334 Actor ScrollView::FindClosestActorToPosition(const Vector3& position, FindDirection dirX, FindDirection dirY, FindDirection dirZ)
1335 {
1336   Actor closestChild;
1337   float closestDistance2 = 0.0f;
1338   Vector3 actualPosition = position;
1339
1340   unsigned int numChildren = Self().GetChildCount();
1341
1342   for(unsigned int i = 0; i < numChildren; ++i)
1343   {
1344     Actor child = Self().GetChildAt(i);
1345
1346     if(mInternalActor == child) // ignore internal actor.
1347     {
1348       continue;
1349     }
1350
1351     Vector3 childPosition = GetPositionOfAnchor(child, AnchorPoint::CENTER);
1352
1353     Vector3 delta = childPosition - actualPosition;
1354
1355     // X-axis checking (only find Actors to the [dirX] of actualPosition)
1356     if(dirX > All) // != All,None
1357     {
1358       FindDirection deltaH = delta.x > 0 ? Right : Left;
1359       if(dirX != deltaH)
1360       {
1361         continue;
1362       }
1363     }
1364
1365     // Y-axis checking (only find Actors to the [dirY] of actualPosition)
1366     if(dirY > All) // != All,None
1367     {
1368       FindDirection deltaV = delta.y > 0 ? Down : Up;
1369       if(dirY  != deltaV)
1370       {
1371         continue;
1372       }
1373     }
1374
1375     // Z-axis checking (only find Actors to the [dirZ] of actualPosition)
1376     if(dirZ > All) // != All,None
1377     {
1378       FindDirection deltaV = delta.y > 0 ? In : Out;
1379       if(dirZ  != deltaV)
1380       {
1381         continue;
1382       }
1383     }
1384
1385     // compare child to closest child in terms of distance.
1386     float distance2 = 0.0f;
1387
1388     // distance2 = the Square of the relevant dimensions of delta
1389     if(dirX != None)
1390     {
1391       distance2 += delta.x * delta.x;
1392     }
1393
1394     if(dirY != None)
1395     {
1396       distance2 += delta.y * delta.y;
1397     }
1398
1399     if(dirZ != None)
1400     {
1401       distance2 += delta.z * delta.z;
1402     }
1403
1404     if(closestChild) // Next time.
1405     {
1406       if(distance2 < closestDistance2)
1407       {
1408         closestChild = child;
1409         closestDistance2 = distance2;
1410       }
1411     }
1412     else // First time.
1413     {
1414       closestChild = child;
1415       closestDistance2 = distance2;
1416     }
1417   }
1418
1419   return closestChild;
1420 }
1421
1422 bool ScrollView::ScrollToSnapPoint()
1423 {
1424   DALI_LOG_SCROLL_STATE("[0x%X]", this );
1425   Vector2 stationaryVelocity = Vector2(0.0f, 0.0f);
1426   return SnapWithVelocity( stationaryVelocity );
1427 }
1428
1429 // TODO: In situations where axes are different (X snap, Y free)
1430 // Each axis should really have their own independent animation (time and equation)
1431 // Consider, X axis snapping to nearest grid point (EaseOut over fixed time)
1432 // Consider, Y axis simulating physics to arrive at a point (Physics equation over variable time)
1433 // Currently, the axes have been split however, they both use the same EaseOut equation.
1434 bool ScrollView::SnapWithVelocity(Vector2 velocity)
1435 {
1436   // Animator takes over now, touches are assumed not to interfere.
1437   // And if touches do interfere, then we'll stop animation, update PrePosition
1438   // to current mScroll's properties, and then resume.
1439   // Note: For Flicking this may work a bit different...
1440
1441   float angle = atan2(velocity.y, velocity.x);
1442   float speed2 = velocity.LengthSquared();
1443   AlphaFunction alphaFunction = mSnapAlphaFunction;
1444   Vector2 positionDuration = Vector2::ONE * mSnapDuration;
1445   float biasX = 0.5f;
1446   float biasY = 0.5f;
1447   FindDirection horizontal = None;
1448   FindDirection vertical = None;
1449
1450   // orthoAngleRange = Angle tolerance within the Exact N,E,S,W direction
1451   // that will be accepted as a general N,E,S,W flick direction.
1452
1453   const float orthoAngleRange = FLICK_ORTHO_ANGLE_RANGE * M_PI / 180.0f;
1454   const float flickSpeedThreshold2 = mFlickSpeedThreshold * mFlickSpeedThreshold;
1455
1456   Vector2 positionSnap = mScrollPrePosition;
1457
1458   // Flick logic X Axis
1459
1460   if(mRulerX->IsEnabled() && mLockAxis != LockHorizontal)
1461   {
1462     horizontal = All;
1463
1464     if( speed2 > flickSpeedThreshold2 || // exceeds flick threshold
1465         mInAccessibilityPan ) // With AccessibilityPan its easier to move between snap positions
1466     {
1467       if((angle >= -orthoAngleRange) && (angle < orthoAngleRange)) // Swiping East
1468       {
1469         biasX = 0.0f, horizontal = Left;
1470
1471         // This guards against an error where no movement occurs, due to the flick finishing
1472         // before the update-thread has advanced mScrollPostPosition past the the previous snap point.
1473         positionSnap.x += 1.0f;
1474       }
1475       else if((angle >= M_PI-orthoAngleRange) || (angle < -M_PI+orthoAngleRange)) // Swiping West
1476       {
1477         biasX = 1.0f, horizontal = Right;
1478
1479         // This guards against an error where no movement occurs, due to the flick finishing
1480         // before the update-thread has advanced mScrollPostPosition past the the previous snap point.
1481         positionSnap.x -= 1.0f;
1482       }
1483     }
1484   }
1485
1486   // Flick logic Y Axis
1487
1488   if(mRulerY->IsEnabled() && mLockAxis != LockVertical)
1489   {
1490     vertical = All;
1491
1492     if( speed2 > flickSpeedThreshold2 || // exceeds flick threshold
1493         mInAccessibilityPan ) // With AccessibilityPan its easier to move between snap positions
1494     {
1495       if((angle >= M_PI_2-orthoAngleRange) && (angle < M_PI_2+orthoAngleRange)) // Swiping South
1496       {
1497         biasY = 0.0f, vertical = Up;
1498       }
1499       else if((angle >= -M_PI_2-orthoAngleRange) && (angle < -M_PI_2+orthoAngleRange)) // Swiping North
1500       {
1501         biasY = 1.0f, vertical = Down;
1502       }
1503     }
1504   }
1505
1506   // isFlick: Whether this gesture is a flick or not.
1507   bool isFlick = (horizontal != All || vertical != All);
1508   // isFreeFlick: Whether this gesture is a flick under free panning criteria.
1509   bool isFreeFlick = velocity.LengthSquared() > (FREE_FLICK_SPEED_THRESHOLD*FREE_FLICK_SPEED_THRESHOLD);
1510
1511   if(isFlick || isFreeFlick)
1512   {
1513     positionDuration = Vector2::ONE * mFlickDuration;
1514     alphaFunction = mFlickAlphaFunction;
1515   }
1516
1517   // Calculate next positionSnap ////////////////////////////////////////////////////////////
1518
1519   if(mActorAutoSnapEnabled)
1520   {
1521     Vector3 size = Self().GetCurrentSize();
1522
1523     Actor child = FindClosestActorToPosition( Vector3(size.width * 0.5f,size.height * 0.5f,0.0f), horizontal, vertical );
1524
1525     if(!child && isFlick )
1526     {
1527       // If we conducted a direction limited search and found no actor, then just snap to the closest actor.
1528       child = FindClosestActorToPosition( Vector3(size.width * 0.5f,size.height * 0.5f,0.0f) );
1529     }
1530
1531     if(child)
1532     {
1533       Vector2 position = Self().GetProperty<Vector2>(Toolkit::ScrollView::Property::SCROLL_POSITION);
1534
1535       // Get center-point of the Actor.
1536       Vector3 childPosition = GetPositionOfAnchor(child, AnchorPoint::CENTER);
1537
1538       if(mRulerX->IsEnabled())
1539       {
1540         positionSnap.x = position.x - childPosition.x + size.width * 0.5f;
1541       }
1542       if(mRulerY->IsEnabled())
1543       {
1544         positionSnap.y = position.y - childPosition.y + size.height * 0.5f;
1545       }
1546     }
1547   }
1548
1549   Vector2 startPosition = positionSnap;
1550   positionSnap.x = -mRulerX->Snap(-positionSnap.x, biasX);  // NOTE: X & Y rulers think in -ve coordinate system.
1551   positionSnap.y = -mRulerY->Snap(-positionSnap.y, biasY);  // That is scrolling RIGHT (e.g. 100.0, 0.0) means moving LEFT.
1552
1553   Vector2 clampDelta(Vector2::ZERO);
1554   ClampPosition(positionSnap);
1555
1556   if( (mRulerX->GetType() == Ruler::Free || mRulerY->GetType() == Ruler::Free)
1557       && isFreeFlick && !mActorAutoSnapEnabled)
1558   {
1559     // Calculate target position based on velocity of flick.
1560
1561     // a = Deceleration (Set to diagonal stage length * friction coefficient)
1562     // u = Initial Velocity (Flick velocity)
1563     // v = 0 (Final Velocity)
1564     // t = Time (Velocity / Deceleration)
1565     Vector2 stageSize = Stage::GetCurrent().GetSize();
1566     float stageLength = Vector3(stageSize.x, stageSize.y, 0.0f).Length();
1567     float a = (stageLength * mFrictionCoefficient);
1568     Vector3 u = Vector3(velocity.x, velocity.y, 0.0f) * mFlickSpeedCoefficient;
1569     float speed = u.Length();
1570     u/= speed;
1571
1572     // TODO: Change this to a decay function. (faster you flick, the slower it should be)
1573     speed = std::min(speed, stageLength * mMaxFlickSpeed );
1574     u*= speed;
1575     alphaFunction = ConstantDecelerationAlphaFunction;
1576
1577     float t = speed / a;
1578
1579     if(mRulerX->IsEnabled() && mRulerX->GetType() == Ruler::Free)
1580     {
1581       positionSnap.x += t*u.x*0.5f;
1582     }
1583
1584     if(mRulerY->IsEnabled() && mRulerY->GetType() == Ruler::Free)
1585     {
1586       positionSnap.y += t*u.y*0.5f;
1587     }
1588
1589     clampDelta = positionSnap;
1590     ClampPosition(positionSnap);
1591     if((positionSnap - startPosition).LengthSquared() > Math::MACHINE_EPSILON_0)
1592     {
1593       clampDelta -= positionSnap;
1594       clampDelta.x = clampDelta.x > 0.0f ? std::min(clampDelta.x, mMaxOvershoot.x) : std::max(clampDelta.x, -mMaxOvershoot.x);
1595       clampDelta.y = clampDelta.y > 0.0f ? std::min(clampDelta.y, mMaxOvershoot.y) : std::max(clampDelta.y, -mMaxOvershoot.y);
1596     }
1597     else
1598     {
1599       clampDelta = Vector2::ZERO;
1600     }
1601
1602     // If Axis is Free and has velocity, then calculate time taken
1603     // to reach target based on velocity in axis.
1604     if(mRulerX->IsEnabled() && mRulerX->GetType() == Ruler::Free)
1605     {
1606       float deltaX = fabsf(startPosition.x - positionSnap.x);
1607
1608       if(fabsf(u.x) > Math::MACHINE_EPSILON_1)
1609       {
1610         positionDuration.x = fabsf(deltaX / u.x);
1611       }
1612       else
1613       {
1614         positionDuration.x = 0;
1615       }
1616     }
1617
1618     if(mRulerY->IsEnabled() && mRulerY->GetType() == Ruler::Free)
1619     {
1620       float deltaY = fabsf(startPosition.y - positionSnap.y);
1621
1622       if(fabsf(u.y) > Math::MACHINE_EPSILON_1)
1623       {
1624         positionDuration.y = fabsf(deltaY / u.y);
1625       }
1626       else
1627       {
1628         positionDuration.y = 0;
1629       }
1630     }
1631   }
1632
1633   if(IsOvershootEnabled())
1634   {
1635     // Scroll to the end of the overshoot only when overshoot is enabled.
1636     positionSnap += clampDelta;
1637   }
1638
1639   bool animating = AnimateTo(positionSnap, positionDuration,
1640                              alphaFunction, false,
1641                              DirectionBiasNone, DirectionBiasNone,
1642                              isFlick || isFreeFlick ? Flick : Snap);
1643
1644   return animating;
1645 }
1646
1647 void ScrollView::StopAnimation(void)
1648 {
1649   // Clear Snap animation if exists.
1650   StopAnimation(mInternalXAnimation);
1651   StopAnimation(mInternalYAnimation);
1652   mScrollStateFlags = 0;
1653   // remove scroll animation flags
1654   HandleStoppedAnimation();
1655 }
1656
1657 void ScrollView::StopAnimation(Animation& animation)
1658 {
1659   if(animation)
1660   {
1661     animation.Stop();
1662     animation.Reset();
1663   }
1664 }
1665
1666 bool ScrollView::AnimateTo(const Vector2& position, const Vector2& positionDuration,
1667                            AlphaFunction alpha, bool findShortcuts,
1668                            DirectionBias horizontalBias, DirectionBias verticalBias,
1669                            SnapType snapType)
1670 {
1671   // Here we perform an animation on a number of properties (depending on which have changed)
1672   // The animation is applied to all ScrollBases
1673   Actor self = Self();
1674   mScrollTargetPosition = position;
1675   float totalDuration = 0.0f;
1676
1677   bool positionChanged = (mScrollTargetPosition != mScrollPostPosition);
1678
1679   if(positionChanged)
1680   {
1681     totalDuration = std::max(totalDuration, positionDuration.x);
1682     totalDuration = std::max(totalDuration, positionDuration.y);
1683   }
1684   else
1685   {
1686     // try to animate for a frame, on some occasions update will be changing scroll value while event side thinks it hasnt changed
1687     totalDuration = 0.01f;
1688     positionChanged = true;
1689   }
1690
1691   StopAnimation();
1692
1693   // Position Delta ///////////////////////////////////////////////////////
1694   if(positionChanged)
1695   {
1696     UpdateMainInternalConstraint();
1697     if(mWrapMode && findShortcuts)
1698     {
1699       // In Wrap Mode, the shortest distance is a little less intuitive...
1700       const RulerDomain rulerDomainX = mRulerX->GetDomain();
1701       const RulerDomain rulerDomainY = mRulerY->GetDomain();
1702
1703       if(mRulerX->IsEnabled())
1704       {
1705         float dir = VectorInDomain(-mScrollPrePosition.x, -mScrollTargetPosition.x, rulerDomainX.min, rulerDomainX.max, horizontalBias);
1706         mScrollTargetPosition.x = mScrollPrePosition.x + -dir;
1707       }
1708
1709       if(mRulerY->IsEnabled())
1710       {
1711         float dir = VectorInDomain(-mScrollPrePosition.y, -mScrollTargetPosition.y, rulerDomainY.min, rulerDomainY.max, verticalBias);
1712         mScrollTargetPosition.y = mScrollPrePosition.y + -dir;
1713       }
1714     }
1715
1716     // note we have two separate animations for X & Y, this deals with sliding diagonally and hitting
1717     // a horizonal/vertical wall.delay
1718     AnimateInternalXTo(mScrollTargetPosition.x, positionDuration.x, alpha);
1719     AnimateInternalYTo(mScrollTargetPosition.y, positionDuration.y, alpha);
1720
1721     if( !(mScrollStateFlags & SCROLL_ANIMATION_FLAGS) )
1722     {
1723       DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollTargetPosition.x, mScrollTargetPosition.y );
1724       self.SetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, mScrollTargetPosition);
1725       mScrollPrePosition = mScrollTargetPosition;
1726       mScrollPostPosition = mScrollTargetPosition;
1727       WrapPosition(mScrollPostPosition);
1728     }
1729
1730     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 );
1731     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 );
1732   }
1733
1734   SetScrollUpdateNotification(true);
1735
1736   // Always send a snap event when AnimateTo is called.
1737   Toolkit::ScrollView::SnapEvent snapEvent;
1738   snapEvent.type = snapType;
1739   snapEvent.position = -mScrollTargetPosition;
1740   snapEvent.duration = totalDuration;
1741
1742   DALI_LOG_SCROLL_STATE("[0x%X] mSnapStartedSignal [%.2f, %.2f]", this, snapEvent.position.x, snapEvent.position.y);
1743   mSnapStartedSignal.Emit( snapEvent );
1744
1745   return (mScrollStateFlags & SCROLL_ANIMATION_FLAGS) != 0;
1746 }
1747
1748 void ScrollView::EnableScrollOvershoot(bool enable)
1749 {
1750   if (enable)
1751   {
1752     if (!mOvershootIndicator)
1753     {
1754       mOvershootIndicator = ScrollOvershootIndicator::New();
1755     }
1756
1757     mOvershootIndicator->AttachToScrollable(*this);
1758   }
1759   else
1760   {
1761     mMaxOvershoot = mUserMaxOvershoot;
1762
1763     if (mOvershootIndicator)
1764     {
1765       mOvershootIndicator->DetachFromScrollable(*this);
1766     }
1767   }
1768
1769   UpdateMainInternalConstraint();
1770 }
1771
1772 void ScrollView::AddOverlay(Actor actor)
1773 {
1774   actor.SetDrawMode( DrawMode::OVERLAY_2D );
1775   mInternalActor.Add( actor );
1776 }
1777
1778 void ScrollView::RemoveOverlay(Actor actor)
1779 {
1780   mInternalActor.Remove( actor );
1781 }
1782
1783 void ScrollView::SetOvershootEffectColor( const Vector4& color )
1784 {
1785   mOvershootEffectColor = color;
1786   if( mOvershootIndicator )
1787   {
1788     mOvershootIndicator->SetOvershootEffectColor( color );
1789   }
1790 }
1791
1792 void ScrollView::SetScrollingDirection( Radian direction, Radian threshold )
1793 {
1794   PanGestureDetector panGesture( GetPanGestureDetector() );
1795
1796   // First remove just in case we have some set, then add.
1797   panGesture.RemoveDirection( direction );
1798   panGesture.AddDirection( direction, threshold );
1799 }
1800
1801 void ScrollView::RemoveScrollingDirection( Radian direction )
1802 {
1803   PanGestureDetector panGesture( GetPanGestureDetector() );
1804   panGesture.RemoveDirection( direction );
1805 }
1806
1807 Toolkit::ScrollView::SnapStartedSignalType& ScrollView::SnapStartedSignal()
1808 {
1809   return mSnapStartedSignal;
1810 }
1811
1812 void ScrollView::FindAndUnbindActor(Actor child)
1813 {
1814   UnbindActor(child);
1815 }
1816
1817 Vector2 ScrollView::GetPropertyPrePosition() const
1818 {
1819   Vector2 position = Self().GetProperty<Vector2>(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION);
1820   WrapPosition(position);
1821   return position;
1822 }
1823
1824 Vector2 ScrollView::GetPropertyPosition() const
1825 {
1826   Vector2 position = Self().GetProperty<Vector2>(Toolkit::ScrollView::Property::SCROLL_POSITION);
1827   WrapPosition(position);
1828
1829   return position;
1830 }
1831
1832 void ScrollView::HandleStoppedAnimation()
1833 {
1834   SetScrollUpdateNotification(false);
1835 }
1836
1837 void ScrollView::HandleSnapAnimationFinished()
1838 {
1839   // Emit Signal that scrolling has completed.
1840   mScrolling = false;
1841   Actor self = Self();
1842   self.SetProperty(Toolkit::ScrollView::Property::SCROLLING, false);
1843
1844   Vector2 deltaPosition(mScrollPrePosition);
1845
1846   UpdateLocalScrollProperties();
1847   WrapPosition(mScrollPrePosition);
1848   DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y );
1849   self.SetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, mScrollPrePosition);
1850
1851   Vector2 currentScrollPosition = GetCurrentScrollPosition();
1852   DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignal 3 current[%.2f, %.2f], mScrollTargetPosition[%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y, -mScrollTargetPosition.x, -mScrollTargetPosition.y );
1853   mScrollCompletedSignal.Emit( currentScrollPosition );
1854
1855   mDomainOffset += deltaPosition - mScrollPostPosition;
1856   self.SetProperty(Toolkit::ScrollView::Property::SCROLL_DOMAIN_OFFSET, mDomainOffset);
1857   HandleStoppedAnimation();
1858 }
1859
1860 void ScrollView::SetScrollUpdateNotification( bool enabled )
1861 {
1862   Actor self = Self();
1863   if( mScrollXUpdateNotification )
1864   {
1865     // disconnect now to avoid a notification before removed from update thread
1866     mScrollXUpdateNotification.NotifySignal().Disconnect(this, &ScrollView::OnScrollUpdateNotification);
1867     self.RemovePropertyNotification(mScrollXUpdateNotification);
1868     mScrollXUpdateNotification.Reset();
1869   }
1870   if( enabled && !mScrollUpdatedSignal.Empty())
1871   {
1872     // Only set up the notification when the application has connected to the updated signal
1873     mScrollXUpdateNotification = self.AddPropertyNotification(Toolkit::ScrollView::Property::SCROLL_POSITION, 0, StepCondition(mScrollUpdateDistance, 0.0f));
1874     mScrollXUpdateNotification.NotifySignal().Connect( this, &ScrollView::OnScrollUpdateNotification );
1875   }
1876   if( mScrollYUpdateNotification )
1877   {
1878     // disconnect now to avoid a notification before removed from update thread
1879     mScrollYUpdateNotification.NotifySignal().Disconnect(this, &ScrollView::OnScrollUpdateNotification);
1880     self.RemovePropertyNotification(mScrollYUpdateNotification);
1881     mScrollYUpdateNotification.Reset();
1882   }
1883   if( enabled && !mScrollUpdatedSignal.Empty())
1884   {
1885     // Only set up the notification when the application has connected to the updated signal
1886     mScrollYUpdateNotification = self.AddPropertyNotification(Toolkit::ScrollView::Property::SCROLL_POSITION, 1, StepCondition(mScrollUpdateDistance, 0.0f));
1887     mScrollYUpdateNotification.NotifySignal().Connect( this, &ScrollView::OnScrollUpdateNotification );
1888   }
1889 }
1890
1891 void ScrollView::OnScrollUpdateNotification(Dali::PropertyNotification& source)
1892 {
1893   // Guard against destruction during signal emission
1894   Toolkit::ScrollView handle( GetOwner() );
1895
1896   Vector2 currentScrollPosition = GetCurrentScrollPosition();
1897   mScrollUpdatedSignal.Emit( currentScrollPosition );
1898 }
1899
1900 bool ScrollView::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
1901 {
1902   Dali::BaseHandle handle( object );
1903
1904   bool connected( true );
1905   Toolkit::ScrollView view = Toolkit::ScrollView::DownCast( handle );
1906
1907   if( 0 == strcmp( signalName.c_str(), SIGNAL_SNAP_STARTED ) )
1908   {
1909     view.SnapStartedSignal().Connect( tracker, functor );
1910   }
1911   else
1912   {
1913     // signalName does not match any signal
1914     connected = false;
1915   }
1916
1917   return connected;
1918 }
1919
1920 void ScrollView::OnSizeAnimation(Animation& animation, const Vector3& targetSize)
1921 {
1922   // need to update domain properties for new size
1923   UpdatePropertyDomain();
1924 }
1925
1926 void ScrollView::OnSizeSet( const Vector3& size )
1927 {
1928   // need to update domain properties for new size
1929   if( mDefaultMaxOvershoot )
1930   {
1931     mUserMaxOvershoot.x = size.x * 0.5f;
1932     mUserMaxOvershoot.y = size.y * 0.5f;
1933     if( !IsOvershootEnabled() )
1934     {
1935       mMaxOvershoot = mUserMaxOvershoot;
1936     }
1937   }
1938   UpdatePropertyDomain();
1939   UpdateMainInternalConstraint();
1940   if( IsOvershootEnabled() )
1941   {
1942     mOvershootIndicator->Reset();
1943   }
1944 }
1945
1946 void ScrollView::OnChildAdd(Actor& child)
1947 {
1948   ScrollBase::OnChildAdd( child );
1949
1950   Dali::Toolkit::ScrollBar scrollBar = Dali::Toolkit::ScrollBar::DownCast(child);
1951   if(scrollBar)
1952   {
1953     mInternalActor.Add(scrollBar);
1954     if(scrollBar.GetScrollDirection() == Toolkit::ScrollBar::Horizontal)
1955     {
1956       scrollBar.SetScrollPropertySource(Self(),
1957                                         Toolkit::ScrollView::Property::SCROLL_PRE_POSITION_X,
1958                                         Toolkit::Scrollable::Property::SCROLL_POSITION_MIN_X,
1959                                         Toolkit::ScrollView::Property::SCROLL_PRE_POSITION_MAX_X,
1960                                         Toolkit::ScrollView::Property::SCROLL_DOMAIN_SIZE_X);
1961     }
1962     else
1963     {
1964       scrollBar.SetScrollPropertySource(Self(),
1965                                         Toolkit::ScrollView::Property::SCROLL_PRE_POSITION_Y,
1966                                         Toolkit::Scrollable::Property::SCROLL_POSITION_MIN_Y,
1967                                         Toolkit::ScrollView::Property::SCROLL_PRE_POSITION_MAX_Y,
1968                                         Toolkit::ScrollView::Property::SCROLL_DOMAIN_SIZE_Y);
1969     }
1970   }
1971   else if(mAlterChild)
1972   {
1973     BindActor(child);
1974   }
1975 }
1976
1977 void ScrollView::OnChildRemove(Actor& child)
1978 {
1979   // TODO: Actor needs a RemoveConstraint method to take out an individual constraint.
1980   UnbindActor(child);
1981
1982   ScrollBase::OnChildRemove( child );
1983 }
1984
1985 void ScrollView::StartTouchDownTimer()
1986 {
1987   if ( !mTouchDownTimer )
1988   {
1989     mTouchDownTimer = Timer::New( TOUCH_DOWN_TIMER_INTERVAL );
1990     mTouchDownTimer.TickSignal().Connect( this, &ScrollView::OnTouchDownTimeout );
1991   }
1992
1993   mTouchDownTimer.Start();
1994 }
1995
1996 void ScrollView::StopTouchDownTimer()
1997 {
1998   if ( mTouchDownTimer )
1999   {
2000     mTouchDownTimer.Stop();
2001   }
2002 }
2003
2004 bool ScrollView::OnTouchDownTimeout()
2005 {
2006   DALI_LOG_SCROLL_STATE("[0x%X]", this);
2007
2008   mTouchDownTimeoutReached = true;
2009
2010   unsigned int currentScrollStateFlags( mScrollStateFlags ); // Cleared in StopAnimation so keep local copy for comparison
2011   if( currentScrollStateFlags & (SCROLL_ANIMATION_FLAGS | SNAP_ANIMATION_FLAGS) )
2012   {
2013     DALI_LOG_SCROLL_STATE("[0x%X] Scrolling Or snapping flags set, stopping animation", this);
2014
2015     StopAnimation();
2016     if( currentScrollStateFlags & SCROLL_ANIMATION_FLAGS )
2017     {
2018       DALI_LOG_SCROLL_STATE("[0x%X] Scrolling flags set, emitting signal", this);
2019
2020       mScrollInterrupted = true;
2021       // reset domain offset as scrolling from original plane.
2022       mDomainOffset = Vector2::ZERO;
2023       Self().SetProperty(Toolkit::ScrollView::Property::SCROLL_DOMAIN_OFFSET, Vector2::ZERO);
2024
2025       UpdateLocalScrollProperties();
2026       Vector2 currentScrollPosition = GetCurrentScrollPosition();
2027       DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignal 4 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
2028       mScrollCompletedSignal.Emit( currentScrollPosition );
2029     }
2030   }
2031
2032   return false;
2033 }
2034
2035 bool ScrollView::OnTouch( Actor actor, const TouchData& touch )
2036 {
2037   if(!mSensitive)
2038   {
2039     DALI_LOG_SCROLL_STATE("[0x%X], Not Sensitive, ignoring", this);
2040
2041     // Ignore this touch event, if scrollview is insensitive.
2042     return false;
2043   }
2044
2045   // Ignore events with multiple-touch points
2046   if (touch.GetPointCount() != 1)
2047   {
2048     DALI_LOG_SCROLL_STATE("[0x%X], multiple touch, ignoring", this);
2049
2050     return false;
2051   }
2052
2053   const PointState::Type pointState = touch.GetState( 0 );
2054   if( pointState == PointState::DOWN )
2055   {
2056     DALI_LOG_SCROLL_STATE("[0x%X] Down", this);
2057
2058     if(mGestureStackDepth==0)
2059     {
2060       mTouchDownTime = touch.GetTime();
2061
2062       // This allows time for a pan-gesture to start, to avoid breaking snap-animation behavior with fast flicks.
2063       // If touch-down does not become a pan (after timeout interval), then snap-animation can be interrupted.
2064       mTouchDownTimeoutReached = false;
2065       mScrollInterrupted = false;
2066       StartTouchDownTimer();
2067     }
2068   }
2069   else if( ( pointState == PointState::UP ) ||
2070            ( ( pointState == PointState::INTERRUPTED ) && ( touch.GetHitActor( 0 )== Self() ) ) )
2071   {
2072     DALI_LOG_SCROLL_STATE("[0x%X] %s", this, ( ( pointState == TouchPoint::Up ) ? "Up" : "Interrupted" ) );
2073
2074     StopTouchDownTimer();
2075
2076     // if the user touches and releases without enough movement to go
2077     // into a gesture state, then we should snap to nearest point.
2078     // otherwise our scroll could be stopped (interrupted) half way through an animation.
2079     if(mGestureStackDepth==0 && mTouchDownTimeoutReached)
2080     {
2081       if( ( pointState == PointState::INTERRUPTED ) ||
2082           ( ( touch.GetTime() - mTouchDownTime ) >= MINIMUM_TIME_BETWEEN_DOWN_AND_UP_FOR_RESET ) )
2083       {
2084         // Reset the velocity only if down was received a while ago
2085         mLastVelocity = Vector2( 0.0f, 0.0f );
2086       }
2087
2088       UpdateLocalScrollProperties();
2089       // Only finish the transform if scrolling was interrupted on down or if we are scrolling
2090       if ( mScrollInterrupted || mScrolling )
2091       {
2092         DALI_LOG_SCROLL_STATE("[0x%X] Calling FinishTransform", this);
2093
2094         FinishTransform();
2095       }
2096     }
2097     mTouchDownTimeoutReached = false;
2098     mScrollInterrupted = false;
2099   }
2100
2101   return true;
2102 }
2103
2104 bool ScrollView::OnWheelEvent(const WheelEvent& event)
2105 {
2106   if(!mSensitive)
2107   {
2108     // Ignore this wheel event, if scrollview is insensitive.
2109     return false;
2110   }
2111
2112   Vector2 targetScrollPosition = GetPropertyPosition();
2113
2114   if(mRulerX->IsEnabled() && !mRulerY->IsEnabled())
2115   {
2116     // If only the ruler in the X axis is enabled, scroll in the X axis.
2117     if(mRulerX->GetType() == Ruler::Free)
2118     {
2119       // Free panning mode
2120       targetScrollPosition.x += event.z * mWheelScrollDistanceStep.x;
2121       ClampPosition(targetScrollPosition);
2122       ScrollTo(-targetScrollPosition);
2123     }
2124     else if(!mScrolling)
2125     {
2126       // Snap mode, only respond to the event when the previous snap animation is finished.
2127       ScrollTo(GetCurrentPage() - event.z);
2128     }
2129   }
2130   else
2131   {
2132     // If the ruler in the Y axis is enabled, scroll in the Y axis.
2133     if(mRulerY->GetType() == Ruler::Free)
2134     {
2135       // Free panning mode
2136       targetScrollPosition.y += event.z * mWheelScrollDistanceStep.y;
2137       ClampPosition(targetScrollPosition);
2138       ScrollTo(-targetScrollPosition);
2139     }
2140     else if(!mScrolling)
2141     {
2142       // Snap mode, only respond to the event when the previous snap animation is finished.
2143       ScrollTo(GetCurrentPage() - event.z * mRulerX->GetTotalPages());
2144     }
2145   }
2146
2147   return true;
2148 }
2149
2150 void ScrollView::ResetScrolling()
2151 {
2152   Actor self = Self();
2153   self.GetProperty(Toolkit::ScrollView::Property::SCROLL_POSITION).Get(mScrollPostPosition);
2154   mScrollPrePosition = mScrollPostPosition;
2155   DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPostPosition.x, mScrollPostPosition.y );
2156   self.SetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, mScrollPostPosition);
2157 }
2158
2159 void ScrollView::UpdateLocalScrollProperties()
2160 {
2161   Actor self = Self();
2162   self.GetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION).Get(mScrollPrePosition);
2163   self.GetProperty(Toolkit::ScrollView::Property::SCROLL_POSITION).Get(mScrollPostPosition);
2164 }
2165
2166 // private functions
2167
2168 void ScrollView::PreAnimatedScrollSetup()
2169 {
2170   // SCROLL_PRE_POSITION is our unclamped property with wrapping
2171   // SCROLL_POSITION is our final scroll position after clamping
2172
2173   Actor self = Self();
2174
2175   Vector2 deltaPosition(mScrollPostPosition);
2176   WrapPosition(mScrollPostPosition);
2177   mDomainOffset += deltaPosition - mScrollPostPosition;
2178   Self().SetProperty(Toolkit::ScrollView::Property::SCROLL_DOMAIN_OFFSET, mDomainOffset);
2179
2180   if( mScrollStateFlags & SCROLL_X_STATE_MASK )
2181   {
2182     // already performing animation on internal x position
2183     StopAnimation(mInternalXAnimation);
2184   }
2185
2186   if( mScrollStateFlags & SCROLL_Y_STATE_MASK )
2187   {
2188     // already performing animation on internal y position
2189     StopAnimation(mInternalYAnimation);
2190   }
2191
2192   mScrollStateFlags = 0;
2193
2194   // Update Actor position with this wrapped value.
2195 }
2196
2197 void ScrollView::FinaliseAnimatedScroll()
2198 {
2199   // TODO - common animation finishing code in here
2200 }
2201
2202 void ScrollView::AnimateInternalXTo( float position, float duration, AlphaFunction alpha )
2203 {
2204   StopAnimation(mInternalXAnimation);
2205
2206   if( duration > Math::MACHINE_EPSILON_10 )
2207   {
2208     Actor self = Self();
2209     DALI_LOG_SCROLL_STATE("[0x%X], Animating from[%.2f] to[%.2f]", this, self.GetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION).Get<Vector2>().x, position );
2210     mInternalXAnimation = Animation::New(duration);
2211     DALI_LOG_SCROLL_STATE("[0x%X], mInternalXAnimation[0x%X]", this, mInternalXAnimation.GetObjectPtr() );
2212     mInternalXAnimation.FinishedSignal().Connect(this, &ScrollView::OnScrollAnimationFinished);
2213     mInternalXAnimation.AnimateTo( Property(self, Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, 0), position, alpha, TimePeriod(duration));
2214     mInternalXAnimation.Play();
2215
2216     // erase current state flags
2217     mScrollStateFlags &= ~SCROLL_X_STATE_MASK;
2218     // add internal animation state flag
2219     mScrollStateFlags |= AnimatingInternalX;
2220   }
2221 }
2222
2223 void ScrollView::AnimateInternalYTo( float position, float duration, AlphaFunction alpha )
2224 {
2225   StopAnimation(mInternalYAnimation);
2226
2227   if( duration > Math::MACHINE_EPSILON_10 )
2228   {
2229     Actor self = Self();
2230     DALI_LOG_SCROLL_STATE("[0x%X], Animating from[%.2f] to[%.2f]", this, self.GetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION).Get<Vector2>().y, position );
2231     mInternalYAnimation = Animation::New(duration);
2232     DALI_LOG_SCROLL_STATE("[0x%X], mInternalYAnimation[0x%X]", this, mInternalYAnimation.GetObjectPtr() );
2233     mInternalYAnimation.FinishedSignal().Connect(this, &ScrollView::OnScrollAnimationFinished);
2234     mInternalYAnimation.AnimateTo( Property(self, Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, 1), position, alpha, TimePeriod(duration));
2235     mInternalYAnimation.Play();
2236
2237     // erase current state flags
2238     mScrollStateFlags &= ~SCROLL_Y_STATE_MASK;
2239     // add internal animation state flag
2240     mScrollStateFlags |= AnimatingInternalY;
2241   }
2242 }
2243
2244 void ScrollView::OnScrollAnimationFinished( Animation& source )
2245 {
2246   // Guard against destruction during signal emission
2247   // Note that ScrollCompletedSignal is emitted from HandleSnapAnimationFinished()
2248   Toolkit::ScrollView handle( GetOwner() );
2249
2250   bool scrollingFinished = false;
2251
2252   // update our local scroll positions
2253   UpdateLocalScrollProperties();
2254
2255   if( source == mInternalXAnimation )
2256   {
2257     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 );
2258
2259     if( !(mScrollStateFlags & AnimatingInternalY) )
2260     {
2261       scrollingFinished = true;
2262     }
2263     mInternalXAnimation.Reset();
2264     // wrap pre scroll x position and set it
2265     if( mWrapMode )
2266     {
2267       const RulerDomain rulerDomain = mRulerX->GetDomain();
2268       mScrollPrePosition.x = -WrapInDomain(-mScrollPrePosition.x, rulerDomain.min, rulerDomain.max);
2269       DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y );
2270       handle.SetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, mScrollPrePosition);
2271     }
2272     SnapInternalXTo(mScrollPostPosition.x);
2273   }
2274
2275   if( source == mInternalYAnimation )
2276   {
2277     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 );
2278
2279     if( !(mScrollStateFlags & AnimatingInternalX) )
2280     {
2281       scrollingFinished = true;
2282     }
2283     mInternalYAnimation.Reset();
2284     if( mWrapMode )
2285     {
2286       // wrap pre scroll y position and set it
2287       const RulerDomain rulerDomain = mRulerY->GetDomain();
2288       mScrollPrePosition.y = -WrapInDomain(-mScrollPrePosition.y, rulerDomain.min, rulerDomain.max);
2289       DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y );
2290       handle.SetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, mScrollPrePosition);
2291     }
2292     SnapInternalYTo(mScrollPostPosition.y);
2293   }
2294
2295   DALI_LOG_SCROLL_STATE("[0x%X] scrollingFinished[%d] Animation[0x%X]", this, scrollingFinished, source.GetObjectPtr());
2296
2297   if(scrollingFinished)
2298   {
2299     HandleSnapAnimationFinished();
2300   }
2301 }
2302
2303 void ScrollView::OnSnapInternalPositionFinished( Animation& source )
2304 {
2305   Actor self = Self();
2306   UpdateLocalScrollProperties();
2307   if( source == mInternalXAnimation )
2308   {
2309     DALI_LOG_SCROLL_STATE("[0x%X] Finished X PostPosition Animation", this );
2310
2311     // clear internal x animation flags
2312     mScrollStateFlags &= ~SCROLL_X_STATE_MASK;
2313     mInternalXAnimation.Reset();
2314     WrapPosition(mScrollPrePosition);
2315   }
2316   if( source == mInternalYAnimation )
2317   {
2318     DALI_LOG_SCROLL_STATE("[0x%X] Finished Y PostPosition Animation", this );
2319
2320     mScrollStateFlags &= ~SCROLL_Y_STATE_MASK;
2321     mInternalYAnimation.Reset();
2322     WrapPosition(mScrollPrePosition);
2323   }
2324 }
2325
2326 void ScrollView::SnapInternalXTo(float position)
2327 {
2328   Actor self = Self();
2329
2330   StopAnimation(mInternalXAnimation);
2331
2332   // erase current state flags
2333   mScrollStateFlags &= ~SCROLL_X_STATE_MASK;
2334
2335   // if internal x not equal to inputed parameter, animate it
2336   float duration = std::min(fabsf((position - mScrollPrePosition.x) / mMaxOvershoot.x) * mSnapOvershootDuration, mSnapOvershootDuration);
2337   DALI_LOG_SCROLL_STATE("[0x%X] duration[%.2f]", this, duration );
2338   if( duration > Math::MACHINE_EPSILON_1 )
2339   {
2340     DALI_LOG_SCROLL_STATE("[0x%X] Starting X Snap Animation to[%.2f]", this, position );
2341
2342     mInternalXAnimation = Animation::New(duration);
2343     mInternalXAnimation.FinishedSignal().Connect(this, &ScrollView::OnSnapInternalPositionFinished);
2344     mInternalXAnimation.AnimateTo(Property(self, Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, 0), position);
2345     mInternalXAnimation.Play();
2346
2347     // add internal animation state flag
2348     mScrollStateFlags |= SnappingInternalX;
2349   }
2350 }
2351
2352 void ScrollView::SnapInternalYTo(float position)
2353 {
2354   Actor self = Self();
2355
2356   StopAnimation(mInternalYAnimation);
2357
2358   // erase current state flags
2359   mScrollStateFlags &= ~SCROLL_Y_STATE_MASK;
2360
2361   // if internal y not equal to inputed parameter, animate it
2362   float duration = std::min(fabsf((position - mScrollPrePosition.y) / mMaxOvershoot.y) * mSnapOvershootDuration, mSnapOvershootDuration);
2363   DALI_LOG_SCROLL_STATE("[0x%X] duration[%.2f]", this, duration );
2364   if( duration > Math::MACHINE_EPSILON_1 )
2365   {
2366     DALI_LOG_SCROLL_STATE("[0x%X] Starting Y Snap Animation to[%.2f]", this, position );
2367
2368     mInternalYAnimation = Animation::New(duration);
2369     mInternalYAnimation.FinishedSignal().Connect(this, &ScrollView::OnSnapInternalPositionFinished);
2370     mInternalYAnimation.AnimateTo(Property(self, Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, 1), position);
2371     mInternalYAnimation.Play();
2372
2373     // add internal animation state flag
2374     mScrollStateFlags |= SnappingInternalY;
2375   }
2376 }
2377
2378 void ScrollView::GestureStarted()
2379 {
2380   // we handle the first gesture.
2381   // if we're currently doing a gesture and receive another
2382   // we continue and combine the effects of the gesture instead of reseting.
2383   if(mGestureStackDepth++==0)
2384   {
2385     Actor self = Self();
2386     StopTouchDownTimer();
2387     StopAnimation();
2388     mPanDelta = Vector2::ZERO;
2389     mLastVelocity = Vector2::ZERO;
2390     if( !mScrolling )
2391     {
2392       mLockAxis = LockPossible;
2393     }
2394
2395     if( mScrollStateFlags & SCROLL_X_STATE_MASK )
2396     {
2397       StopAnimation(mInternalXAnimation);
2398     }
2399     if( mScrollStateFlags & SCROLL_Y_STATE_MASK )
2400     {
2401       StopAnimation(mInternalYAnimation);
2402     }
2403     mScrollStateFlags = 0;
2404
2405     if(mScrolling) // are we interrupting a current scroll?
2406     {
2407       // set mScrolling to false, in case user has code that interrogates mScrolling Getter() in complete.
2408       mScrolling = false;
2409       // send negative scroll position since scroll internal scroll position works as an offset for actors,
2410       // give applications the position within the domain from the scroll view's anchor position
2411       DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignal 5 [%.2f, %.2f]", this, -mScrollPostPosition.x, -mScrollPostPosition.y);
2412       mScrollCompletedSignal.Emit( -mScrollPostPosition );
2413     }
2414   }
2415 }
2416
2417 void ScrollView::GestureContinuing(const Vector2& panDelta)
2418 {
2419   mPanDelta.x+= panDelta.x;
2420   mPanDelta.y+= panDelta.y;
2421
2422   // Save the velocity, there is a bug in PanGesture
2423   // Whereby the Gesture::Finished's velocity is either:
2424   // NaN (due to time delta of zero between the last two events)
2425   // or 0 (due to position being the same between the last two events)
2426
2427   // Axis Auto Lock - locks the panning to the horizontal or vertical axis if the pan
2428   // appears mostly horizontal or mostly vertical respectively.
2429   if(mAxisAutoLock)
2430   {
2431     mLockAxis = GetLockAxis(mPanDelta, mLockAxis, mAxisAutoLockGradient);
2432   } // end if mAxisAutoLock
2433 }
2434
2435 // TODO: Upgrade to use a more powerful gesture detector (one that supports multiple touches on pan - so works as pan and flick gesture)
2436 // BUG: Gesture::Finished doesn't always return velocity on release (due to
2437 // timeDelta between last two events being 0 sometimes, or posiiton being the same)
2438 void ScrollView::OnPan( const PanGesture& gesture )
2439 {
2440   // Guard against destruction during signal emission
2441   // Note that Emit() methods are called indirectly e.g. from within ScrollView::OnGestureEx()
2442   Actor self( Self() );
2443
2444   if(!mSensitive)
2445   {
2446     DALI_LOG_SCROLL_STATE("[0x%X] Pan Ignored, Insensitive", this);
2447
2448     // If another callback on the same original signal disables sensitivity,
2449     // this callback will still be called, so we must suppress it.
2450     return;
2451   }
2452
2453   // translate Gesture input to get useful data...
2454   switch(gesture.state)
2455   {
2456     case Gesture::Started:
2457     {
2458       DALI_LOG_SCROLL_STATE("[0x%X] Pan Started", this);
2459       mPanStartPosition = gesture.position - gesture.displacement;
2460       UpdateLocalScrollProperties();
2461       GestureStarted();
2462       mPanning = true;
2463       self.SetProperty( Toolkit::ScrollView::Property::PANNING, true );
2464       self.SetProperty( Toolkit::ScrollView::Property::START_PAGE_POSITION, Vector3(gesture.position.x, gesture.position.y, 0.0f) );
2465
2466       UpdateMainInternalConstraint();
2467       break;
2468     }
2469
2470     case Gesture::Continuing:
2471     {
2472       if ( mPanning )
2473       {
2474         DALI_LOG_SCROLL_STATE("[0x%X] Pan Continuing", this);
2475         GestureContinuing(gesture.screenDisplacement);
2476       }
2477       else
2478       {
2479         // If we do not think we are panning, then we should not do anything here
2480         return;
2481       }
2482       break;
2483     }
2484
2485     case Gesture::Finished:
2486     case Gesture::Cancelled:
2487     {
2488       if ( mPanning )
2489       {
2490         DALI_LOG_SCROLL_STATE("[0x%X] Pan %s", this, ( ( gesture.state == Gesture::Finished ) ? "Finished" : "Cancelled" ) );
2491
2492         UpdateLocalScrollProperties();
2493         mLastVelocity = gesture.velocity;
2494         mPanning = false;
2495         self.SetProperty( Toolkit::ScrollView::Property::PANNING, false );
2496
2497         if( mScrollMainInternalPrePositionConstraint )
2498         {
2499           mScrollMainInternalPrePositionConstraint.Remove();
2500         }
2501       }
2502       else
2503       {
2504         // If we do not think we are panning, then we should not do anything here
2505         return;
2506       }
2507       break;
2508     }
2509
2510     case Gesture::Possible:
2511     case Gesture::Clear:
2512     {
2513       // Nothing to do, not needed.
2514       break;
2515     }
2516
2517   } // end switch(gesture.state)
2518
2519   OnGestureEx(gesture.state);
2520 }
2521
2522 void ScrollView::OnGestureEx(Gesture::State state)
2523 {
2524   // call necessary signals for application developer
2525
2526   if(state == Gesture::Started)
2527   {
2528     Vector2 currentScrollPosition = GetCurrentScrollPosition();
2529     Self().SetProperty(Toolkit::ScrollView::Property::SCROLLING, true);
2530     mScrolling = true;
2531     DALI_LOG_SCROLL_STATE("[0x%X] mScrollStartedSignal 2 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
2532     mScrollStartedSignal.Emit( currentScrollPosition );
2533   }
2534   else if( (state == Gesture::Finished) ||
2535            (state == Gesture::Cancelled) ) // Finished/default
2536   {
2537     // when all the gestures have finished, we finish the transform.
2538     // so if a user decides to pan (1 gesture), and then pan+zoom (2 gestures)
2539     // then stop panning (back to 1 gesture), and then stop zooming (0 gestures).
2540     // this is the point we end, and perform necessary snapping.
2541     mGestureStackDepth--;
2542     if(mGestureStackDepth==0)
2543     {
2544       // no flick if we have not exceeded min flick distance
2545       if( (fabsf(mPanDelta.x) < mMinFlickDistance.x)
2546           && (fabsf(mPanDelta.y) < mMinFlickDistance.y) )
2547       {
2548         // reset flick velocity
2549         mLastVelocity = Vector2::ZERO;
2550       }
2551       FinishTransform();
2552     }
2553     else
2554     {
2555       DALI_LOG_SCROLL_STATE("[0x%X] mGestureStackDepth[%d]", this, mGestureStackDepth);
2556     }
2557   }
2558 }
2559
2560 void ScrollView::FinishTransform()
2561 {
2562   // at this stage internal x and x scroll position should have followed prescroll position exactly
2563   Actor self = Self();
2564
2565   PreAnimatedScrollSetup();
2566
2567   // convert pixels/millisecond to pixels per second
2568   bool animating = SnapWithVelocity(mLastVelocity * 1000.0f);
2569
2570   if(!animating)
2571   {
2572     // if not animating, then this pan has completed right now.
2573     SetScrollUpdateNotification(false);
2574     mScrolling = false;
2575     Self().SetProperty(Toolkit::ScrollView::Property::SCROLLING, false);
2576
2577     if( fabs(mScrollPrePosition.x - mScrollTargetPosition.x) > Math::MACHINE_EPSILON_10 )
2578     {
2579       SnapInternalXTo(mScrollTargetPosition.x);
2580     }
2581     if( fabs(mScrollPrePosition.y - mScrollTargetPosition.y) > Math::MACHINE_EPSILON_10 )
2582     {
2583       SnapInternalYTo(mScrollTargetPosition.y);
2584     }
2585     Vector2 currentScrollPosition = GetCurrentScrollPosition();
2586     DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignal 6 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
2587     mScrollCompletedSignal.Emit( currentScrollPosition );
2588   }
2589 }
2590
2591 Vector2 ScrollView::GetOvershoot(Vector2& position) const
2592 {
2593   Vector3 size = Self().GetCurrentSize();
2594   Vector2 overshoot;
2595
2596   const RulerDomain rulerDomainX = mRulerX->GetDomain();
2597   const RulerDomain rulerDomainY = mRulerY->GetDomain();
2598
2599   if(mRulerX->IsEnabled() && rulerDomainX.enabled)
2600   {
2601     const float left = rulerDomainX.min - position.x;
2602     const float right = size.width - rulerDomainX.max - position.x;
2603     if(left<0)
2604     {
2605       overshoot.x = left;
2606     }
2607     else if(right>0)
2608     {
2609       overshoot.x = right;
2610     }
2611   }
2612
2613   if(mRulerY->IsEnabled() && rulerDomainY.enabled)
2614   {
2615     const float top = rulerDomainY.min - position.y;
2616     const float bottom = size.height - rulerDomainY.max - position.y;
2617     if(top<0)
2618     {
2619       overshoot.y = top;
2620     }
2621     else if(bottom>0)
2622     {
2623       overshoot.y = bottom;
2624     }
2625   }
2626
2627   return overshoot;
2628 }
2629
2630 bool ScrollView::OnAccessibilityPan(PanGesture gesture)
2631 {
2632   // Keep track of whether this is an AccessibilityPan
2633   mInAccessibilityPan = true;
2634   OnPan(gesture);
2635   mInAccessibilityPan = false;
2636
2637   return true;
2638 }
2639
2640 void ScrollView::ClampPosition(Vector2& position) const
2641 {
2642   ClampState2D clamped;
2643   ClampPosition(position, clamped);
2644 }
2645
2646 void ScrollView::ClampPosition(Vector2& position, ClampState2D &clamped) const
2647 {
2648   Vector3 size = Self().GetCurrentSize();
2649
2650   position.x = -mRulerX->Clamp(-position.x, size.width, 1.0f, clamped.x);    // NOTE: X & Y rulers think in -ve coordinate system.
2651   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.
2652 }
2653
2654 void ScrollView::WrapPosition(Vector2& position) const
2655 {
2656   if(mWrapMode)
2657   {
2658     const RulerDomain rulerDomainX = mRulerX->GetDomain();
2659     const RulerDomain rulerDomainY = mRulerY->GetDomain();
2660
2661     if(mRulerX->IsEnabled())
2662     {
2663       position.x = -WrapInDomain(-position.x, rulerDomainX.min, rulerDomainX.max);
2664     }
2665
2666     if(mRulerY->IsEnabled())
2667     {
2668       position.y = -WrapInDomain(-position.y, rulerDomainY.min, rulerDomainY.max);
2669     }
2670   }
2671 }
2672
2673 void ScrollView::UpdateMainInternalConstraint()
2674 {
2675   // TODO: Only update the constraints which have changed, rather than remove all and add all again.
2676   // Requires a dali-core ApplyConstraintAt, or a ReplaceConstraint. The former is probably more flexible.
2677   Actor self = Self();
2678   PanGestureDetector detector( GetPanGestureDetector() );
2679
2680   if(mScrollMainInternalPositionConstraint)
2681   {
2682     mScrollMainInternalPositionConstraint.Remove();
2683     mScrollMainInternalDeltaConstraint.Remove();
2684     mScrollMainInternalFinalConstraint.Remove();
2685     mScrollMainInternalRelativeConstraint.Remove();
2686     mScrollMainInternalDomainConstraint.Remove();
2687     mScrollMainInternalPrePositionMaxConstraint.Remove();
2688   }
2689   if( mScrollMainInternalPrePositionConstraint )
2690   {
2691     mScrollMainInternalPrePositionConstraint.Remove();
2692   }
2693
2694   // TODO: It's probably better to use a local displacement value as this will give a displacement when scrolling just commences
2695   // but we need to make sure than the gesture system gives displacement since last frame (60Hz), not displacement since last touch event (90Hz).
2696
2697   // 1. First calculate the pre-position (this is the scroll position if no clamping has taken place)
2698   Vector2 initialPanMask = Vector2(mRulerX->IsEnabled() ? 1.0f : 0.0f, mRulerY->IsEnabled() ? 1.0f : 0.0f);
2699
2700   if( mLockAxis == LockVertical )
2701   {
2702     initialPanMask.y = 0.0f;
2703   }
2704   else if( mLockAxis == LockHorizontal )
2705   {
2706     initialPanMask.x = 0.0f;
2707   }
2708
2709   if( mPanning )
2710   {
2711     mScrollMainInternalPrePositionConstraint = Constraint::New<Vector2>( self,
2712                                                                          Toolkit::ScrollView::Property::SCROLL_PRE_POSITION,
2713                                                                          InternalPrePositionConstraint( mPanStartPosition,
2714                                                                                                         initialPanMask,
2715                                                                                                         mAxisAutoLock,
2716                                                                                                         mAxisAutoLockGradient,
2717                                                                                                         mLockAxis,
2718                                                                                                         mMaxOvershoot,
2719                                                                                                         mRulerX,
2720                                                                                                         mRulerY ) );
2721     mScrollMainInternalPrePositionConstraint.AddSource( Source( detector, PanGestureDetector::Property::LOCAL_POSITION ) );
2722     mScrollMainInternalPrePositionConstraint.AddSource( Source( detector, PanGestureDetector::Property::PANNING ) );
2723     mScrollMainInternalPrePositionConstraint.AddSource( Source( self, Actor::Property::SIZE ) );
2724     mScrollMainInternalPrePositionConstraint.Apply();
2725   }
2726
2727   // 2. Second calculate the clamped position (actual position)
2728   mScrollMainInternalPositionConstraint = Constraint::New<Vector2>( self,
2729                                                                     Toolkit::ScrollView::Property::SCROLL_POSITION,
2730                                                                     InternalPositionConstraint( mRulerX->GetDomain(),
2731                                                                                                 mRulerY->GetDomain(),
2732                                                                                                 mWrapMode ) );
2733   mScrollMainInternalPositionConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_PRE_POSITION ) );
2734   mScrollMainInternalPositionConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::SCROLL_POSITION_MIN ) );
2735   mScrollMainInternalPositionConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::SCROLL_POSITION_MAX ) );
2736   mScrollMainInternalPositionConstraint.AddSource( Source( self, Actor::Property::SIZE ) );
2737   mScrollMainInternalPositionConstraint.Apply();
2738
2739   mScrollMainInternalDeltaConstraint = Constraint::New<Vector2>( self, Toolkit::ScrollView::Property::SCROLL_POSITION_DELTA, InternalPositionDeltaConstraint );
2740   mScrollMainInternalDeltaConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_POSITION ) );
2741   mScrollMainInternalDeltaConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_DOMAIN_OFFSET ) );
2742   mScrollMainInternalDeltaConstraint.Apply();
2743
2744   mScrollMainInternalFinalConstraint = Constraint::New<Vector2>( self, Toolkit::ScrollView::Property::SCROLL_FINAL,
2745                                                                  InternalFinalConstraint( FinalDefaultAlphaFunction,
2746                                                                                           FinalDefaultAlphaFunction ) );
2747   mScrollMainInternalFinalConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_POSITION ) );
2748   mScrollMainInternalFinalConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::OVERSHOOT_X ) );
2749   mScrollMainInternalFinalConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::OVERSHOOT_Y ) );
2750   mScrollMainInternalFinalConstraint.Apply();
2751
2752   mScrollMainInternalRelativeConstraint = Constraint::New<Vector2>( self, Toolkit::Scrollable::Property::SCROLL_RELATIVE_POSITION, InternalRelativePositionConstraint );
2753   mScrollMainInternalRelativeConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_POSITION ) );
2754   mScrollMainInternalRelativeConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::SCROLL_POSITION_MIN ) );
2755   mScrollMainInternalRelativeConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::SCROLL_POSITION_MAX ) );
2756   mScrollMainInternalRelativeConstraint.AddSource( LocalSource( Actor::Property::SIZE ) );
2757   mScrollMainInternalRelativeConstraint.Apply();
2758
2759   mScrollMainInternalDomainConstraint = Constraint::New<Vector2>( self, Toolkit::ScrollView::Property::SCROLL_DOMAIN_SIZE, InternalScrollDomainConstraint );
2760   mScrollMainInternalDomainConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::SCROLL_POSITION_MIN ) );
2761   mScrollMainInternalDomainConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::SCROLL_POSITION_MAX ) );
2762   mScrollMainInternalDomainConstraint.AddSource( LocalSource( Actor::Property::SIZE ) );
2763   mScrollMainInternalDomainConstraint.Apply();
2764
2765   mScrollMainInternalPrePositionMaxConstraint = Constraint::New<Vector2>( self, Toolkit::ScrollView::Property::SCROLL_PRE_POSITION_MAX, InternalPrePositionMaxConstraint );
2766   mScrollMainInternalPrePositionMaxConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::SCROLL_POSITION_MAX ) );
2767   mScrollMainInternalPrePositionMaxConstraint.AddSource( LocalSource( Actor::Property::SIZE ) );
2768   mScrollMainInternalPrePositionMaxConstraint.Apply();
2769
2770   // When panning we want to make sure overshoot values are affected by pre position and post position
2771   SetOvershootConstraintsEnabled(!mWrapMode);
2772 }
2773
2774 void ScrollView::SetOvershootConstraintsEnabled(bool enabled)
2775 {
2776   Actor self( Self() );
2777   // remove and reset, it may now be in wrong order with the main internal constraints
2778   if( mScrollMainInternalOvershootXConstraint )
2779   {
2780     mScrollMainInternalOvershootXConstraint.Remove();
2781     mScrollMainInternalOvershootXConstraint.Reset();
2782     mScrollMainInternalOvershootYConstraint.Remove();
2783     mScrollMainInternalOvershootYConstraint.Reset();
2784   }
2785   if( enabled )
2786   {
2787     mScrollMainInternalOvershootXConstraint= Constraint::New<float>( self, Toolkit::ScrollView::Property::OVERSHOOT_X, OvershootXConstraint(mMaxOvershoot.x) );
2788     mScrollMainInternalOvershootXConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_PRE_POSITION ) );
2789     mScrollMainInternalOvershootXConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_POSITION ) );
2790     mScrollMainInternalOvershootXConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::CAN_SCROLL_HORIZONTAL ) );
2791     mScrollMainInternalOvershootXConstraint.Apply();
2792
2793     mScrollMainInternalOvershootYConstraint = Constraint::New<float>( self, Toolkit::ScrollView::Property::OVERSHOOT_Y, OvershootYConstraint(mMaxOvershoot.y) );
2794     mScrollMainInternalOvershootYConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_PRE_POSITION ) );
2795     mScrollMainInternalOvershootYConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_POSITION ) );
2796     mScrollMainInternalOvershootYConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::CAN_SCROLL_VERTICAL ) );
2797     mScrollMainInternalOvershootYConstraint.Apply();
2798   }
2799   else
2800   {
2801     self.SetProperty(Toolkit::ScrollView::Property::OVERSHOOT_X, 0.0f);
2802     self.SetProperty(Toolkit::ScrollView::Property::OVERSHOOT_Y, 0.0f);
2803   }
2804 }
2805
2806 void ScrollView::SetInternalConstraints()
2807 {
2808   // Internal constraints (applied to target ScrollBase Actor itself) /////////
2809   UpdateMainInternalConstraint();
2810
2811   // User definable constraints to apply to all child actors //////////////////
2812   Actor self = Self();
2813
2814   // Apply some default constraints to ScrollView & its bound actors
2815   // Movement + Wrap function
2816
2817   Constraint constraint;
2818
2819   // MoveActor (scrolling)
2820   constraint = Constraint::New<Vector3>( self, Actor::Property::POSITION, MoveActorConstraint );
2821   constraint.AddSource( Source( self, Toolkit::ScrollView::Property::SCROLL_POSITION ) );
2822   constraint.SetRemoveAction(Constraint::Discard);
2823   ApplyConstraintToBoundActors(constraint);
2824
2825   // WrapActor (wrap functionality)
2826   constraint = Constraint::New<Vector3>( self, Actor::Property::POSITION, WrapActorConstraint );
2827   constraint.AddSource( LocalSource( Actor::Property::SCALE ) );
2828   constraint.AddSource( LocalSource( Actor::Property::ANCHOR_POINT ) );
2829   constraint.AddSource( LocalSource( Actor::Property::SIZE ) );
2830   constraint.AddSource( Source( self, Toolkit::Scrollable::Property::SCROLL_POSITION_MIN ) );
2831   constraint.AddSource( Source( self, Toolkit::Scrollable::Property::SCROLL_POSITION_MAX ) );
2832   constraint.AddSource( Source( self, Toolkit::ScrollView::Property::WRAP ) );
2833   constraint.SetRemoveAction(Constraint::Discard);
2834   ApplyConstraintToBoundActors(constraint);
2835 }
2836
2837 void ScrollView::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
2838 {
2839   Toolkit::ScrollView scrollView = Toolkit::ScrollView::DownCast( Dali::BaseHandle( object ) );
2840
2841   if( scrollView )
2842   {
2843     ScrollView& scrollViewImpl( GetImpl( scrollView ) );
2844     switch( index )
2845     {
2846       case Toolkit::ScrollView::Property::WRAP_ENABLED:
2847       {
2848         scrollViewImpl.SetWrapMode( value.Get<bool>() );
2849         break;
2850       }
2851       case Toolkit::ScrollView::Property::PANNING_ENABLED:
2852       {
2853         scrollViewImpl.SetScrollSensitive( value.Get<bool>() );
2854         break;
2855       }
2856       case Toolkit::ScrollView::Property::AXIS_AUTO_LOCK_ENABLED:
2857       {
2858         scrollViewImpl.SetAxisAutoLock( value.Get<bool>() );
2859         break;
2860       }
2861       case Toolkit::ScrollView::Property::WHEEL_SCROLL_DISTANCE_STEP:
2862       {
2863         scrollViewImpl.SetWheelScrollDistanceStep( value.Get<Vector2>() );
2864         break;
2865       }
2866     }
2867   }
2868 }
2869
2870 Property::Value ScrollView::GetProperty( BaseObject* object, Property::Index index )
2871 {
2872   Property::Value value;
2873
2874   Toolkit::ScrollView scrollView = Toolkit::ScrollView::DownCast( Dali::BaseHandle( object ) );
2875
2876   if( scrollView )
2877   {
2878     ScrollView& scrollViewImpl( GetImpl( scrollView ) );
2879     switch( index )
2880     {
2881       case Toolkit::ScrollView::Property::WRAP_ENABLED:
2882       {
2883         value = scrollViewImpl.GetWrapMode();
2884         break;
2885       }
2886       case Toolkit::ScrollView::Property::PANNING_ENABLED:
2887       {
2888         value = scrollViewImpl.GetScrollSensitive();
2889         break;
2890       }
2891       case Toolkit::ScrollView::Property::AXIS_AUTO_LOCK_ENABLED:
2892       {
2893         value = scrollViewImpl.GetAxisAutoLock();
2894         break;
2895       }
2896       case Toolkit::ScrollView::Property::WHEEL_SCROLL_DISTANCE_STEP:
2897       {
2898         value = scrollViewImpl.GetWheelScrollDistanceStep();
2899         break;
2900       }
2901     }
2902   }
2903
2904   return value;
2905 }
2906
2907 } // namespace Internal
2908
2909 } // namespace Toolkit
2910
2911 } // namespace Dali