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