2 * Copyright (c) 2020 Samsung Electronics Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include <dali-toolkit/internal/controls/scrollable/scroll-view/scroll-view-impl.h>
22 #include <cstring> // for strcmp
23 #include <dali/public-api/animation/constraints.h>
24 #include <dali/devel-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/public-api/object/property-map.h>
30 #include <dali/devel-api/object/property-helper-devel.h>
31 #include <dali/devel-api/events/pan-gesture-devel.h>
32 #include <dali/integration-api/debug.h>
35 #include <dali-toolkit/devel-api/controls/scroll-bar/scroll-bar.h>
36 #include <dali-toolkit/public-api/controls/scrollable/scroll-view/scroll-view.h>
37 #include <dali-toolkit/public-api/controls/scrollable/scroll-view/scroll-view-constraints.h>
38 #include <dali-toolkit/public-api/controls/scrollable/scroll-view/scroll-mode.h>
39 #include <dali-toolkit/internal/controls/scrollable/scroll-view/scroll-overshoot-indicator-impl.h>
40 #include <dali-toolkit/internal/controls/scrollable/scroll-view/scroll-view-effect-impl.h>
42 //#define ENABLED_SCROLL_STATE_LOGGING
44 #ifdef ENABLED_SCROLL_STATE_LOGGING
45 #define DALI_LOG_SCROLL_STATE(format, ...) Dali::Integration::Log::LogMessage(Dali::Integration::Log::DebugInfo, "%s:%d " format "\n", __PRETTY_FUNCTION__, __LINE__, ## __VA_ARGS__)
47 #define DALI_LOG_SCROLL_STATE(format, ...)
50 // TODO: Change to two class system:
51 // 1. DraggableActor (is an actor which can be dragged anywhere, can be set to range using the ruler)
52 // 2. ScrollView (contains a draggable actor that can a) be dragged in the negative X, and Y domain, b) has a hitArea for touches)
53 // TODO: external components (page and status overlays).
55 // TODO: upgrade Vector2/3 to support returning Unit vectors, normals, & cross product (dot product is already provided)
61 const float DEFAULT_SLOW_SNAP_ANIMATION_DURATION(0.5f); ///< Default Drag-Release animation time.
62 const float DEFAULT_FAST_SNAP_ANIMATION_DURATION(0.25f); ///< Default Drag-Flick animation time.
63 const float DEFAULT_SNAP_OVERSHOOT_DURATION(0.5f); ///< Default Overshoot snapping animation time.
64 const float DEFAULT_MAX_OVERSHOOT(100.0f); ///< Default maximum allowed overshoot in pixels
66 const float DEFAULT_AXIS_AUTO_LOCK_GRADIENT(0.36f); ///< Default Axis-AutoLock gradient threshold. default is 0.36:1 (20 degrees)
67 const float DEFAULT_FRICTION_COEFFICIENT(1.0f); ///< Default Friction Co-efficient. (in stage diagonals per second)
68 const float DEFAULT_FLICK_SPEED_COEFFICIENT(1.0f); ///< Default Flick speed coefficient (multiples input touch velocity)
69 const float DEFAULT_MAX_FLICK_SPEED(3.0f); ///< Default Maximum flick speed. (in stage diagonals per second)
71 const Vector2 DEFAULT_MIN_FLICK_DISTANCE(30.0f, 30.0f); ///< minimum distance for pan before flick allowed
72 const float DEFAULT_MIN_FLICK_SPEED_THRESHOLD(500.0f); ///< Minimum pan speed required for flick in pixels/s
73 const float FREE_FLICK_SPEED_THRESHOLD = 200.0f; ///< Free-Flick threshold in pixels/ms
74 const float AUTOLOCK_AXIS_MINIMUM_DISTANCE2 = 100.0f; ///< Auto-lock axis after minimum distance squared.
75 const float FLICK_ORTHO_ANGLE_RANGE = 75.0f; ///< degrees. (if >45, then supports diagonal flicking)
76 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.
77 const unsigned long MINIMUM_TIME_BETWEEN_DOWN_AND_UP_FOR_RESET( 150u );
78 const float TOUCH_DOWN_TIMER_INTERVAL = 100.0f;
79 const float DEFAULT_SCROLL_UPDATE_DISTANCE( 30.0f ); ///< Default distance to travel in pixels for scroll update signal
81 const std::string INTERNAL_MAX_POSITION_PROPERTY_NAME( "internalMaxPosition" );
83 // Helpers ////////////////////////////////////////////////////////////////////////////////////////
86 * Find the vector (distance) from (a) to (b)
87 * in domain (start) to (end)
88 * (\ / start) (\ / end)
91 * @note assumes both (a) and (b) are already with the domain
94 * @param[in] a the current point
95 * @param[in] b the target point
96 * @param[in] start the start of the domain
97 * @param[in] end the end of the domain
98 * @param[in] bias whether to only take the right direction or the left direction,
99 * or the shortest direction.
100 * @return the shortest direction and distance
102 float VectorInDomain(float a, float b, float start, float end, Dali::Toolkit::DirectionBias bias)
104 if(bias == Dali::Toolkit::DIRECTION_BIAS_NONE)
106 return ShortestDistanceInDomain( a, b, start, end );
109 float size = end-start;
115 if(bias == Dali::Toolkit::DIRECTION_BIAS_RIGHT) // going right, take the vector.
121 float aRight = a+size;
128 if(bias == Dali::Toolkit::DIRECTION_BIAS_LEFT) // going left, take the vector.
134 float aLeft = a-size;
141 * Returns the position of the anchor within actor
143 * @param actor The Actor
144 * @param anchor The Anchor point of interest.
145 * @return The position of the Anchor
147 Vector3 GetPositionOfAnchor(Actor &actor, const Vector3 &anchor)
149 Vector3 childPosition = actor.GetCurrentProperty< Vector3 >( Actor::Property::POSITION );
150 Vector3 childAnchor = - actor.GetCurrentProperty< Vector3 >( Actor::Property::ANCHOR_POINT ) + anchor;
151 Vector3 childSize = actor.GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
153 return childPosition + childAnchor * childSize;
156 // AlphaFunctions /////////////////////////////////////////////////////////////////////////////////
158 float FinalDefaultAlphaFunction(float offset)
160 return offset * 0.5f;
164 * ConstantDecelerationAlphaFunction
165 * Newtoninan distance for constant deceleration
166 * v = 1 - t, s = t - 1/2 t^2
167 * when t = 0, s = 0.0 (min distance)
168 * when t = 1, s = 0.5 (max distance)
169 * progress = s / (max-min) = 2t - t^2
171 * @param[in] offset The input progress
172 * @return The output progress
174 float ConstantDecelerationAlphaFunction(float progress)
176 return progress * 2.0f - progress * progress;
179 // Internal Constraints ///////////////////////////////////////////////////////////////////////////
182 * Internal Relative position Constraint
183 * Generates the relative position value of the scroll view
184 * based on the absolute position, and it's relation to the
185 * scroll domain. This is a value from 0.0f to 1.0f in each
186 * scroll position axis.
188 void InternalRelativePositionConstraint( Vector2& relativePosition, const PropertyInputContainer& inputs)
190 Vector2 position = -inputs[0]->GetVector2();
191 const Vector2& min = inputs[1]->GetVector2();
192 const Vector2& max = inputs[2]->GetVector2();
193 const Vector3& size = inputs[3]->GetVector3();
195 position.x = WrapInDomain(position.x, min.x, max.x);
196 position.y = WrapInDomain(position.y, min.y, max.y);
198 Vector2 domainSize = (max - min) - size.GetVectorXY();
200 relativePosition.x = domainSize.x > Math::MACHINE_EPSILON_1 ? fabsf((position.x - min.x) / domainSize.x) : 0.0f;
201 relativePosition.y = domainSize.y > Math::MACHINE_EPSILON_1 ? fabsf((position.y - min.y) / domainSize.y) : 0.0f;
205 * Internal scroll domain Constraint
206 * Generates the scroll domain of the scroll view.
208 void InternalScrollDomainConstraint( Vector2& scrollDomain, const PropertyInputContainer& inputs)
210 const Vector2& min = inputs[0]->GetVector2();
211 const Vector2& max = inputs[1]->GetVector2();
212 const Vector3& size = inputs[2]->GetVector3();
214 scrollDomain = (max - min) - size.GetVectorXY();
218 * Internal maximum scroll position Constraint
219 * Generates the maximum scroll position of the scroll view.
221 void InternalPrePositionMaxConstraint( Vector2& scrollMax, const PropertyInputContainer& inputs)
223 const Vector2& max = inputs[0]->GetVector2();
224 const Vector3& size = inputs[1]->GetVector3();
226 scrollMax = max - size.GetVectorXY();
229 } // unnamed namespace
245 return Toolkit::ScrollView::New();
248 // Setup properties, signals and actions using the type-registry.
249 DALI_TYPE_REGISTRATION_BEGIN( Toolkit::ScrollView, Toolkit::Scrollable, Create )
251 DALI_PROPERTY_REGISTRATION( Toolkit, ScrollView, "wrapEnabled", BOOLEAN, WRAP_ENABLED )
252 DALI_PROPERTY_REGISTRATION( Toolkit, ScrollView, "panningEnabled", BOOLEAN, PANNING_ENABLED )
253 DALI_PROPERTY_REGISTRATION( Toolkit, ScrollView, "axisAutoLockEnabled", BOOLEAN, AXIS_AUTO_LOCK_ENABLED )
254 DALI_PROPERTY_REGISTRATION( Toolkit, ScrollView, "wheelScrollDistanceStep", VECTOR2, WHEEL_SCROLL_DISTANCE_STEP )
255 DALI_PROPERTY_REGISTRATION( Toolkit, ScrollView, "scrollMode", MAP, SCROLL_MODE )
257 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "scrollPosition", VECTOR2, SCROLL_POSITION)
258 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "scrollPrePosition", VECTOR2, SCROLL_PRE_POSITION)
259 DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, ScrollView, "scrollPrePositionX", SCROLL_PRE_POSITION_X, SCROLL_PRE_POSITION, 0)
260 DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, ScrollView, "scrollPrePositionY", SCROLL_PRE_POSITION_Y, SCROLL_PRE_POSITION, 1)
261 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "scrollPrePositionMax", VECTOR2, SCROLL_PRE_POSITION_MAX)
262 DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, ScrollView, "scrollPrePositionMaxX", SCROLL_PRE_POSITION_MAX_X, SCROLL_PRE_POSITION_MAX, 0)
263 DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, ScrollView, "scrollPrePositionMaxY", SCROLL_PRE_POSITION_MAX_Y, SCROLL_PRE_POSITION_MAX, 1)
264 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "overshootX", FLOAT, OVERSHOOT_X)
265 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "overshootY", FLOAT, OVERSHOOT_Y)
266 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "scrollFinal", VECTOR2, SCROLL_FINAL)
267 DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, ScrollView, "scrollFinalX", SCROLL_FINAL_X, SCROLL_FINAL,0)
268 DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, ScrollView, "scrollFinalY", SCROLL_FINAL_Y, SCROLL_FINAL,1)
269 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "wrap", BOOLEAN, WRAP)
270 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "panning", BOOLEAN, PANNING)
271 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "scrolling", BOOLEAN, SCROLLING)
272 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "scrollDomainSize", VECTOR2, SCROLL_DOMAIN_SIZE)
273 DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, ScrollView, "scrollDomainSizeX", SCROLL_DOMAIN_SIZE_X, SCROLL_DOMAIN_SIZE, 0)
274 DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, ScrollView, "scrollDomainSizeY", SCROLL_DOMAIN_SIZE_Y, SCROLL_DOMAIN_SIZE, 1)
275 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "scrollDomainOffset", VECTOR2, SCROLL_DOMAIN_OFFSET)
276 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "scrollPositionDelta", VECTOR2, SCROLL_POSITION_DELTA)
277 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "startPagePosition", VECTOR3, START_PAGE_POSITION)
279 DALI_SIGNAL_REGISTRATION( Toolkit, ScrollView, "valueChanged", SIGNAL_SNAP_STARTED )
281 DALI_TYPE_REGISTRATION_END()
284 * Returns whether to lock scrolling to a particular axis
286 * @param[in] panDelta Distance panned since gesture started
287 * @param[in] currentLockAxis The current lock axis value
288 * @param[in] lockGradient How quickly to lock to a particular axis
290 * @return The new axis lock state
292 ScrollView::LockAxis GetLockAxis(const Vector2& panDelta, ScrollView::LockAxis currentLockAxis, float lockGradient)
294 if(panDelta.LengthSquared() > AUTOLOCK_AXIS_MINIMUM_DISTANCE2 &&
295 currentLockAxis == ScrollView::LockPossible)
297 float dx = fabsf(panDelta.x);
298 float dy = fabsf(panDelta.y);
299 if(dx * lockGradient >= dy)
301 // 0.36:1 gradient to the horizontal (deviate < 20 degrees)
302 currentLockAxis = ScrollView::LockVertical;
304 else if(dy * lockGradient > dx)
306 // 0.36:1 gradient to the vertical (deviate < 20 degrees)
307 currentLockAxis = ScrollView::LockHorizontal;
311 currentLockAxis = ScrollView::LockNone;
314 return currentLockAxis;
318 * Internal Pre-Position Property Constraint.
320 * Generates position property based on current position + gesture displacement.
321 * Or generates position property based on positionX/Y.
322 * Note: This is the position prior to any clamping at scroll boundaries.
324 struct InternalPrePositionConstraint
326 InternalPrePositionConstraint( const Vector2& initialPanPosition,
327 const Vector2& initialPanMask,
329 float axisAutoLockGradient,
330 ScrollView::LockAxis initialLockAxis,
331 const Vector2& maxOvershoot,
332 const RulerPtr& rulerX, const RulerPtr& rulerY )
333 : mLocalStart( initialPanPosition ),
334 mInitialPanMask( initialPanMask ),
335 mMaxOvershoot( maxOvershoot ),
336 mAxisAutoLockGradient( axisAutoLockGradient ),
337 mLockAxis( initialLockAxis ),
338 mAxisAutoLock( axisAutoLock ),
341 const RulerDomain& rulerDomainX = rulerX->GetDomain();
342 const RulerDomain& rulerDomainY = rulerY->GetDomain();
343 mDomainMin = Vector2( rulerDomainX.min, -rulerDomainY.min );
344 mDomainMax = Vector2( -rulerDomainX.max, -rulerDomainY.max );
345 mClampX = rulerDomainX.enabled;
346 mClampY = rulerDomainY.enabled;
347 mFixedRulerX = rulerX->GetType() == Ruler::FIXED;
348 mFixedRulerY = rulerY->GetType() == Ruler::FIXED;
351 void operator()( Vector2& scrollPostPosition, const PropertyInputContainer& inputs )
353 const Vector2& panPosition = inputs[0]->GetVector2();
354 const bool& inGesture = inputs[1]->GetBoolean();
356 // First check if we are within a gesture.
357 // The ScrollView may have received a start gesture from ::OnPan()
358 // while the finish gesture is received now in this constraint.
359 // This gesture must then be rejected as the value will be "old".
360 // Typically the last value from the end of the last gesture.
361 // If we are rejecting the gesture, we simply don't modify the constraint target.
366 mPrePosition = scrollPostPosition;
367 mStartPosition = mPrePosition;
368 mCurrentPanMask = mInitialPanMask;
372 // Calculate Deltas...
373 const Vector2& currentPosition = panPosition;
374 Vector2 panDelta( currentPosition - mLocalStart );
376 // Axis Auto Lock - locks the panning to the horizontal or vertical axis if the pan
377 // appears mostly horizontal or mostly vertical respectively...
380 mLockAxis = GetLockAxis( panDelta, mLockAxis, mAxisAutoLockGradient );
381 if( mLockAxis == ScrollView::LockVertical )
383 mCurrentPanMask.y = 0.0f;
385 else if( mLockAxis == ScrollView::LockHorizontal )
387 mCurrentPanMask.x = 0.0f;
391 // Restrict deltas based on ruler enable/disable and axis-lock state...
392 panDelta *= mCurrentPanMask;
394 // Perform Position transform based on input deltas...
395 scrollPostPosition = mPrePosition;
396 scrollPostPosition += panDelta;
398 // if no wrapping then clamp preposition to maximum overshoot amount
399 const Vector3& size = inputs[2]->GetVector3();
402 float newXPosition = Clamp( scrollPostPosition.x, ( mDomainMax.x + size.x ) - mMaxOvershoot.x, mDomainMin.x + mMaxOvershoot.x );
403 if( (newXPosition < scrollPostPosition.x - Math::MACHINE_EPSILON_1)
404 || (newXPosition > scrollPostPosition.x + Math::MACHINE_EPSILON_1) )
406 mPrePosition.x = newXPosition;
407 mLocalStart.x = panPosition.x;
409 scrollPostPosition.x = newXPosition;
413 float newYPosition = Clamp( scrollPostPosition.y, ( mDomainMax.y + size.y ) - mMaxOvershoot.y, mDomainMin.y + mMaxOvershoot.y );
414 if( ( newYPosition < scrollPostPosition.y - Math::MACHINE_EPSILON_1 )
415 || ( newYPosition > scrollPostPosition.y + Math::MACHINE_EPSILON_1 ) )
417 mPrePosition.y = newYPosition;
418 mLocalStart.y = panPosition.y;
420 scrollPostPosition.y = newYPosition;
423 // If we are using a fixed ruler in a particular axis, limit the maximum pages scrolled on that axis.
424 if( mFixedRulerX || mFixedRulerY )
426 // Here we limit the maximum amount that can be moved from the starting position of the gesture to one page.
427 // We do this only if we have a fixed ruler (on that axis) and the mode is enabled.
428 // Note: 1.0f is subtracted to keep the value within one page size (otherwise we stray on to the page after).
429 // Note: A further 1.0f is subtracted to handle a compensation that happens later within the flick handling code in SnapWithVelocity().
430 // When a flick is completed, an adjustment of 1.0f is sometimes made to allow for the scenario where:
431 // A flick finishes before the update thread has advanced the scroll position past the previous snap point.
432 Vector2 viewPageSizeLimit( size.x - ( 1.0f + 1.0f ), size.y - ( 1.0f - 1.0f ) );
433 Vector2 minPosition( mStartPosition.x - viewPageSizeLimit.x, mStartPosition.y - viewPageSizeLimit.y );
434 Vector2 maxPosition( mStartPosition.x + viewPageSizeLimit.x, mStartPosition.y + viewPageSizeLimit.y );
438 scrollPostPosition.x = Clamp( scrollPostPosition.x, minPosition.x, maxPosition.x );
442 scrollPostPosition.y = Clamp( scrollPostPosition.y, minPosition.y, maxPosition.y );
448 Vector2 mPrePosition;
450 Vector2 mStartPosition; ///< The start position of the gesture - used to limit scroll amount (not modified by clamping).
451 Vector2 mInitialPanMask; ///< Initial pan mask (based on ruler settings).
452 Vector2 mCurrentPanMask; ///< Current pan mask that can be altered by axis lock mode.
455 Vector2 mMaxOvershoot;
457 float mAxisAutoLockGradient; ///< Set by ScrollView
458 ScrollView::LockAxis mLockAxis;
460 bool mAxisAutoLock:1; ///< Set by ScrollView
469 * Internal Position Property Constraint.
471 * Generates position property based on pre-position
472 * Note: This is the position after clamping.
473 * (uses result of InternalPrePositionConstraint)
475 struct InternalPositionConstraint
477 InternalPositionConstraint(const RulerDomain& domainX, const RulerDomain& domainY, bool wrap)
478 : mDomainMin( -domainX.min, -domainY.min ),
479 mDomainMax( -domainX.max, -domainY.max ),
480 mClampX( domainX.enabled ),
481 mClampY( domainY.enabled ),
486 void operator()( Vector2& position, const PropertyInputContainer& inputs )
488 position = inputs[0]->GetVector2();
489 const Vector2& size = inputs[3]->GetVector3().GetVectorXY();
490 const Vector2& min = inputs[1]->GetVector2();
491 const Vector2& max = inputs[2]->GetVector2();
495 position.x = -WrapInDomain(-position.x, min.x, max.x);
496 position.y = -WrapInDomain(-position.y, min.y, max.y);
500 // clamp post position to domain
501 position.x = mClampX ? Clamp(position.x, mDomainMax.x + size.x, mDomainMin.x ) : position.x;
502 position.y = mClampY ? Clamp(position.y, mDomainMax.y + size.y, mDomainMin.y ) : position.y;
515 * This constraint updates the X overshoot property using the difference
516 * SCROLL_PRE_POSITION.x and SCROLL_POSITION.x, returning a relative value between 0.0f and 1.0f
518 struct OvershootXConstraint
520 OvershootXConstraint(float maxOvershoot) : mMaxOvershoot(maxOvershoot) {}
522 void operator()( float& current, const PropertyInputContainer& inputs )
524 if( inputs[2]->GetBoolean() )
526 const Vector2& scrollPrePosition = inputs[0]->GetVector2();
527 const Vector2& scrollPostPosition = inputs[1]->GetVector2();
528 float newOvershoot = scrollPrePosition.x - scrollPostPosition.x;
529 current = (newOvershoot > 0.0f ? std::min(newOvershoot, mMaxOvershoot) : std::max(newOvershoot, -mMaxOvershoot)) / mMaxOvershoot;
541 * This constraint updates the Y overshoot property using the difference
542 * SCROLL_PRE_POSITION.y and SCROLL_POSITION.y, returning a relative value between 0.0f and 1.0f
544 struct OvershootYConstraint
546 OvershootYConstraint(float maxOvershoot) : mMaxOvershoot(maxOvershoot) {}
548 void operator()( float& current, const PropertyInputContainer& inputs )
550 if( inputs[2]->GetBoolean() )
552 const Vector2& scrollPrePosition = inputs[0]->GetVector2();
553 const Vector2& scrollPostPosition = inputs[1]->GetVector2();
554 float newOvershoot = scrollPrePosition.y - scrollPostPosition.y;
555 current = (newOvershoot > 0.0f ? std::min(newOvershoot, mMaxOvershoot) : std::max(newOvershoot, -mMaxOvershoot)) / mMaxOvershoot;
567 * Internal Position-Delta Property Constraint.
569 * Generates position-delta property based on scroll-position + scroll-offset properties.
571 void InternalPositionDeltaConstraint( Vector2& current, const PropertyInputContainer& inputs )
573 const Vector2& scrollPosition = inputs[0]->GetVector2();
574 const Vector2& scrollOffset = inputs[1]->GetVector2();
576 current = scrollPosition + scrollOffset;
580 * Internal Final Position Constraint
581 * The position of content is:
582 * of scroll-position + f(scroll-overshoot)
583 * where f(...) function defines how overshoot
584 * should affect final-position.
586 struct InternalFinalConstraint
588 InternalFinalConstraint(AlphaFunctionPrototype functionX,
589 AlphaFunctionPrototype functionY)
590 : mFunctionX(functionX),
591 mFunctionY(functionY)
595 void operator()( Vector2& current, const PropertyInputContainer& inputs )
597 const float& overshootx = inputs[1]->GetFloat();
598 const float& overshooty = inputs[2]->GetFloat();
599 Vector2 offset( mFunctionX(overshootx),
600 mFunctionY(overshooty) );
602 current = inputs[0]->GetVector2() - offset;
605 AlphaFunctionPrototype mFunctionX;
606 AlphaFunctionPrototype mFunctionY;
612 ///////////////////////////////////////////////////////////////////////////////////////////////////
614 ///////////////////////////////////////////////////////////////////////////////////////////////////
616 Dali::Toolkit::ScrollView ScrollView::New()
618 // Create the implementation
619 ScrollViewPtr scrollView(new ScrollView());
621 // Pass ownership to CustomActor via derived handle
622 Dali::Toolkit::ScrollView handle(*scrollView);
624 // Second-phase init of the implementation
625 // This can only be done after the CustomActor connection has been made...
626 scrollView->Initialize();
631 ScrollView::ScrollView()
632 : ScrollBase( ControlBehaviour( DISABLE_STYLE_CHANGE_SIGNALS ) ), // Enable size negotiation
634 mGestureStackDepth(0),
635 mScrollStateFlags(0),
636 mLockAxis(LockPossible),
637 mScrollUpdateDistance(DEFAULT_SCROLL_UPDATE_DISTANCE),
638 mMaxOvershoot(DEFAULT_MAX_OVERSHOOT, DEFAULT_MAX_OVERSHOOT),
639 mUserMaxOvershoot(DEFAULT_MAX_OVERSHOOT, DEFAULT_MAX_OVERSHOOT),
640 mSnapOvershootDuration(DEFAULT_SNAP_OVERSHOOT_DURATION),
641 mSnapOvershootAlphaFunction(AlphaFunction::EASE_OUT),
642 mSnapDuration(DEFAULT_SLOW_SNAP_ANIMATION_DURATION),
643 mSnapAlphaFunction(AlphaFunction::EASE_OUT),
644 mMinFlickDistance(DEFAULT_MIN_FLICK_DISTANCE),
645 mFlickSpeedThreshold(DEFAULT_MIN_FLICK_SPEED_THRESHOLD),
646 mFlickDuration(DEFAULT_FAST_SNAP_ANIMATION_DURATION),
647 mFlickAlphaFunction(AlphaFunction::EASE_OUT),
648 mAxisAutoLockGradient(DEFAULT_AXIS_AUTO_LOCK_GRADIENT),
649 mFrictionCoefficient(DEFAULT_FRICTION_COEFFICIENT),
650 mFlickSpeedCoefficient(DEFAULT_FLICK_SPEED_COEFFICIENT),
651 mMaxFlickSpeed(DEFAULT_MAX_FLICK_SPEED),
652 mWheelScrollDistanceStep(Vector2::ZERO),
653 mInAccessibilityPan(false),
655 mScrollInterrupted(false),
658 mTouchDownTimeoutReached(false),
659 mActorAutoSnapEnabled(false),
660 mAutoResizeContainerEnabled(false),
662 mAxisAutoLock(false),
664 mDefaultMaxOvershoot(true),
665 mCanScrollHorizontal(true),
666 mCanScrollVertical(true),
667 mTransientScrollBar(true)
671 void ScrollView::OnInitialize()
675 // Internal Actor, used to hide actors from enumerations.
676 // Also actors added to Internal actor appear as overlays e.g. ScrollBar components.
677 mInternalActor = Actor::New();
678 self.Add(mInternalActor);
680 mInternalActor.SetProperty( Actor::Property::PARENT_ORIGIN,ParentOrigin::CENTER );
681 mInternalActor.SetProperty( Actor::Property::ANCHOR_POINT,AnchorPoint::CENTER);
682 mInternalActor.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS );
686 mScrollPostPosition = mScrollPrePosition = Vector2::ZERO;
688 mWheelScrollDistanceStep = Stage::GetCurrent().GetSize() * DEFAULT_WHEEL_SCROLL_DISTANCE_STEP_PROPORTION;
690 mGestureStackDepth = 0;
692 self.TouchedSignal().Connect( this, &ScrollView::OnTouch );
693 EnableGestureDetection( GestureType::Value( GestureType::PAN ) );
695 // By default we'll allow the user to freely drag the scroll view,
696 // while disabling the other rulers.
697 RulerPtr ruler = new DefaultRuler();
701 self.SetProperty(Toolkit::Scrollable::Property::CAN_SCROLL_VERTICAL, mCanScrollVertical);
702 self.SetProperty(Toolkit::Scrollable::Property::CAN_SCROLL_HORIZONTAL, mCanScrollHorizontal);
704 UpdatePropertyDomain();
705 SetInternalConstraints();
707 // Connect wheel event
708 self.WheelEventSignal().Connect( this, &ScrollView::OnWheelEvent );
711 void ScrollView::OnSceneConnection( int depth )
713 DALI_LOG_SCROLL_STATE("[0x%X]", this);
717 SetScrollSensitive( false );
718 SetScrollSensitive( true );
721 if(IsOvershootEnabled())
723 // try and make sure property notifications are set
724 EnableScrollOvershoot(true);
727 ScrollBase::OnSceneConnection( depth );
730 void ScrollView::OnSceneDisconnection()
732 DALI_LOG_SCROLL_STATE("[0x%X]", this);
736 ScrollBase::OnSceneDisconnection();
739 ScrollView::~ScrollView()
741 DALI_LOG_SCROLL_STATE("[0x%X]", this);
744 AlphaFunction ScrollView::GetScrollSnapAlphaFunction() const
746 return mSnapAlphaFunction;
749 void ScrollView::SetScrollSnapAlphaFunction(AlphaFunction alpha)
751 mSnapAlphaFunction = alpha;
754 AlphaFunction ScrollView::GetScrollFlickAlphaFunction() const
756 return mFlickAlphaFunction;
759 void ScrollView::SetScrollFlickAlphaFunction(AlphaFunction alpha)
761 mFlickAlphaFunction = alpha;
764 float ScrollView::GetScrollSnapDuration() const
766 return mSnapDuration;
769 void ScrollView::SetScrollSnapDuration(float time)
771 mSnapDuration = time;
774 float ScrollView::GetScrollFlickDuration() const
776 return mFlickDuration;
779 void ScrollView::SetScrollFlickDuration(float time)
781 mFlickDuration = time;
784 void ScrollView::ApplyEffect(Toolkit::ScrollViewEffect effect)
786 Dali::Toolkit::ScrollView self = Dali::Toolkit::ScrollView::DownCast(Self());
788 // Assertion check to ensure effect doesn't already exist in this scrollview
789 bool effectAlreadyExistsInScrollView(false);
790 for (ScrollViewEffectIter iter = mEffects.begin(); iter != mEffects.end(); ++iter)
794 effectAlreadyExistsInScrollView = true;
799 DALI_ASSERT_ALWAYS(!effectAlreadyExistsInScrollView);
801 // add effect to effects list
802 mEffects.push_back(effect);
804 // invoke Attachment request to ScrollView first
805 GetImpl(effect).Attach(self);
808 void ScrollView::RemoveEffect(Toolkit::ScrollViewEffect effect)
810 Dali::Toolkit::ScrollView self = Dali::Toolkit::ScrollView::DownCast(Self());
812 // remove effect from effects list
813 bool effectExistedInScrollView(false);
814 for (ScrollViewEffectIter iter = mEffects.begin(); iter != mEffects.end(); ++iter)
818 mEffects.erase(iter);
819 effectExistedInScrollView = true;
824 // Assertion check to ensure effect existed.
825 DALI_ASSERT_ALWAYS(effectExistedInScrollView);
827 // invoke Detachment request to ScrollView last
828 GetImpl(effect).Detach(self);
831 void ScrollView::RemoveAllEffects()
833 Dali::Toolkit::ScrollView self = Dali::Toolkit::ScrollView::DownCast(Self());
835 for (ScrollViewEffectIter effectIter = mEffects.begin(); effectIter != mEffects.end(); ++effectIter)
837 Toolkit::ScrollViewEffect effect = *effectIter;
839 // invoke Detachment request to ScrollView last
840 GetImpl(effect).Detach(self);
846 void ScrollView::ApplyConstraintToChildren(Constraint constraint)
848 ApplyConstraintToBoundActors(constraint);
851 void ScrollView::RemoveConstraintsFromChildren()
853 RemoveConstraintsFromBoundActors();
856 const RulerPtr ScrollView::GetRulerX() const
861 const RulerPtr ScrollView::GetRulerY() const
866 void ScrollView::SetRulerX(RulerPtr ruler)
870 UpdatePropertyDomain();
871 UpdateMainInternalConstraint();
874 void ScrollView::SetRulerY(RulerPtr ruler)
878 UpdatePropertyDomain();
879 UpdateMainInternalConstraint();
882 void ScrollView::UpdatePropertyDomain()
885 Vector3 size = self.GetTargetSize();
886 Vector2 min = mMinScroll;
887 Vector2 max = mMaxScroll;
888 bool scrollPositionChanged = false;
889 bool domainChanged = false;
891 bool canScrollVertical = false;
892 bool canScrollHorizontal = false;
893 UpdateLocalScrollProperties();
894 if(mRulerX->IsEnabled())
896 const Toolkit::RulerDomain& rulerDomain = mRulerX->GetDomain();
897 if( fabsf(min.x - rulerDomain.min) > Math::MACHINE_EPSILON_100
898 || fabsf(max.x - rulerDomain.max) > Math::MACHINE_EPSILON_100 )
900 domainChanged = true;
901 min.x = rulerDomain.min;
902 max.x = rulerDomain.max;
904 // make sure new scroll value is within new domain
905 if( mScrollPrePosition.x < min.x
906 || mScrollPrePosition.x > max.x )
908 scrollPositionChanged = true;
909 mScrollPrePosition.x = Clamp(mScrollPrePosition.x, -(max.x - size.x), -min.x);
912 if( (fabsf(rulerDomain.max - rulerDomain.min) - size.x) > Math::MACHINE_EPSILON_100 )
914 canScrollHorizontal = true;
917 else if( fabs(min.x) > Math::MACHINE_EPSILON_100
918 || fabs(max.x) > Math::MACHINE_EPSILON_100 )
920 // need to reset to 0
921 domainChanged = true;
924 canScrollHorizontal = false;
927 if(mRulerY->IsEnabled())
929 const Toolkit::RulerDomain& rulerDomain = mRulerY->GetDomain();
930 if( fabsf(min.y - rulerDomain.min) > Math::MACHINE_EPSILON_100
931 || fabsf(max.y - rulerDomain.max) > Math::MACHINE_EPSILON_100 )
933 domainChanged = true;
934 min.y = rulerDomain.min;
935 max.y = rulerDomain.max;
937 // make sure new scroll value is within new domain
938 if( mScrollPrePosition.y < min.y
939 || mScrollPrePosition.y > max.y )
941 scrollPositionChanged = true;
942 mScrollPrePosition.y = Clamp(mScrollPrePosition.y, -(max.y - size.y), -min.y);
945 if( (fabsf(rulerDomain.max - rulerDomain.min) - size.y) > Math::MACHINE_EPSILON_100 )
947 canScrollVertical = true;
950 else if( fabs(min.y) > Math::MACHINE_EPSILON_100
951 || fabs(max.y) > Math::MACHINE_EPSILON_100 )
953 // need to reset to 0
954 domainChanged = true;
957 canScrollVertical = false;
960 // avoid setting properties if possible, otherwise this will cause an entire update as well as triggering constraints using each property we update
961 if( mCanScrollVertical != canScrollVertical )
963 mCanScrollVertical = canScrollVertical;
964 self.SetProperty(Toolkit::Scrollable::Property::CAN_SCROLL_VERTICAL, canScrollVertical);
966 if( mCanScrollHorizontal != canScrollHorizontal )
968 mCanScrollHorizontal = canScrollHorizontal;
969 self.SetProperty(Toolkit::Scrollable::Property::CAN_SCROLL_HORIZONTAL, canScrollHorizontal);
971 if( scrollPositionChanged )
973 DALI_LOG_SCROLL_STATE("[0x%X] Domain Changed, setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y );
974 self.SetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, mScrollPrePosition);
980 self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MIN, mMinScroll );
981 self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX, mMaxScroll );
985 bool ScrollView::GetScrollSensitive()
990 void ScrollView::SetScrollSensitive(bool sensitive)
993 PanGestureDetector panGesture( GetPanGestureDetector() );
995 DALI_LOG_SCROLL_STATE("[0x%X] sensitive: before:[%d] setting[%d]", this, int(mSensitive), int(sensitive));
997 if((!mSensitive) && (sensitive))
999 mSensitive = sensitive;
1000 panGesture.Attach(self);
1002 else if((mSensitive) && (!sensitive))
1004 DALI_LOG_SCROLL_STATE("[0x%X] BEFORE: panning:[%d]", this, int(mPanning));
1006 // while the scroll view is panning, the state needs to be reset.
1009 PanGesture cancelGesture = DevelPanGesture::New( GestureState::CANCELLED );
1010 OnPan( cancelGesture );
1013 panGesture.Detach(self);
1014 mSensitive = sensitive;
1016 mGestureStackDepth = 0;
1017 DALI_LOG_SCROLL_STATE("[0x%X] AFTER: panning:[%d]", this, int(mPanning));
1021 void ScrollView::SetMaxOvershoot(float overshootX, float overshootY)
1023 mMaxOvershoot.x = overshootX;
1024 mMaxOvershoot.y = overshootY;
1025 mUserMaxOvershoot = mMaxOvershoot;
1026 mDefaultMaxOvershoot = false;
1027 UpdateMainInternalConstraint();
1030 void ScrollView::SetSnapOvershootAlphaFunction(AlphaFunction alpha)
1032 mSnapOvershootAlphaFunction = alpha;
1035 float ScrollView::GetSnapOvershootDuration()
1037 return mSnapOvershootDuration;
1040 void ScrollView::SetSnapOvershootDuration(float duration)
1042 mSnapOvershootDuration = duration;
1045 bool ScrollView::GetActorAutoSnap()
1047 return mActorAutoSnapEnabled;
1050 void ScrollView::SetActorAutoSnap(bool enable)
1052 mActorAutoSnapEnabled = enable;
1055 void ScrollView::SetAutoResize(bool enable)
1057 mAutoResizeContainerEnabled = enable;
1058 // TODO: This needs a lot of issues to be addressed before working.
1061 bool ScrollView::GetWrapMode() const
1066 void ScrollView::SetWrapMode(bool enable)
1069 Self().SetProperty(Toolkit::ScrollView::Property::WRAP, enable);
1072 int ScrollView::GetScrollUpdateDistance() const
1074 return mScrollUpdateDistance;
1077 void ScrollView::SetScrollUpdateDistance(int distance)
1079 mScrollUpdateDistance = distance;
1082 bool ScrollView::GetAxisAutoLock() const
1084 return mAxisAutoLock;
1087 void ScrollView::SetAxisAutoLock(bool enable)
1089 mAxisAutoLock = enable;
1090 UpdateMainInternalConstraint();
1093 float ScrollView::GetAxisAutoLockGradient() const
1095 return mAxisAutoLockGradient;
1098 void ScrollView::SetAxisAutoLockGradient(float gradient)
1100 DALI_ASSERT_DEBUG( gradient >= 0.0f && gradient <= 1.0f );
1101 mAxisAutoLockGradient = gradient;
1102 UpdateMainInternalConstraint();
1105 float ScrollView::GetFrictionCoefficient() const
1107 return mFrictionCoefficient;
1110 void ScrollView::SetFrictionCoefficient(float friction)
1112 DALI_ASSERT_DEBUG( friction > 0.0f );
1113 mFrictionCoefficient = friction;
1116 float ScrollView::GetFlickSpeedCoefficient() const
1118 return mFlickSpeedCoefficient;
1121 void ScrollView::SetFlickSpeedCoefficient(float speed)
1123 mFlickSpeedCoefficient = speed;
1126 Vector2 ScrollView::GetMinimumDistanceForFlick() const
1128 return mMinFlickDistance;
1131 void ScrollView::SetMinimumDistanceForFlick( const Vector2& distance )
1133 mMinFlickDistance = distance;
1136 float ScrollView::GetMinimumSpeedForFlick() const
1138 return mFlickSpeedThreshold;
1141 void ScrollView::SetMinimumSpeedForFlick( float speed )
1143 mFlickSpeedThreshold = speed;
1146 float ScrollView::GetMaxFlickSpeed() const
1148 return mMaxFlickSpeed;
1151 void ScrollView::SetMaxFlickSpeed(float speed)
1153 mMaxFlickSpeed = speed;
1156 void ScrollView::SetWheelScrollDistanceStep(Vector2 step)
1158 mWheelScrollDistanceStep = step;
1161 Vector2 ScrollView::GetWheelScrollDistanceStep() const
1163 return mWheelScrollDistanceStep;
1166 unsigned int ScrollView::GetCurrentPage() const
1168 // in case animation is currently taking place.
1169 Vector2 position = GetPropertyPosition();
1171 Actor self = Self();
1172 unsigned int page = 0;
1173 unsigned int pagesPerVolume = 1;
1174 unsigned int volume = 0;
1176 // if rulerX is enabled, then get page count (columns)
1177 page = mRulerX->GetPageFromPosition(-position.x, mWrapMode);
1178 volume = mRulerY->GetPageFromPosition(-position.y, mWrapMode);
1179 pagesPerVolume = mRulerX->GetTotalPages();
1181 return volume * pagesPerVolume + page;
1184 Vector2 ScrollView::GetCurrentScrollPosition() const
1186 return -GetPropertyPosition();
1189 void ScrollView::TransformTo(const Vector2& position,
1190 DirectionBias horizontalBias, DirectionBias verticalBias)
1192 TransformTo(position, mSnapDuration, mSnapAlphaFunction, horizontalBias, verticalBias);
1195 void ScrollView::TransformTo(const Vector2& position, float duration, AlphaFunction alpha,
1196 DirectionBias horizontalBias, DirectionBias verticalBias)
1198 // If this is called while the timer is running, then cancel it
1199 StopTouchDownTimer();
1201 Actor self( Self() );
1203 // Guard against destruction during signal emission
1204 // Note that Emit() methods are called indirectly e.g. from within ScrollView::AnimateTo()
1205 Toolkit::ScrollView handle( GetOwner() );
1207 DALI_LOG_SCROLL_STATE("[0x%X] pos[%.2f,%.2f], duration[%.2f] bias[%d, %d]",
1208 this, position.x, position.y, duration, int(horizontalBias), int(verticalBias));
1210 Vector2 currentScrollPosition = GetCurrentScrollPosition();
1211 self.SetProperty( Toolkit::ScrollView::Property::START_PAGE_POSITION, Vector3(currentScrollPosition) );
1213 if( mScrolling ) // are we interrupting a current scroll?
1215 // set mScrolling to false, in case user has code that interrogates mScrolling Getter() in complete.
1217 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignal 1 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
1218 mScrollCompletedSignal.Emit( currentScrollPosition );
1221 if( mPanning ) // are we interrupting a current pan?
1223 DALI_LOG_SCROLL_STATE("[0x%X] Interrupting Pan, set to false", this );
1225 mGestureStackDepth = 0;
1226 self.SetProperty( Toolkit::ScrollView::Property::PANNING, false );
1228 if( mScrollMainInternalPrePositionConstraint )
1230 mScrollMainInternalPrePositionConstraint.Remove();
1234 self.SetProperty(Toolkit::ScrollView::Property::SCROLLING, true);
1237 DALI_LOG_SCROLL_STATE("[0x%X] mScrollStartedSignal 1 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
1238 mScrollStartedSignal.Emit( currentScrollPosition );
1239 bool animating = AnimateTo(-position,
1240 Vector2::ONE * duration,
1249 // if not animating, then this pan has completed right now.
1250 self.SetProperty(Toolkit::ScrollView::Property::SCROLLING, false);
1253 // If we have no duration, then in the next update frame, we will be at the position specified as we just set.
1254 // In this scenario, we cannot return the currentScrollPosition as this is out-of-date and should instead return the requested final position
1255 Vector2 completedPosition( currentScrollPosition );
1256 if( duration <= Math::MACHINE_EPSILON_10 )
1258 completedPosition = position;
1261 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignal 2 [%.2f, %.2f]", this, completedPosition.x, completedPosition.y);
1262 SetScrollUpdateNotification(false);
1263 mScrollCompletedSignal.Emit( completedPosition );
1267 void ScrollView::ScrollTo(const Vector2& position)
1269 ScrollTo(position, mSnapDuration );
1272 void ScrollView::ScrollTo(const Vector2& position, float duration)
1274 ScrollTo(position, duration, DIRECTION_BIAS_NONE, DIRECTION_BIAS_NONE);
1277 void ScrollView::ScrollTo(const Vector2& position, float duration, AlphaFunction alpha)
1279 ScrollTo(position, duration, alpha, DIRECTION_BIAS_NONE, DIRECTION_BIAS_NONE);
1282 void ScrollView::ScrollTo(const Vector2& position, float duration,
1283 DirectionBias horizontalBias, DirectionBias verticalBias)
1285 ScrollTo(position, duration, mSnapAlphaFunction, horizontalBias, verticalBias);
1288 void ScrollView::ScrollTo(const Vector2& position, float duration, AlphaFunction alpha,
1289 DirectionBias horizontalBias, DirectionBias verticalBias)
1291 DALI_LOG_SCROLL_STATE("[0x%X] position[%.2f, %.2f] duration[%.2f], bias[%d, %d]", this, position.x, position.y, duration, int(horizontalBias), int(verticalBias));
1292 TransformTo(position, duration, alpha, horizontalBias, verticalBias);
1295 void ScrollView::ScrollTo(unsigned int page)
1297 ScrollTo(page, mSnapDuration);
1300 void ScrollView::ScrollTo(unsigned int page, float duration, DirectionBias bias)
1303 unsigned int volume;
1304 unsigned int libraries;
1306 // The position to scroll to is continuous and linear
1307 // unless a domain has been enabled on the X axis.
1308 // or if WrapMode has been enabled.
1309 bool carryX = mRulerX->GetDomain().enabled | mWrapMode;
1310 bool carryY = mRulerY->GetDomain().enabled | mWrapMode;
1312 position.x = mRulerX->GetPositionFromPage(page, volume, carryX);
1313 position.y = mRulerY->GetPositionFromPage(volume, libraries, carryY);
1315 ScrollTo(position, duration, bias, bias);
1318 void ScrollView::ScrollTo(Actor &actor)
1320 ScrollTo(actor, mSnapDuration);
1323 void ScrollView::ScrollTo(Actor &actor, float duration)
1325 DALI_ASSERT_ALWAYS(actor.GetParent() == Self());
1327 Actor self = Self();
1328 Vector3 size = self.GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
1329 Vector3 position = actor.GetCurrentProperty< Vector3 >( Actor::Property::POSITION );
1330 Vector2 prePosition = GetPropertyPrePosition();
1331 position.GetVectorXY() -= prePosition;
1333 ScrollTo(Vector2(position.x - size.width * 0.5f, position.y - size.height * 0.5f), duration);
1336 Actor ScrollView::FindClosestActor()
1338 Actor self = Self();
1339 Vector3 size = self.GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
1341 return FindClosestActorToPosition(Vector3(size.width * 0.5f,size.height * 0.5f,0.0f));
1344 Actor ScrollView::FindClosestActorToPosition(const Vector3& position, FindDirection dirX, FindDirection dirY, FindDirection dirZ)
1347 float closestDistance2 = 0.0f;
1348 Vector3 actualPosition = position;
1350 unsigned int numChildren = Self().GetChildCount();
1352 for(unsigned int i = 0; i < numChildren; ++i)
1354 Actor child = Self().GetChildAt(i);
1356 if(mInternalActor == child) // ignore internal actor.
1361 Vector3 childPosition = GetPositionOfAnchor(child, AnchorPoint::CENTER);
1363 Vector3 delta = childPosition - actualPosition;
1365 // X-axis checking (only find Actors to the [dirX] of actualPosition)
1366 if(dirX > All) // != All,None
1368 FindDirection deltaH = delta.x > 0 ? Right : Left;
1375 // Y-axis checking (only find Actors to the [dirY] of actualPosition)
1376 if(dirY > All) // != All,None
1378 FindDirection deltaV = delta.y > 0 ? Down : Up;
1385 // Z-axis checking (only find Actors to the [dirZ] of actualPosition)
1386 if(dirZ > All) // != All,None
1388 FindDirection deltaV = delta.y > 0 ? In : Out;
1395 // compare child to closest child in terms of distance.
1396 float distance2 = 0.0f;
1398 // distance2 = the Square of the relevant dimensions of delta
1401 distance2 += delta.x * delta.x;
1406 distance2 += delta.y * delta.y;
1411 distance2 += delta.z * delta.z;
1414 if(closestChild) // Next time.
1416 if(distance2 < closestDistance2)
1418 closestChild = child;
1419 closestDistance2 = distance2;
1424 closestChild = child;
1425 closestDistance2 = distance2;
1429 return closestChild;
1432 bool ScrollView::ScrollToSnapPoint()
1434 DALI_LOG_SCROLL_STATE("[0x%X]", this );
1435 Vector2 stationaryVelocity = Vector2(0.0f, 0.0f);
1436 return SnapWithVelocity( stationaryVelocity );
1439 // TODO: In situations where axes are different (X snap, Y free)
1440 // Each axis should really have their own independent animation (time and equation)
1441 // Consider, X axis snapping to nearest grid point (EaseOut over fixed time)
1442 // Consider, Y axis simulating physics to arrive at a point (Physics equation over variable time)
1443 // Currently, the axes have been split however, they both use the same EaseOut equation.
1444 bool ScrollView::SnapWithVelocity(Vector2 velocity)
1446 // Animator takes over now, touches are assumed not to interfere.
1447 // And if touches do interfere, then we'll stop animation, update PrePosition
1448 // to current mScroll's properties, and then resume.
1449 // Note: For Flicking this may work a bit different...
1451 float angle = atan2(velocity.y, velocity.x);
1452 float speed2 = velocity.LengthSquared();
1453 AlphaFunction alphaFunction = mSnapAlphaFunction;
1454 Vector2 positionDuration = Vector2::ONE * mSnapDuration;
1457 FindDirection horizontal = None;
1458 FindDirection vertical = None;
1460 // orthoAngleRange = Angle tolerance within the Exact N,E,S,W direction
1461 // that will be accepted as a general N,E,S,W flick direction.
1463 const float orthoAngleRange = FLICK_ORTHO_ANGLE_RANGE * M_PI / 180.0f;
1464 const float flickSpeedThreshold2 = mFlickSpeedThreshold * mFlickSpeedThreshold;
1466 Vector2 positionSnap = mScrollPrePosition;
1468 // Flick logic X Axis
1470 if(mRulerX->IsEnabled() && mLockAxis != LockHorizontal)
1474 if( speed2 > flickSpeedThreshold2 || // exceeds flick threshold
1475 mInAccessibilityPan ) // With AccessibilityPan its easier to move between snap positions
1477 if((angle >= -orthoAngleRange) && (angle < orthoAngleRange)) // Swiping East
1479 biasX = 0.0f, horizontal = Left;
1481 // This guards against an error where no movement occurs, due to the flick finishing
1482 // before the update-thread has advanced mScrollPostPosition past the the previous snap point.
1483 positionSnap.x += 1.0f;
1485 else if((angle >= M_PI-orthoAngleRange) || (angle < -M_PI+orthoAngleRange)) // Swiping West
1487 biasX = 1.0f, horizontal = Right;
1489 // This guards against an error where no movement occurs, due to the flick finishing
1490 // before the update-thread has advanced mScrollPostPosition past the the previous snap point.
1491 positionSnap.x -= 1.0f;
1496 // Flick logic Y Axis
1498 if(mRulerY->IsEnabled() && mLockAxis != LockVertical)
1502 if( speed2 > flickSpeedThreshold2 || // exceeds flick threshold
1503 mInAccessibilityPan ) // With AccessibilityPan its easier to move between snap positions
1505 if((angle >= M_PI_2-orthoAngleRange) && (angle < M_PI_2+orthoAngleRange)) // Swiping South
1507 biasY = 0.0f, vertical = Up;
1509 else if((angle >= -M_PI_2-orthoAngleRange) && (angle < -M_PI_2+orthoAngleRange)) // Swiping North
1511 biasY = 1.0f, vertical = Down;
1516 // isFlick: Whether this gesture is a flick or not.
1517 bool isFlick = (horizontal != All || vertical != All);
1518 // isFreeFlick: Whether this gesture is a flick under free panning criteria.
1519 bool isFreeFlick = velocity.LengthSquared() > (FREE_FLICK_SPEED_THRESHOLD*FREE_FLICK_SPEED_THRESHOLD);
1521 if(isFlick || isFreeFlick)
1523 positionDuration = Vector2::ONE * mFlickDuration;
1524 alphaFunction = mFlickAlphaFunction;
1527 // Calculate next positionSnap ////////////////////////////////////////////////////////////
1529 if(mActorAutoSnapEnabled)
1531 Vector3 size = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
1533 Actor child = FindClosestActorToPosition( Vector3(size.width * 0.5f,size.height * 0.5f,0.0f), horizontal, vertical );
1535 if(!child && isFlick )
1537 // If we conducted a direction limited search and found no actor, then just snap to the closest actor.
1538 child = FindClosestActorToPosition( Vector3(size.width * 0.5f,size.height * 0.5f,0.0f) );
1543 Vector2 position = Self().GetCurrentProperty<Vector2>( Toolkit::ScrollView::Property::SCROLL_POSITION );
1545 // Get center-point of the Actor.
1546 Vector3 childPosition = GetPositionOfAnchor(child, AnchorPoint::CENTER);
1548 if(mRulerX->IsEnabled())
1550 positionSnap.x = position.x - childPosition.x + size.width * 0.5f;
1552 if(mRulerY->IsEnabled())
1554 positionSnap.y = position.y - childPosition.y + size.height * 0.5f;
1559 Vector2 startPosition = positionSnap;
1560 positionSnap.x = -mRulerX->Snap(-positionSnap.x, biasX); // NOTE: X & Y rulers think in -ve coordinate system.
1561 positionSnap.y = -mRulerY->Snap(-positionSnap.y, biasY); // That is scrolling RIGHT (e.g. 100.0, 0.0) means moving LEFT.
1563 Vector2 clampDelta(Vector2::ZERO);
1564 ClampPosition(positionSnap);
1566 if( (mRulerX->GetType() == Ruler::FREE || mRulerY->GetType() == Ruler::FREE)
1567 && isFreeFlick && !mActorAutoSnapEnabled)
1569 // Calculate target position based on velocity of flick.
1571 // a = Deceleration (Set to diagonal stage length * friction coefficient)
1572 // u = Initial Velocity (Flick velocity)
1573 // v = 0 (Final Velocity)
1574 // t = Time (Velocity / Deceleration)
1575 Vector2 stageSize = Stage::GetCurrent().GetSize();
1576 float stageLength = Vector3(stageSize.x, stageSize.y, 0.0f).Length();
1577 float a = (stageLength * mFrictionCoefficient);
1578 Vector3 u = Vector3(velocity.x, velocity.y, 0.0f) * mFlickSpeedCoefficient;
1579 float speed = u.Length();
1582 // TODO: Change this to a decay function. (faster you flick, the slower it should be)
1583 speed = std::min(speed, stageLength * mMaxFlickSpeed );
1585 alphaFunction = ConstantDecelerationAlphaFunction;
1587 float t = speed / a;
1589 if(mRulerX->IsEnabled() && mRulerX->GetType() == Ruler::FREE)
1591 positionSnap.x += t*u.x*0.5f;
1594 if(mRulerY->IsEnabled() && mRulerY->GetType() == Ruler::FREE)
1596 positionSnap.y += t*u.y*0.5f;
1599 clampDelta = positionSnap;
1600 ClampPosition(positionSnap);
1601 if((positionSnap - startPosition).LengthSquared() > Math::MACHINE_EPSILON_0)
1603 clampDelta -= positionSnap;
1604 clampDelta.x = clampDelta.x > 0.0f ? std::min(clampDelta.x, mMaxOvershoot.x) : std::max(clampDelta.x, -mMaxOvershoot.x);
1605 clampDelta.y = clampDelta.y > 0.0f ? std::min(clampDelta.y, mMaxOvershoot.y) : std::max(clampDelta.y, -mMaxOvershoot.y);
1609 clampDelta = Vector2::ZERO;
1612 // If Axis is Free and has velocity, then calculate time taken
1613 // to reach target based on velocity in axis.
1614 if(mRulerX->IsEnabled() && mRulerX->GetType() == Ruler::FREE)
1616 float deltaX = fabsf(startPosition.x - positionSnap.x);
1618 if(fabsf(u.x) > Math::MACHINE_EPSILON_1)
1620 positionDuration.x = fabsf(deltaX / u.x);
1624 positionDuration.x = 0;
1628 if(mRulerY->IsEnabled() && mRulerY->GetType() == Ruler::FREE)
1630 float deltaY = fabsf(startPosition.y - positionSnap.y);
1632 if(fabsf(u.y) > Math::MACHINE_EPSILON_1)
1634 positionDuration.y = fabsf(deltaY / u.y);
1638 positionDuration.y = 0;
1643 if(IsOvershootEnabled())
1645 // Scroll to the end of the overshoot only when overshoot is enabled.
1646 positionSnap += clampDelta;
1649 bool animating = AnimateTo(positionSnap, positionDuration,
1650 alphaFunction, false,
1651 DIRECTION_BIAS_NONE, DIRECTION_BIAS_NONE,
1652 isFlick || isFreeFlick ? FLICK : SNAP);
1657 void ScrollView::StopAnimation(void)
1659 // Clear Snap animation if exists.
1660 StopAnimation(mInternalXAnimation);
1661 StopAnimation(mInternalYAnimation);
1662 mScrollStateFlags = 0;
1663 // remove scroll animation flags
1664 HandleStoppedAnimation();
1667 void ScrollView::StopAnimation(Animation& animation)
1676 bool ScrollView::AnimateTo(const Vector2& position, const Vector2& positionDuration,
1677 AlphaFunction alpha, bool findShortcuts,
1678 DirectionBias horizontalBias, DirectionBias verticalBias,
1681 // Here we perform an animation on a number of properties (depending on which have changed)
1682 // The animation is applied to all ScrollBases
1683 Actor self = Self();
1684 mScrollTargetPosition = position;
1685 float totalDuration = 0.0f;
1687 bool positionChanged = (mScrollTargetPosition != mScrollPostPosition);
1691 totalDuration = std::max(totalDuration, positionDuration.x);
1692 totalDuration = std::max(totalDuration, positionDuration.y);
1696 // try to animate for a frame, on some occasions update will be changing scroll value while event side thinks it hasnt changed
1697 totalDuration = 0.01f;
1698 positionChanged = true;
1703 // Position Delta ///////////////////////////////////////////////////////
1706 UpdateMainInternalConstraint();
1707 if(mWrapMode && findShortcuts)
1709 // In Wrap Mode, the shortest distance is a little less intuitive...
1710 const RulerDomain rulerDomainX = mRulerX->GetDomain();
1711 const RulerDomain rulerDomainY = mRulerY->GetDomain();
1713 if(mRulerX->IsEnabled())
1715 float dir = VectorInDomain(-mScrollPrePosition.x, -mScrollTargetPosition.x, rulerDomainX.min, rulerDomainX.max, horizontalBias);
1716 mScrollTargetPosition.x = mScrollPrePosition.x + -dir;
1719 if(mRulerY->IsEnabled())
1721 float dir = VectorInDomain(-mScrollPrePosition.y, -mScrollTargetPosition.y, rulerDomainY.min, rulerDomainY.max, verticalBias);
1722 mScrollTargetPosition.y = mScrollPrePosition.y + -dir;
1726 // note we have two separate animations for X & Y, this deals with sliding diagonally and hitting
1727 // a horizonal/vertical wall.delay
1728 AnimateInternalXTo(mScrollTargetPosition.x, positionDuration.x, alpha);
1729 AnimateInternalYTo(mScrollTargetPosition.y, positionDuration.y, alpha);
1731 if( !(mScrollStateFlags & SCROLL_ANIMATION_FLAGS) )
1733 DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollTargetPosition.x, mScrollTargetPosition.y );
1734 self.SetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, mScrollTargetPosition);
1735 mScrollPrePosition = mScrollTargetPosition;
1736 mScrollPostPosition = mScrollTargetPosition;
1737 WrapPosition(mScrollPostPosition);
1740 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 );
1741 DALI_LOG_SCROLL_STATE("[0x%X] SCROLL_PRE_POSITION[%.2f, %.2f], SCROLL_POSITION[%.2f, %.2f]", this, self.GetCurrentProperty( Toolkit::ScrollView::Property::SCROLL_PRE_POSITION ).Get<Vector2>().x, self.GetCurrentProperty( Toolkit::ScrollView::Property::SCROLL_PRE_POSITION ).Get<Vector2>().y, self.GetCurrentProperty( Toolkit::ScrollView::Property::SCROLL_POSITION ).Get<Vector2>().x, self.GetCurrentProperty( Toolkit::ScrollView::Property::SCROLL_POSITION ).Get<Vector2>().y );
1744 SetScrollUpdateNotification(true);
1746 // Always send a snap event when AnimateTo is called.
1747 Toolkit::ScrollView::SnapEvent snapEvent;
1748 snapEvent.type = snapType;
1749 snapEvent.position = -mScrollTargetPosition;
1750 snapEvent.duration = totalDuration;
1752 DALI_LOG_SCROLL_STATE("[0x%X] mSnapStartedSignal [%.2f, %.2f]", this, snapEvent.position.x, snapEvent.position.y);
1753 mSnapStartedSignal.Emit( snapEvent );
1755 return (mScrollStateFlags & SCROLL_ANIMATION_FLAGS) != 0;
1758 void ScrollView::EnableScrollOvershoot(bool enable)
1762 if (!mOvershootIndicator)
1764 mOvershootIndicator = ScrollOvershootIndicator::New();
1767 mOvershootIndicator->AttachToScrollable(*this);
1771 mMaxOvershoot = mUserMaxOvershoot;
1773 if (mOvershootIndicator)
1775 mOvershootIndicator->DetachFromScrollable(*this);
1779 UpdateMainInternalConstraint();
1782 void ScrollView::AddOverlay(Actor actor)
1784 actor.SetProperty( Actor::Property::DRAW_MODE, DrawMode::OVERLAY_2D );
1785 mInternalActor.Add( actor );
1788 void ScrollView::RemoveOverlay(Actor actor)
1790 mInternalActor.Remove( actor );
1793 void ScrollView::SetOvershootSize( const Vector2& size )
1795 mOvershootSize = size;
1796 if( IsOvershootEnabled() && mOvershootIndicator )
1798 mOvershootIndicator->AttachToScrollable(*this);
1802 void ScrollView::SetOvershootEffectColor( const Vector4& color )
1804 mOvershootEffectColor = color;
1805 if( mOvershootIndicator )
1807 mOvershootIndicator->SetOvershootEffectColor( color );
1811 void ScrollView::SetScrollingDirection( Radian direction, Radian threshold )
1813 PanGestureDetector panGesture( GetPanGestureDetector() );
1815 // First remove just in case we have some set, then add.
1816 panGesture.RemoveDirection( direction );
1817 panGesture.AddDirection( direction, threshold );
1820 void ScrollView::RemoveScrollingDirection( Radian direction )
1822 PanGestureDetector panGesture( GetPanGestureDetector() );
1823 panGesture.RemoveDirection( direction );
1826 Toolkit::ScrollView::SnapStartedSignalType& ScrollView::SnapStartedSignal()
1828 return mSnapStartedSignal;
1831 void ScrollView::FindAndUnbindActor(Actor child)
1836 Vector2 ScrollView::GetPropertyPrePosition() const
1838 Vector2 position = Self().GetCurrentProperty< Vector2 >( Toolkit::ScrollView::Property::SCROLL_PRE_POSITION );
1839 WrapPosition(position);
1843 Vector2 ScrollView::GetPropertyPosition() const
1845 Vector2 position = Self().GetCurrentProperty< Vector2 >( Toolkit::ScrollView::Property::SCROLL_POSITION );
1846 WrapPosition(position);
1851 void ScrollView::HandleStoppedAnimation()
1853 SetScrollUpdateNotification(false);
1856 void ScrollView::HandleSnapAnimationFinished()
1858 // Emit Signal that scrolling has completed.
1860 Actor self = Self();
1861 self.SetProperty(Toolkit::ScrollView::Property::SCROLLING, false);
1863 Vector2 deltaPosition(mScrollPrePosition);
1865 UpdateLocalScrollProperties();
1866 WrapPosition(mScrollPrePosition);
1867 DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y );
1868 self.SetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, mScrollPrePosition);
1870 Vector2 currentScrollPosition = GetCurrentScrollPosition();
1871 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignal 3 current[%.2f, %.2f], mScrollTargetPosition[%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y, -mScrollTargetPosition.x, -mScrollTargetPosition.y );
1872 mScrollCompletedSignal.Emit( currentScrollPosition );
1874 mDomainOffset += deltaPosition - mScrollPostPosition;
1875 self.SetProperty(Toolkit::ScrollView::Property::SCROLL_DOMAIN_OFFSET, mDomainOffset);
1876 HandleStoppedAnimation();
1879 void ScrollView::SetScrollUpdateNotification( bool enabled )
1881 Actor self = Self();
1882 if( mScrollXUpdateNotification )
1884 // disconnect now to avoid a notification before removed from update thread
1885 mScrollXUpdateNotification.NotifySignal().Disconnect(this, &ScrollView::OnScrollUpdateNotification);
1886 self.RemovePropertyNotification(mScrollXUpdateNotification);
1887 mScrollXUpdateNotification.Reset();
1889 if( enabled && !mScrollUpdatedSignal.Empty())
1891 // Only set up the notification when the application has connected to the updated signal
1892 mScrollXUpdateNotification = self.AddPropertyNotification(Toolkit::ScrollView::Property::SCROLL_POSITION, 0, StepCondition(mScrollUpdateDistance, 0.0f));
1893 mScrollXUpdateNotification.NotifySignal().Connect( this, &ScrollView::OnScrollUpdateNotification );
1895 if( mScrollYUpdateNotification )
1897 // disconnect now to avoid a notification before removed from update thread
1898 mScrollYUpdateNotification.NotifySignal().Disconnect(this, &ScrollView::OnScrollUpdateNotification);
1899 self.RemovePropertyNotification(mScrollYUpdateNotification);
1900 mScrollYUpdateNotification.Reset();
1902 if( enabled && !mScrollUpdatedSignal.Empty())
1904 // Only set up the notification when the application has connected to the updated signal
1905 mScrollYUpdateNotification = self.AddPropertyNotification(Toolkit::ScrollView::Property::SCROLL_POSITION, 1, StepCondition(mScrollUpdateDistance, 0.0f));
1906 mScrollYUpdateNotification.NotifySignal().Connect( this, &ScrollView::OnScrollUpdateNotification );
1910 void ScrollView::OnScrollUpdateNotification(Dali::PropertyNotification& source)
1912 // Guard against destruction during signal emission
1913 Toolkit::ScrollView handle( GetOwner() );
1915 Vector2 currentScrollPosition = GetCurrentScrollPosition();
1916 mScrollUpdatedSignal.Emit( currentScrollPosition );
1919 bool ScrollView::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
1921 Dali::BaseHandle handle( object );
1923 bool connected( true );
1924 Toolkit::ScrollView view = Toolkit::ScrollView::DownCast( handle );
1926 if( 0 == strcmp( signalName.c_str(), SIGNAL_SNAP_STARTED ) )
1928 view.SnapStartedSignal().Connect( tracker, functor );
1932 // signalName does not match any signal
1939 void ScrollView::OnSizeAnimation(Animation& animation, const Vector3& targetSize)
1941 // need to update domain properties for new size
1942 UpdatePropertyDomain();
1945 void ScrollView::OnSizeSet( const Vector3& size )
1947 // need to update domain properties for new size
1948 if( mDefaultMaxOvershoot )
1950 mUserMaxOvershoot.x = size.x * 0.5f;
1951 mUserMaxOvershoot.y = size.y * 0.5f;
1952 if( !IsOvershootEnabled() )
1954 mMaxOvershoot = mUserMaxOvershoot;
1957 UpdatePropertyDomain();
1958 UpdateMainInternalConstraint();
1959 if( IsOvershootEnabled() )
1961 mOvershootIndicator->Reset();
1964 ScrollBase::OnSizeSet( size );
1967 void ScrollView::OnChildAdd(Actor& child)
1969 ScrollBase::OnChildAdd( child );
1971 Dali::Toolkit::ScrollBar scrollBar = Dali::Toolkit::ScrollBar::DownCast(child);
1974 mScrollBar = scrollBar;
1975 scrollBar.SetProperty( Dali::Actor::Property::NAME,"ScrollBar");
1977 mInternalActor.Add( scrollBar );
1978 if( scrollBar.GetScrollDirection() == Toolkit::ScrollBar::HORIZONTAL )
1980 scrollBar.SetScrollPropertySource( Self(),
1981 Toolkit::ScrollView::Property::SCROLL_PRE_POSITION_X,
1982 Toolkit::Scrollable::Property::SCROLL_POSITION_MIN_X,
1983 Toolkit::ScrollView::Property::SCROLL_PRE_POSITION_MAX_X,
1984 Toolkit::ScrollView::Property::SCROLL_DOMAIN_SIZE_X );
1988 scrollBar.SetScrollPropertySource( Self(),
1989 Toolkit::ScrollView::Property::SCROLL_PRE_POSITION_Y,
1990 Toolkit::Scrollable::Property::SCROLL_POSITION_MIN_Y,
1991 Toolkit::ScrollView::Property::SCROLL_PRE_POSITION_MAX_Y,
1992 Toolkit::ScrollView::Property::SCROLL_DOMAIN_SIZE_Y );
1995 if( mTransientScrollBar )
1997 // Show the scroll-indicator for a brief period
1998 Property::Map emptyMap;
1999 scrollBar.DoAction( "ShowTransientIndicator", emptyMap );
2002 else if(mAlterChild)
2008 void ScrollView::OnChildRemove(Actor& child)
2010 // TODO: Actor needs a RemoveConstraint method to take out an individual constraint.
2013 ScrollBase::OnChildRemove( child );
2016 void ScrollView::StartTouchDownTimer()
2018 if ( !mTouchDownTimer )
2020 mTouchDownTimer = Timer::New( TOUCH_DOWN_TIMER_INTERVAL );
2021 mTouchDownTimer.TickSignal().Connect( this, &ScrollView::OnTouchDownTimeout );
2024 mTouchDownTimer.Start();
2027 void ScrollView::StopTouchDownTimer()
2029 if ( mTouchDownTimer )
2031 mTouchDownTimer.Stop();
2035 bool ScrollView::OnTouchDownTimeout()
2037 DALI_LOG_SCROLL_STATE("[0x%X]", this);
2039 mTouchDownTimeoutReached = true;
2041 unsigned int currentScrollStateFlags( mScrollStateFlags ); // Cleared in StopAnimation so keep local copy for comparison
2042 if( currentScrollStateFlags & (SCROLL_ANIMATION_FLAGS | SNAP_ANIMATION_FLAGS) )
2044 DALI_LOG_SCROLL_STATE("[0x%X] Scrolling Or snapping flags set, stopping animation", this);
2047 if( currentScrollStateFlags & SCROLL_ANIMATION_FLAGS )
2049 DALI_LOG_SCROLL_STATE("[0x%X] Scrolling flags set, emitting signal", this);
2051 mScrollInterrupted = true;
2052 // reset domain offset as scrolling from original plane.
2053 mDomainOffset = Vector2::ZERO;
2054 Self().SetProperty(Toolkit::ScrollView::Property::SCROLL_DOMAIN_OFFSET, Vector2::ZERO);
2056 UpdateLocalScrollProperties();
2057 Vector2 currentScrollPosition = GetCurrentScrollPosition();
2058 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignal 4 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
2059 mScrollCompletedSignal.Emit( currentScrollPosition );
2066 bool ScrollView::OnTouch( Actor actor, const TouchEvent& touch )
2070 DALI_LOG_SCROLL_STATE("[0x%X], Not Sensitive, ignoring", this);
2072 // Ignore this touch event, if scrollview is insensitive.
2076 // Ignore events with multiple-touch points
2077 if (touch.GetPointCount() != 1)
2079 DALI_LOG_SCROLL_STATE("[0x%X], multiple touch, ignoring", this);
2084 const PointState::Type pointState = touch.GetState( 0 );
2085 if( pointState == PointState::DOWN )
2087 DALI_LOG_SCROLL_STATE("[0x%X] Down", this);
2089 if(mGestureStackDepth==0)
2091 mTouchDownTime = touch.GetTime();
2093 // This allows time for a pan-gesture to start, to avoid breaking snap-animation behavior with fast flicks.
2094 // If touch-down does not become a pan (after timeout interval), then snap-animation can be interrupted.
2095 mTouchDownTimeoutReached = false;
2096 mScrollInterrupted = false;
2097 StartTouchDownTimer();
2100 else if( ( pointState == PointState::UP ) ||
2101 ( ( pointState == PointState::INTERRUPTED ) && ( touch.GetHitActor( 0 )== Self() ) ) )
2103 DALI_LOG_SCROLL_STATE("[0x%X] %s", this, ( ( pointState == PointState::UP ) ? "Up" : "Interrupted" ) );
2105 StopTouchDownTimer();
2107 // if the user touches and releases without enough movement to go
2108 // into a gesture state, then we should snap to nearest point.
2109 // otherwise our scroll could be stopped (interrupted) half way through an animation.
2110 if(mGestureStackDepth==0 && mTouchDownTimeoutReached)
2112 if( ( pointState == PointState::INTERRUPTED ) ||
2113 ( ( touch.GetTime() - mTouchDownTime ) >= MINIMUM_TIME_BETWEEN_DOWN_AND_UP_FOR_RESET ) )
2115 // Reset the velocity only if down was received a while ago
2116 mLastVelocity = Vector2( 0.0f, 0.0f );
2119 UpdateLocalScrollProperties();
2120 // Only finish the transform if scrolling was interrupted on down or if we are scrolling
2121 if ( mScrollInterrupted || mScrolling )
2123 DALI_LOG_SCROLL_STATE("[0x%X] Calling FinishTransform", this);
2128 mTouchDownTimeoutReached = false;
2129 mScrollInterrupted = false;
2135 bool ScrollView::OnWheelEvent( Actor actor, const WheelEvent& event)
2139 // Ignore this wheel event, if scrollview is insensitive.
2143 Vector2 targetScrollPosition = GetPropertyPosition();
2145 if(mRulerX->IsEnabled() && !mRulerY->IsEnabled())
2147 // If only the ruler in the X axis is enabled, scroll in the X axis.
2148 if(mRulerX->GetType() == Ruler::FREE)
2150 // Free panning mode
2151 targetScrollPosition.x += event.GetDelta() * mWheelScrollDistanceStep.x;
2152 ClampPosition(targetScrollPosition);
2153 ScrollTo(-targetScrollPosition);
2155 else if(!mScrolling)
2157 // Snap mode, only respond to the event when the previous snap animation is finished.
2158 ScrollTo(GetCurrentPage() - event.GetDelta());
2163 // If the ruler in the Y axis is enabled, scroll in the Y axis.
2164 if(mRulerY->GetType() == Ruler::FREE)
2166 // Free panning mode
2167 targetScrollPosition.y += event.GetDelta() * mWheelScrollDistanceStep.y;
2168 ClampPosition(targetScrollPosition);
2169 ScrollTo(-targetScrollPosition);
2171 else if(!mScrolling)
2173 // Snap mode, only respond to the event when the previous snap animation is finished.
2174 ScrollTo(GetCurrentPage() - event.GetDelta() * mRulerX->GetTotalPages());
2181 void ScrollView::ResetScrolling()
2183 Actor self = Self();
2184 self.GetCurrentProperty( Toolkit::ScrollView::Property::SCROLL_POSITION ).Get( mScrollPostPosition );
2185 mScrollPrePosition = mScrollPostPosition;
2186 DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPostPosition.x, mScrollPostPosition.y );
2187 self.SetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, mScrollPostPosition);
2190 void ScrollView::UpdateLocalScrollProperties()
2192 Actor self = Self();
2193 self.GetCurrentProperty( Toolkit::ScrollView::Property::SCROLL_PRE_POSITION ).Get( mScrollPrePosition );
2194 self.GetCurrentProperty( Toolkit::ScrollView::Property::SCROLL_POSITION ).Get( mScrollPostPosition );
2197 // private functions
2199 void ScrollView::PreAnimatedScrollSetup()
2201 // SCROLL_PRE_POSITION is our unclamped property with wrapping
2202 // SCROLL_POSITION is our final scroll position after clamping
2204 Actor self = Self();
2206 Vector2 deltaPosition(mScrollPostPosition);
2207 WrapPosition(mScrollPostPosition);
2208 mDomainOffset += deltaPosition - mScrollPostPosition;
2209 Self().SetProperty(Toolkit::ScrollView::Property::SCROLL_DOMAIN_OFFSET, mDomainOffset);
2211 if( mScrollStateFlags & SCROLL_X_STATE_MASK )
2213 // already performing animation on internal x position
2214 StopAnimation(mInternalXAnimation);
2217 if( mScrollStateFlags & SCROLL_Y_STATE_MASK )
2219 // already performing animation on internal y position
2220 StopAnimation(mInternalYAnimation);
2223 mScrollStateFlags = 0;
2225 // Update Actor position with this wrapped value.
2228 void ScrollView::FinaliseAnimatedScroll()
2230 // TODO - common animation finishing code in here
2233 void ScrollView::AnimateInternalXTo( float position, float duration, AlphaFunction alpha )
2235 StopAnimation(mInternalXAnimation);
2237 if( duration > Math::MACHINE_EPSILON_10 )
2239 Actor self = Self();
2240 DALI_LOG_SCROLL_STATE("[0x%X], Animating from[%.2f] to[%.2f]", this, self.GetCurrentProperty( Toolkit::ScrollView::Property::SCROLL_PRE_POSITION ).Get< Vector2 >().x, position );
2241 mInternalXAnimation = Animation::New(duration);
2242 DALI_LOG_SCROLL_STATE("[0x%X], mInternalXAnimation[0x%X]", this, mInternalXAnimation.GetObjectPtr() );
2243 mInternalXAnimation.FinishedSignal().Connect(this, &ScrollView::OnScrollAnimationFinished);
2244 mInternalXAnimation.AnimateTo( Property(self, Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, 0), position, alpha, TimePeriod(duration));
2245 mInternalXAnimation.Play();
2247 // erase current state flags
2248 mScrollStateFlags &= ~SCROLL_X_STATE_MASK;
2249 // add internal animation state flag
2250 mScrollStateFlags |= AnimatingInternalX;
2254 void ScrollView::AnimateInternalYTo( float position, float duration, AlphaFunction alpha )
2256 StopAnimation(mInternalYAnimation);
2258 if( duration > Math::MACHINE_EPSILON_10 )
2260 Actor self = Self();
2261 DALI_LOG_SCROLL_STATE("[0x%X], Animating from[%.2f] to[%.2f]", this, self.GetCurrentProperty( Toolkit::ScrollView::Property::SCROLL_PRE_POSITION ).Get< Vector2 >().y, position );
2262 mInternalYAnimation = Animation::New(duration);
2263 DALI_LOG_SCROLL_STATE("[0x%X], mInternalYAnimation[0x%X]", this, mInternalYAnimation.GetObjectPtr() );
2264 mInternalYAnimation.FinishedSignal().Connect(this, &ScrollView::OnScrollAnimationFinished);
2265 mInternalYAnimation.AnimateTo( Property(self, Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, 1), position, alpha, TimePeriod(duration));
2266 mInternalYAnimation.Play();
2268 // erase current state flags
2269 mScrollStateFlags &= ~SCROLL_Y_STATE_MASK;
2270 // add internal animation state flag
2271 mScrollStateFlags |= AnimatingInternalY;
2275 void ScrollView::OnScrollAnimationFinished( Animation& source )
2277 // Guard against destruction during signal emission
2278 // Note that ScrollCompletedSignal is emitted from HandleSnapAnimationFinished()
2279 Toolkit::ScrollView handle( GetOwner() );
2281 bool scrollingFinished = false;
2283 // update our local scroll positions
2284 UpdateLocalScrollProperties();
2286 if( source == mInternalXAnimation )
2288 DALI_LOG_SCROLL_STATE("[0x%X] mInternalXAnimation[0x%X], expected[%.2f], actual[%.2f], post[%.2f]", this, mInternalXAnimation.GetObjectPtr(), mScrollTargetPosition.x, Self().GetCurrentProperty( SCROLL_PRE_POSITION ).Get< Vector2 >().x, mScrollPostPosition.x );
2290 if( !(mScrollStateFlags & AnimatingInternalY) )
2292 scrollingFinished = true;
2294 mInternalXAnimation.Reset();
2295 // wrap pre scroll x position and set it
2298 const RulerDomain rulerDomain = mRulerX->GetDomain();
2299 mScrollPrePosition.x = -WrapInDomain(-mScrollPrePosition.x, rulerDomain.min, rulerDomain.max);
2300 DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y );
2301 handle.SetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, mScrollPrePosition);
2303 SnapInternalXTo(mScrollPostPosition.x);
2306 if( source == mInternalYAnimation )
2308 DALI_LOG_SCROLL_STATE("[0x%X] mInternalYAnimation[0x%X], expected[%.2f], actual[%.2f], post[%.2f]", this, mInternalYAnimation.GetObjectPtr(), mScrollTargetPosition.y, DevelHandle::GetProperty( Self(), SCROLL_PRE_POSITION ).Get< Vector2 >().y, mScrollPostPosition.y );
2310 if( !(mScrollStateFlags & AnimatingInternalX) )
2312 scrollingFinished = true;
2314 mInternalYAnimation.Reset();
2317 // wrap pre scroll y position and set it
2318 const RulerDomain rulerDomain = mRulerY->GetDomain();
2319 mScrollPrePosition.y = -WrapInDomain(-mScrollPrePosition.y, rulerDomain.min, rulerDomain.max);
2320 DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y );
2321 handle.SetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, mScrollPrePosition);
2323 SnapInternalYTo(mScrollPostPosition.y);
2326 DALI_LOG_SCROLL_STATE("[0x%X] scrollingFinished[%d] Animation[0x%X]", this, scrollingFinished, source.GetObjectPtr());
2328 if(scrollingFinished)
2330 HandleSnapAnimationFinished();
2334 void ScrollView::OnSnapInternalPositionFinished( Animation& source )
2336 Actor self = Self();
2337 UpdateLocalScrollProperties();
2338 if( source == mInternalXAnimation )
2340 DALI_LOG_SCROLL_STATE("[0x%X] Finished X PostPosition Animation", this );
2342 // clear internal x animation flags
2343 mScrollStateFlags &= ~SCROLL_X_STATE_MASK;
2344 mInternalXAnimation.Reset();
2345 WrapPosition(mScrollPrePosition);
2347 if( source == mInternalYAnimation )
2349 DALI_LOG_SCROLL_STATE("[0x%X] Finished Y PostPosition Animation", this );
2351 mScrollStateFlags &= ~SCROLL_Y_STATE_MASK;
2352 mInternalYAnimation.Reset();
2353 WrapPosition(mScrollPrePosition);
2357 void ScrollView::SnapInternalXTo(float position)
2359 Actor self = Self();
2361 StopAnimation(mInternalXAnimation);
2363 // erase current state flags
2364 mScrollStateFlags &= ~SCROLL_X_STATE_MASK;
2366 // if internal x not equal to inputed parameter, animate it
2367 float duration = std::min(fabsf((position - mScrollPrePosition.x) / mMaxOvershoot.x) * mSnapOvershootDuration, mSnapOvershootDuration);
2368 DALI_LOG_SCROLL_STATE("[0x%X] duration[%.2f]", this, duration );
2369 if( duration > Math::MACHINE_EPSILON_1 )
2371 DALI_LOG_SCROLL_STATE("[0x%X] Starting X Snap Animation to[%.2f]", this, position );
2373 mInternalXAnimation = Animation::New(duration);
2374 mInternalXAnimation.FinishedSignal().Connect(this, &ScrollView::OnSnapInternalPositionFinished);
2375 mInternalXAnimation.AnimateTo(Property(self, Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, 0), position);
2376 mInternalXAnimation.Play();
2378 // add internal animation state flag
2379 mScrollStateFlags |= SnappingInternalX;
2383 void ScrollView::SnapInternalYTo(float position)
2385 Actor self = Self();
2387 StopAnimation(mInternalYAnimation);
2389 // erase current state flags
2390 mScrollStateFlags &= ~SCROLL_Y_STATE_MASK;
2392 // if internal y not equal to inputed parameter, animate it
2393 float duration = std::min(fabsf((position - mScrollPrePosition.y) / mMaxOvershoot.y) * mSnapOvershootDuration, mSnapOvershootDuration);
2394 DALI_LOG_SCROLL_STATE("[0x%X] duration[%.2f]", this, duration );
2395 if( duration > Math::MACHINE_EPSILON_1 )
2397 DALI_LOG_SCROLL_STATE("[0x%X] Starting Y Snap Animation to[%.2f]", this, position );
2399 mInternalYAnimation = Animation::New(duration);
2400 mInternalYAnimation.FinishedSignal().Connect(this, &ScrollView::OnSnapInternalPositionFinished);
2401 mInternalYAnimation.AnimateTo(Property(self, Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, 1), position);
2402 mInternalYAnimation.Play();
2404 // add internal animation state flag
2405 mScrollStateFlags |= SnappingInternalY;
2409 void ScrollView::GestureStarted()
2411 // we handle the first gesture.
2412 // if we're currently doing a gesture and receive another
2413 // we continue and combine the effects of the gesture instead of reseting.
2414 if(mGestureStackDepth++==0)
2416 Actor self = Self();
2417 StopTouchDownTimer();
2419 mPanDelta = Vector2::ZERO;
2420 mLastVelocity = Vector2::ZERO;
2423 mLockAxis = LockPossible;
2426 if( mScrollStateFlags & SCROLL_X_STATE_MASK )
2428 StopAnimation(mInternalXAnimation);
2430 if( mScrollStateFlags & SCROLL_Y_STATE_MASK )
2432 StopAnimation(mInternalYAnimation);
2434 mScrollStateFlags = 0;
2436 if(mScrolling) // are we interrupting a current scroll?
2438 // set mScrolling to false, in case user has code that interrogates mScrolling Getter() in complete.
2440 // send negative scroll position since scroll internal scroll position works as an offset for actors,
2441 // give applications the position within the domain from the scroll view's anchor position
2442 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignal 5 [%.2f, %.2f]", this, -mScrollPostPosition.x, -mScrollPostPosition.y);
2443 mScrollCompletedSignal.Emit( -mScrollPostPosition );
2448 void ScrollView::GestureContinuing(const Vector2& panDelta)
2450 mPanDelta.x+= panDelta.x;
2451 mPanDelta.y+= panDelta.y;
2453 // Save the velocity, there is a bug in PanGesture
2454 // Whereby the GestureState::FINISHED's velocity is either:
2455 // NaN (due to time delta of zero between the last two events)
2456 // or 0 (due to position being the same between the last two events)
2458 // Axis Auto Lock - locks the panning to the horizontal or vertical axis if the pan
2459 // appears mostly horizontal or mostly vertical respectively.
2462 mLockAxis = GetLockAxis(mPanDelta, mLockAxis, mAxisAutoLockGradient);
2463 } // end if mAxisAutoLock
2466 // TODO: Upgrade to use a more powerful gesture detector (one that supports multiple touches on pan - so works as pan and flick gesture)
2467 // BUG: GestureState::FINISHED doesn't always return velocity on release (due to
2468 // timeDelta between last two events being 0 sometimes, or posiiton being the same)
2469 void ScrollView::OnPan( const PanGesture& gesture )
2471 // Guard against destruction during signal emission
2472 // Note that Emit() methods are called indirectly e.g. from within ScrollView::OnGestureEx()
2473 Actor self( Self() );
2477 DALI_LOG_SCROLL_STATE("[0x%X] Pan Ignored, Insensitive", this);
2479 // If another callback on the same original signal disables sensitivity,
2480 // this callback will still be called, so we must suppress it.
2484 // translate Gesture input to get useful data...
2485 switch(gesture.GetState())
2487 case GestureState::STARTED:
2489 DALI_LOG_SCROLL_STATE("[0x%X] Pan Started", this);
2490 const Vector2& position = gesture.GetPosition();
2491 mPanStartPosition = position - gesture.GetDisplacement();
2492 UpdateLocalScrollProperties();
2495 self.SetProperty( Toolkit::ScrollView::Property::PANNING, true );
2496 self.SetProperty( Toolkit::ScrollView::Property::START_PAGE_POSITION, Vector3(position.x, position.y, 0.0f) );
2498 UpdateMainInternalConstraint();
2499 Toolkit::ScrollBar scrollBar = mScrollBar.GetHandle();
2500 if( scrollBar && mTransientScrollBar )
2502 Vector3 size = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
2503 const Toolkit::RulerDomain& rulerDomainX = mRulerX->GetDomain();
2504 const Toolkit::RulerDomain& rulerDomainY = mRulerY->GetDomain();
2506 if( ( rulerDomainX.max > size.width ) || ( rulerDomainY.max > size.height ) )
2508 scrollBar.ShowIndicator();
2514 case GestureState::CONTINUING:
2518 DALI_LOG_SCROLL_STATE("[0x%X] Pan Continuing", this);
2519 GestureContinuing(gesture.GetScreenDisplacement());
2523 // If we do not think we are panning, then we should not do anything here
2529 case GestureState::FINISHED:
2530 case GestureState::CANCELLED:
2534 DALI_LOG_SCROLL_STATE("[0x%X] Pan %s", this, ( ( gesture.GetState() == GestureState::FINISHED ) ? "Finished" : "Cancelled" ) );
2536 UpdateLocalScrollProperties();
2537 mLastVelocity = gesture.GetVelocity();
2539 self.SetProperty( Toolkit::ScrollView::Property::PANNING, false );
2541 if( mScrollMainInternalPrePositionConstraint )
2543 mScrollMainInternalPrePositionConstraint.Remove();
2546 Toolkit::ScrollBar scrollBar = mScrollBar.GetHandle();
2547 if( scrollBar && mTransientScrollBar )
2549 scrollBar.HideIndicator();
2554 // If we do not think we are panning, then we should not do anything here
2560 case GestureState::POSSIBLE:
2561 case GestureState::CLEAR:
2563 // Nothing to do, not needed.
2567 } // end switch(gesture.state)
2569 OnGestureEx(gesture.GetState());
2572 void ScrollView::OnGestureEx(GestureState state)
2574 // call necessary signals for application developer
2576 if(state == GestureState::STARTED)
2578 Vector2 currentScrollPosition = GetCurrentScrollPosition();
2579 Self().SetProperty(Toolkit::ScrollView::Property::SCROLLING, true);
2581 DALI_LOG_SCROLL_STATE("[0x%X] mScrollStartedSignal 2 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
2582 mScrollStartedSignal.Emit( currentScrollPosition );
2584 else if( (state == GestureState::FINISHED) ||
2585 (state == GestureState::CANCELLED) ) // Finished/default
2587 // when all the gestures have finished, we finish the transform.
2588 // so if a user decides to pan (1 gesture), and then pan+zoom (2 gestures)
2589 // then stop panning (back to 1 gesture), and then stop zooming (0 gestures).
2590 // this is the point we end, and perform necessary snapping.
2591 mGestureStackDepth--;
2592 if(mGestureStackDepth==0)
2594 // no flick if we have not exceeded min flick distance
2595 if( (fabsf(mPanDelta.x) < mMinFlickDistance.x)
2596 && (fabsf(mPanDelta.y) < mMinFlickDistance.y) )
2598 // reset flick velocity
2599 mLastVelocity = Vector2::ZERO;
2605 DALI_LOG_SCROLL_STATE("[0x%X] mGestureStackDepth[%d]", this, mGestureStackDepth);
2610 void ScrollView::FinishTransform()
2612 // at this stage internal x and x scroll position should have followed prescroll position exactly
2613 Actor self = Self();
2615 PreAnimatedScrollSetup();
2617 // convert pixels/millisecond to pixels per second
2618 bool animating = SnapWithVelocity(mLastVelocity * 1000.0f);
2622 // if not animating, then this pan has completed right now.
2623 SetScrollUpdateNotification(false);
2625 Self().SetProperty(Toolkit::ScrollView::Property::SCROLLING, false);
2627 if( fabs(mScrollPrePosition.x - mScrollTargetPosition.x) > Math::MACHINE_EPSILON_10 )
2629 SnapInternalXTo(mScrollTargetPosition.x);
2631 if( fabs(mScrollPrePosition.y - mScrollTargetPosition.y) > Math::MACHINE_EPSILON_10 )
2633 SnapInternalYTo(mScrollTargetPosition.y);
2635 Vector2 currentScrollPosition = GetCurrentScrollPosition();
2636 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignal 6 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
2637 mScrollCompletedSignal.Emit( currentScrollPosition );
2641 Vector2 ScrollView::GetOvershoot(Vector2& position) const
2643 Vector3 size = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
2646 const RulerDomain rulerDomainX = mRulerX->GetDomain();
2647 const RulerDomain rulerDomainY = mRulerY->GetDomain();
2649 if(mRulerX->IsEnabled() && rulerDomainX.enabled)
2651 const float left = rulerDomainX.min - position.x;
2652 const float right = size.width - rulerDomainX.max - position.x;
2659 overshoot.x = right;
2663 if(mRulerY->IsEnabled() && rulerDomainY.enabled)
2665 const float top = rulerDomainY.min - position.y;
2666 const float bottom = size.height - rulerDomainY.max - position.y;
2673 overshoot.y = bottom;
2680 bool ScrollView::OnAccessibilityPan(PanGesture gesture)
2682 // Keep track of whether this is an AccessibilityPan
2683 mInAccessibilityPan = true;
2685 mInAccessibilityPan = false;
2690 void ScrollView::ClampPosition(Vector2& position) const
2692 ClampState2D clamped;
2693 ClampPosition(position, clamped);
2696 void ScrollView::ClampPosition(Vector2& position, ClampState2D &clamped) const
2698 Vector3 size = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
2700 position.x = -mRulerX->Clamp(-position.x, size.width, 1.0f, clamped.x); // NOTE: X & Y rulers think in -ve coordinate system.
2701 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.
2704 void ScrollView::WrapPosition(Vector2& position) const
2708 const RulerDomain rulerDomainX = mRulerX->GetDomain();
2709 const RulerDomain rulerDomainY = mRulerY->GetDomain();
2711 if(mRulerX->IsEnabled())
2713 position.x = -WrapInDomain(-position.x, rulerDomainX.min, rulerDomainX.max);
2716 if(mRulerY->IsEnabled())
2718 position.y = -WrapInDomain(-position.y, rulerDomainY.min, rulerDomainY.max);
2723 void ScrollView::UpdateMainInternalConstraint()
2725 // TODO: Only update the constraints which have changed, rather than remove all and add all again.
2726 // Requires a dali-core ApplyConstraintAt, or a ReplaceConstraint. The former is probably more flexible.
2727 Actor self = Self();
2728 PanGestureDetector detector( GetPanGestureDetector() );
2730 if(mScrollMainInternalPositionConstraint)
2732 mScrollMainInternalPositionConstraint.Remove();
2733 mScrollMainInternalDeltaConstraint.Remove();
2734 mScrollMainInternalFinalConstraint.Remove();
2735 mScrollMainInternalRelativeConstraint.Remove();
2736 mScrollMainInternalDomainConstraint.Remove();
2737 mScrollMainInternalPrePositionMaxConstraint.Remove();
2739 if( mScrollMainInternalPrePositionConstraint )
2741 mScrollMainInternalPrePositionConstraint.Remove();
2744 // TODO: It's probably better to use a local displacement value as this will give a displacement when scrolling just commences
2745 // but we need to make sure than the gesture system gives displacement since last frame (60Hz), not displacement since last touch event (90Hz).
2747 // 1. First calculate the pre-position (this is the scroll position if no clamping has taken place)
2748 Vector2 initialPanMask = Vector2(mRulerX->IsEnabled() ? 1.0f : 0.0f, mRulerY->IsEnabled() ? 1.0f : 0.0f);
2750 if( mLockAxis == LockVertical )
2752 initialPanMask.y = 0.0f;
2754 else if( mLockAxis == LockHorizontal )
2756 initialPanMask.x = 0.0f;
2761 mScrollMainInternalPrePositionConstraint = Constraint::New<Vector2>( self,
2762 Toolkit::ScrollView::Property::SCROLL_PRE_POSITION,
2763 InternalPrePositionConstraint( mPanStartPosition,
2766 mAxisAutoLockGradient,
2771 mScrollMainInternalPrePositionConstraint.AddSource( Source( detector, PanGestureDetector::Property::LOCAL_POSITION ) );
2772 mScrollMainInternalPrePositionConstraint.AddSource( Source( detector, PanGestureDetector::Property::PANNING ) );
2773 mScrollMainInternalPrePositionConstraint.AddSource( Source( self, Actor::Property::SIZE ) );
2774 mScrollMainInternalPrePositionConstraint.Apply();
2777 // 2. Second calculate the clamped position (actual position)
2778 mScrollMainInternalPositionConstraint = Constraint::New<Vector2>( self,
2779 Toolkit::ScrollView::Property::SCROLL_POSITION,
2780 InternalPositionConstraint( mRulerX->GetDomain(),
2781 mRulerY->GetDomain(),
2783 mScrollMainInternalPositionConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_PRE_POSITION ) );
2784 mScrollMainInternalPositionConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::SCROLL_POSITION_MIN ) );
2785 mScrollMainInternalPositionConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::SCROLL_POSITION_MAX ) );
2786 mScrollMainInternalPositionConstraint.AddSource( Source( self, Actor::Property::SIZE ) );
2787 mScrollMainInternalPositionConstraint.Apply();
2789 mScrollMainInternalDeltaConstraint = Constraint::New<Vector2>( self, Toolkit::ScrollView::Property::SCROLL_POSITION_DELTA, InternalPositionDeltaConstraint );
2790 mScrollMainInternalDeltaConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_POSITION ) );
2791 mScrollMainInternalDeltaConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_DOMAIN_OFFSET ) );
2792 mScrollMainInternalDeltaConstraint.Apply();
2794 mScrollMainInternalFinalConstraint = Constraint::New<Vector2>( self, Toolkit::ScrollView::Property::SCROLL_FINAL,
2795 InternalFinalConstraint( FinalDefaultAlphaFunction,
2796 FinalDefaultAlphaFunction ) );
2797 mScrollMainInternalFinalConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_POSITION ) );
2798 mScrollMainInternalFinalConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::OVERSHOOT_X ) );
2799 mScrollMainInternalFinalConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::OVERSHOOT_Y ) );
2800 mScrollMainInternalFinalConstraint.Apply();
2802 mScrollMainInternalRelativeConstraint = Constraint::New<Vector2>( self, Toolkit::Scrollable::Property::SCROLL_RELATIVE_POSITION, InternalRelativePositionConstraint );
2803 mScrollMainInternalRelativeConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_POSITION ) );
2804 mScrollMainInternalRelativeConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::SCROLL_POSITION_MIN ) );
2805 mScrollMainInternalRelativeConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::SCROLL_POSITION_MAX ) );
2806 mScrollMainInternalRelativeConstraint.AddSource( LocalSource( Actor::Property::SIZE ) );
2807 mScrollMainInternalRelativeConstraint.Apply();
2809 mScrollMainInternalDomainConstraint = Constraint::New<Vector2>( self, Toolkit::ScrollView::Property::SCROLL_DOMAIN_SIZE, InternalScrollDomainConstraint );
2810 mScrollMainInternalDomainConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::SCROLL_POSITION_MIN ) );
2811 mScrollMainInternalDomainConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::SCROLL_POSITION_MAX ) );
2812 mScrollMainInternalDomainConstraint.AddSource( LocalSource( Actor::Property::SIZE ) );
2813 mScrollMainInternalDomainConstraint.Apply();
2815 mScrollMainInternalPrePositionMaxConstraint = Constraint::New<Vector2>( self, Toolkit::ScrollView::Property::SCROLL_PRE_POSITION_MAX, InternalPrePositionMaxConstraint );
2816 mScrollMainInternalPrePositionMaxConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::SCROLL_POSITION_MAX ) );
2817 mScrollMainInternalPrePositionMaxConstraint.AddSource( LocalSource( Actor::Property::SIZE ) );
2818 mScrollMainInternalPrePositionMaxConstraint.Apply();
2820 // When panning we want to make sure overshoot values are affected by pre position and post position
2821 SetOvershootConstraintsEnabled(!mWrapMode);
2824 void ScrollView::SetOvershootConstraintsEnabled(bool enabled)
2826 Actor self( Self() );
2827 // remove and reset, it may now be in wrong order with the main internal constraints
2828 if( mScrollMainInternalOvershootXConstraint )
2830 mScrollMainInternalOvershootXConstraint.Remove();
2831 mScrollMainInternalOvershootXConstraint.Reset();
2832 mScrollMainInternalOvershootYConstraint.Remove();
2833 mScrollMainInternalOvershootYConstraint.Reset();
2837 mScrollMainInternalOvershootXConstraint= Constraint::New<float>( self, Toolkit::ScrollView::Property::OVERSHOOT_X, OvershootXConstraint(mMaxOvershoot.x) );
2838 mScrollMainInternalOvershootXConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_PRE_POSITION ) );
2839 mScrollMainInternalOvershootXConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_POSITION ) );
2840 mScrollMainInternalOvershootXConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::CAN_SCROLL_HORIZONTAL ) );
2841 mScrollMainInternalOvershootXConstraint.Apply();
2843 mScrollMainInternalOvershootYConstraint = Constraint::New<float>( self, Toolkit::ScrollView::Property::OVERSHOOT_Y, OvershootYConstraint(mMaxOvershoot.y) );
2844 mScrollMainInternalOvershootYConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_PRE_POSITION ) );
2845 mScrollMainInternalOvershootYConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_POSITION ) );
2846 mScrollMainInternalOvershootYConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::CAN_SCROLL_VERTICAL ) );
2847 mScrollMainInternalOvershootYConstraint.Apply();
2851 self.SetProperty(Toolkit::ScrollView::Property::OVERSHOOT_X, 0.0f);
2852 self.SetProperty(Toolkit::ScrollView::Property::OVERSHOOT_Y, 0.0f);
2856 void ScrollView::SetInternalConstraints()
2858 // Internal constraints (applied to target ScrollBase Actor itself) /////////
2859 UpdateMainInternalConstraint();
2861 // User definable constraints to apply to all child actors //////////////////
2862 Actor self = Self();
2864 // Apply some default constraints to ScrollView & its bound actors
2865 // Movement + Wrap function
2867 Constraint constraint;
2869 // MoveActor (scrolling)
2870 constraint = Constraint::New<Vector3>( self, Actor::Property::POSITION, MoveActorConstraint );
2871 constraint.AddSource( Source( self, Toolkit::ScrollView::Property::SCROLL_POSITION ) );
2872 constraint.SetRemoveAction(Constraint::DISCARD);
2873 ApplyConstraintToBoundActors(constraint);
2875 // WrapActor (wrap functionality)
2876 constraint = Constraint::New<Vector3>( self, Actor::Property::POSITION, WrapActorConstraint );
2877 constraint.AddSource( LocalSource( Actor::Property::SCALE ) );
2878 constraint.AddSource( LocalSource( Actor::Property::ANCHOR_POINT ) );
2879 constraint.AddSource( LocalSource( Actor::Property::SIZE ) );
2880 constraint.AddSource( Source( self, Toolkit::Scrollable::Property::SCROLL_POSITION_MIN ) );
2881 constraint.AddSource( Source( self, Toolkit::Scrollable::Property::SCROLL_POSITION_MAX ) );
2882 constraint.AddSource( Source( self, Toolkit::ScrollView::Property::WRAP ) );
2883 constraint.SetRemoveAction(Constraint::DISCARD);
2884 ApplyConstraintToBoundActors(constraint);
2887 void ScrollView::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
2889 Toolkit::ScrollView scrollView = Toolkit::ScrollView::DownCast( Dali::BaseHandle( object ) );
2893 ScrollView& scrollViewImpl( GetImpl( scrollView ) );
2896 case Toolkit::ScrollView::Property::WRAP_ENABLED:
2898 scrollViewImpl.SetWrapMode( value.Get<bool>() );
2901 case Toolkit::ScrollView::Property::PANNING_ENABLED:
2903 scrollViewImpl.SetScrollSensitive( value.Get<bool>() );
2906 case Toolkit::ScrollView::Property::AXIS_AUTO_LOCK_ENABLED:
2908 scrollViewImpl.SetAxisAutoLock( value.Get<bool>() );
2911 case Toolkit::ScrollView::Property::WHEEL_SCROLL_DISTANCE_STEP:
2913 scrollViewImpl.SetWheelScrollDistanceStep( value.Get<Vector2>() );
2916 case Toolkit::ScrollView::Property::SCROLL_MODE:
2918 const Property::Map* map = value.GetMap();
2921 scrollViewImpl.SetScrollMode( *map );
2928 Property::Value ScrollView::GetProperty( BaseObject* object, Property::Index index )
2930 Property::Value value;
2932 Toolkit::ScrollView scrollView = Toolkit::ScrollView::DownCast( Dali::BaseHandle( object ) );
2936 ScrollView& scrollViewImpl( GetImpl( scrollView ) );
2939 case Toolkit::ScrollView::Property::WRAP_ENABLED:
2941 value = scrollViewImpl.GetWrapMode();
2944 case Toolkit::ScrollView::Property::PANNING_ENABLED:
2946 value = scrollViewImpl.GetScrollSensitive();
2949 case Toolkit::ScrollView::Property::AXIS_AUTO_LOCK_ENABLED:
2951 value = scrollViewImpl.GetAxisAutoLock();
2954 case Toolkit::ScrollView::Property::WHEEL_SCROLL_DISTANCE_STEP:
2956 value = scrollViewImpl.GetWheelScrollDistanceStep();
2965 void ScrollView::SetScrollMode( const Property::Map& scrollModeMap )
2967 Toolkit::RulerPtr rulerX, rulerY;
2969 // Check the scroll mode in the X axis
2970 bool xAxisScrollEnabled = true;
2971 Property::Value* valuePtr = scrollModeMap.Find( Toolkit::ScrollMode::X_AXIS_SCROLL_ENABLED, "xAxisScrollEnabled" );
2972 if( valuePtr && valuePtr->GetType() == Property::BOOLEAN )
2974 valuePtr->Get( xAxisScrollEnabled );
2977 if( !xAxisScrollEnabled )
2979 // Default ruler and disabled
2980 rulerX = new Toolkit::DefaultRuler();
2985 valuePtr = scrollModeMap.Find( Toolkit::ScrollMode::X_AXIS_SNAP_TO_INTERVAL, "xAxisSnapToInterval" );
2986 float xAxisSnapToInterval = 0.0f;
2987 if( valuePtr && valuePtr->Get( xAxisSnapToInterval ) )
2989 // Fixed ruler and enabled
2990 rulerX = new Toolkit::FixedRuler( xAxisSnapToInterval );
2994 // Default ruler and enabled
2995 rulerX = new Toolkit::DefaultRuler();
2998 valuePtr = scrollModeMap.Find( Toolkit::ScrollMode::X_AXIS_SCROLL_BOUNDARY, "xAxisScrollBoundary" );
2999 float xAxisScrollBoundary = 0.0f;
3000 if( valuePtr && valuePtr->Get( xAxisScrollBoundary ) )
3002 // By default ruler domain is disabled unless set
3003 rulerX->SetDomain( Toolkit::RulerDomain( 0, xAxisScrollBoundary, true ) );
3007 // Check the scroll mode in the Y axis
3008 bool yAxisScrollEnabled = true;
3009 valuePtr = scrollModeMap.Find( Toolkit::ScrollMode::Y_AXIS_SCROLL_ENABLED, "yAxisScrollEnabled" );
3010 if( valuePtr && valuePtr->GetType() == Property::BOOLEAN )
3012 valuePtr->Get( yAxisScrollEnabled );
3015 if( !yAxisScrollEnabled )
3017 // Default ruler and disabled
3018 rulerY = new Toolkit::DefaultRuler();
3023 valuePtr = scrollModeMap.Find( Toolkit::ScrollMode::Y_AXIS_SNAP_TO_INTERVAL, "yAxisSnapToInterval" );
3024 float yAxisSnapToInterval = 0.0f;
3025 if( valuePtr && valuePtr->Get( yAxisSnapToInterval ) )
3027 // Fixed ruler and enabled
3028 rulerY = new Toolkit::FixedRuler(yAxisSnapToInterval);
3032 // Default ruler and enabled
3033 rulerY = new Toolkit::DefaultRuler();
3036 valuePtr = scrollModeMap.Find( Toolkit::ScrollMode::Y_AXIS_SCROLL_BOUNDARY, "yAxisScrollBoundary" );
3037 float yAxisScrollBoundary = 0.0f;
3038 if( valuePtr && valuePtr->Get( yAxisScrollBoundary ) )
3040 // By default ruler domain is disabled unless set
3041 rulerY->SetDomain( Toolkit::RulerDomain( 0, yAxisScrollBoundary, true ) );
3049 } // namespace Internal
3051 } // namespace Toolkit