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( REQUIRES_WHEEL_EVENTS | 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.TouchSignal().Connect( this, &ScrollView::OnTouch );
693 EnableGestureDetection( Gesture::Type( Gesture::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();
708 void ScrollView::OnSceneConnection( int depth )
710 DALI_LOG_SCROLL_STATE("[0x%X]", this);
714 SetScrollSensitive( false );
715 SetScrollSensitive( true );
718 if(IsOvershootEnabled())
720 // try and make sure property notifications are set
721 EnableScrollOvershoot(true);
724 ScrollBase::OnSceneConnection( depth );
727 void ScrollView::OnSceneDisconnection()
729 DALI_LOG_SCROLL_STATE("[0x%X]", this);
733 ScrollBase::OnSceneDisconnection();
736 ScrollView::~ScrollView()
738 DALI_LOG_SCROLL_STATE("[0x%X]", this);
741 AlphaFunction ScrollView::GetScrollSnapAlphaFunction() const
743 return mSnapAlphaFunction;
746 void ScrollView::SetScrollSnapAlphaFunction(AlphaFunction alpha)
748 mSnapAlphaFunction = alpha;
751 AlphaFunction ScrollView::GetScrollFlickAlphaFunction() const
753 return mFlickAlphaFunction;
756 void ScrollView::SetScrollFlickAlphaFunction(AlphaFunction alpha)
758 mFlickAlphaFunction = alpha;
761 float ScrollView::GetScrollSnapDuration() const
763 return mSnapDuration;
766 void ScrollView::SetScrollSnapDuration(float time)
768 mSnapDuration = time;
771 float ScrollView::GetScrollFlickDuration() const
773 return mFlickDuration;
776 void ScrollView::SetScrollFlickDuration(float time)
778 mFlickDuration = time;
781 void ScrollView::ApplyEffect(Toolkit::ScrollViewEffect effect)
783 Dali::Toolkit::ScrollView self = Dali::Toolkit::ScrollView::DownCast(Self());
785 // Assertion check to ensure effect doesn't already exist in this scrollview
786 bool effectAlreadyExistsInScrollView(false);
787 for (ScrollViewEffectIter iter = mEffects.begin(); iter != mEffects.end(); ++iter)
791 effectAlreadyExistsInScrollView = true;
796 DALI_ASSERT_ALWAYS(!effectAlreadyExistsInScrollView);
798 // add effect to effects list
799 mEffects.push_back(effect);
801 // invoke Attachment request to ScrollView first
802 GetImpl(effect).Attach(self);
805 void ScrollView::RemoveEffect(Toolkit::ScrollViewEffect effect)
807 Dali::Toolkit::ScrollView self = Dali::Toolkit::ScrollView::DownCast(Self());
809 // remove effect from effects list
810 bool effectExistedInScrollView(false);
811 for (ScrollViewEffectIter iter = mEffects.begin(); iter != mEffects.end(); ++iter)
815 mEffects.erase(iter);
816 effectExistedInScrollView = true;
821 // Assertion check to ensure effect existed.
822 DALI_ASSERT_ALWAYS(effectExistedInScrollView);
824 // invoke Detachment request to ScrollView last
825 GetImpl(effect).Detach(self);
828 void ScrollView::RemoveAllEffects()
830 Dali::Toolkit::ScrollView self = Dali::Toolkit::ScrollView::DownCast(Self());
832 for (ScrollViewEffectIter effectIter = mEffects.begin(); effectIter != mEffects.end(); ++effectIter)
834 Toolkit::ScrollViewEffect effect = *effectIter;
836 // invoke Detachment request to ScrollView last
837 GetImpl(effect).Detach(self);
843 void ScrollView::ApplyConstraintToChildren(Constraint constraint)
845 ApplyConstraintToBoundActors(constraint);
848 void ScrollView::RemoveConstraintsFromChildren()
850 RemoveConstraintsFromBoundActors();
853 const RulerPtr ScrollView::GetRulerX() const
858 const RulerPtr ScrollView::GetRulerY() const
863 void ScrollView::SetRulerX(RulerPtr ruler)
867 UpdatePropertyDomain();
868 UpdateMainInternalConstraint();
871 void ScrollView::SetRulerY(RulerPtr ruler)
875 UpdatePropertyDomain();
876 UpdateMainInternalConstraint();
879 void ScrollView::UpdatePropertyDomain()
882 Vector3 size = self.GetTargetSize();
883 Vector2 min = mMinScroll;
884 Vector2 max = mMaxScroll;
885 bool scrollPositionChanged = false;
886 bool domainChanged = false;
888 bool canScrollVertical = false;
889 bool canScrollHorizontal = false;
890 UpdateLocalScrollProperties();
891 if(mRulerX->IsEnabled())
893 const Toolkit::RulerDomain& rulerDomain = mRulerX->GetDomain();
894 if( fabsf(min.x - rulerDomain.min) > Math::MACHINE_EPSILON_100
895 || fabsf(max.x - rulerDomain.max) > Math::MACHINE_EPSILON_100 )
897 domainChanged = true;
898 min.x = rulerDomain.min;
899 max.x = rulerDomain.max;
901 // make sure new scroll value is within new domain
902 if( mScrollPrePosition.x < min.x
903 || mScrollPrePosition.x > max.x )
905 scrollPositionChanged = true;
906 mScrollPrePosition.x = Clamp(mScrollPrePosition.x, -(max.x - size.x), -min.x);
909 if( (fabsf(rulerDomain.max - rulerDomain.min) - size.x) > Math::MACHINE_EPSILON_100 )
911 canScrollHorizontal = true;
914 else if( fabs(min.x) > Math::MACHINE_EPSILON_100
915 || fabs(max.x) > Math::MACHINE_EPSILON_100 )
917 // need to reset to 0
918 domainChanged = true;
921 canScrollHorizontal = false;
924 if(mRulerY->IsEnabled())
926 const Toolkit::RulerDomain& rulerDomain = mRulerY->GetDomain();
927 if( fabsf(min.y - rulerDomain.min) > Math::MACHINE_EPSILON_100
928 || fabsf(max.y - rulerDomain.max) > Math::MACHINE_EPSILON_100 )
930 domainChanged = true;
931 min.y = rulerDomain.min;
932 max.y = rulerDomain.max;
934 // make sure new scroll value is within new domain
935 if( mScrollPrePosition.y < min.y
936 || mScrollPrePosition.y > max.y )
938 scrollPositionChanged = true;
939 mScrollPrePosition.y = Clamp(mScrollPrePosition.y, -(max.y - size.y), -min.y);
942 if( (fabsf(rulerDomain.max - rulerDomain.min) - size.y) > Math::MACHINE_EPSILON_100 )
944 canScrollVertical = true;
947 else if( fabs(min.y) > Math::MACHINE_EPSILON_100
948 || fabs(max.y) > Math::MACHINE_EPSILON_100 )
950 // need to reset to 0
951 domainChanged = true;
954 canScrollVertical = false;
957 // avoid setting properties if possible, otherwise this will cause an entire update as well as triggering constraints using each property we update
958 if( mCanScrollVertical != canScrollVertical )
960 mCanScrollVertical = canScrollVertical;
961 self.SetProperty(Toolkit::Scrollable::Property::CAN_SCROLL_VERTICAL, canScrollVertical);
963 if( mCanScrollHorizontal != canScrollHorizontal )
965 mCanScrollHorizontal = canScrollHorizontal;
966 self.SetProperty(Toolkit::Scrollable::Property::CAN_SCROLL_HORIZONTAL, canScrollHorizontal);
968 if( scrollPositionChanged )
970 DALI_LOG_SCROLL_STATE("[0x%X] Domain Changed, setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y );
971 self.SetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, mScrollPrePosition);
977 self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MIN, mMinScroll );
978 self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX, mMaxScroll );
982 bool ScrollView::GetScrollSensitive()
987 void ScrollView::SetScrollSensitive(bool sensitive)
990 PanGestureDetector panGesture( GetPanGestureDetector() );
992 DALI_LOG_SCROLL_STATE("[0x%X] sensitive: before:[%d] setting[%d]", this, int(mSensitive), int(sensitive));
994 if((!mSensitive) && (sensitive))
996 mSensitive = sensitive;
997 panGesture.Attach(self);
999 else if((mSensitive) && (!sensitive))
1001 DALI_LOG_SCROLL_STATE("[0x%X] BEFORE: panning:[%d]", this, int(mPanning));
1003 // while the scroll view is panning, the state needs to be reset.
1006 PanGesture cancelGesture = DevelPanGesture::New( Gesture::Cancelled );
1007 OnPan( cancelGesture );
1010 panGesture.Detach(self);
1011 mSensitive = sensitive;
1013 mGestureStackDepth = 0;
1014 DALI_LOG_SCROLL_STATE("[0x%X] AFTER: panning:[%d]", this, int(mPanning));
1018 void ScrollView::SetMaxOvershoot(float overshootX, float overshootY)
1020 mMaxOvershoot.x = overshootX;
1021 mMaxOvershoot.y = overshootY;
1022 mUserMaxOvershoot = mMaxOvershoot;
1023 mDefaultMaxOvershoot = false;
1024 UpdateMainInternalConstraint();
1027 void ScrollView::SetSnapOvershootAlphaFunction(AlphaFunction alpha)
1029 mSnapOvershootAlphaFunction = alpha;
1032 float ScrollView::GetSnapOvershootDuration()
1034 return mSnapOvershootDuration;
1037 void ScrollView::SetSnapOvershootDuration(float duration)
1039 mSnapOvershootDuration = duration;
1042 bool ScrollView::GetActorAutoSnap()
1044 return mActorAutoSnapEnabled;
1047 void ScrollView::SetActorAutoSnap(bool enable)
1049 mActorAutoSnapEnabled = enable;
1052 void ScrollView::SetAutoResize(bool enable)
1054 mAutoResizeContainerEnabled = enable;
1055 // TODO: This needs a lot of issues to be addressed before working.
1058 bool ScrollView::GetWrapMode() const
1063 void ScrollView::SetWrapMode(bool enable)
1066 Self().SetProperty(Toolkit::ScrollView::Property::WRAP, enable);
1069 int ScrollView::GetScrollUpdateDistance() const
1071 return mScrollUpdateDistance;
1074 void ScrollView::SetScrollUpdateDistance(int distance)
1076 mScrollUpdateDistance = distance;
1079 bool ScrollView::GetAxisAutoLock() const
1081 return mAxisAutoLock;
1084 void ScrollView::SetAxisAutoLock(bool enable)
1086 mAxisAutoLock = enable;
1087 UpdateMainInternalConstraint();
1090 float ScrollView::GetAxisAutoLockGradient() const
1092 return mAxisAutoLockGradient;
1095 void ScrollView::SetAxisAutoLockGradient(float gradient)
1097 DALI_ASSERT_DEBUG( gradient >= 0.0f && gradient <= 1.0f );
1098 mAxisAutoLockGradient = gradient;
1099 UpdateMainInternalConstraint();
1102 float ScrollView::GetFrictionCoefficient() const
1104 return mFrictionCoefficient;
1107 void ScrollView::SetFrictionCoefficient(float friction)
1109 DALI_ASSERT_DEBUG( friction > 0.0f );
1110 mFrictionCoefficient = friction;
1113 float ScrollView::GetFlickSpeedCoefficient() const
1115 return mFlickSpeedCoefficient;
1118 void ScrollView::SetFlickSpeedCoefficient(float speed)
1120 mFlickSpeedCoefficient = speed;
1123 Vector2 ScrollView::GetMinimumDistanceForFlick() const
1125 return mMinFlickDistance;
1128 void ScrollView::SetMinimumDistanceForFlick( const Vector2& distance )
1130 mMinFlickDistance = distance;
1133 float ScrollView::GetMinimumSpeedForFlick() const
1135 return mFlickSpeedThreshold;
1138 void ScrollView::SetMinimumSpeedForFlick( float speed )
1140 mFlickSpeedThreshold = speed;
1143 float ScrollView::GetMaxFlickSpeed() const
1145 return mMaxFlickSpeed;
1148 void ScrollView::SetMaxFlickSpeed(float speed)
1150 mMaxFlickSpeed = speed;
1153 void ScrollView::SetWheelScrollDistanceStep(Vector2 step)
1155 mWheelScrollDistanceStep = step;
1158 Vector2 ScrollView::GetWheelScrollDistanceStep() const
1160 return mWheelScrollDistanceStep;
1163 unsigned int ScrollView::GetCurrentPage() const
1165 // in case animation is currently taking place.
1166 Vector2 position = GetPropertyPosition();
1168 Actor self = Self();
1169 unsigned int page = 0;
1170 unsigned int pagesPerVolume = 1;
1171 unsigned int volume = 0;
1173 // if rulerX is enabled, then get page count (columns)
1174 page = mRulerX->GetPageFromPosition(-position.x, mWrapMode);
1175 volume = mRulerY->GetPageFromPosition(-position.y, mWrapMode);
1176 pagesPerVolume = mRulerX->GetTotalPages();
1178 return volume * pagesPerVolume + page;
1181 Vector2 ScrollView::GetCurrentScrollPosition() const
1183 return -GetPropertyPosition();
1186 void ScrollView::TransformTo(const Vector2& position,
1187 DirectionBias horizontalBias, DirectionBias verticalBias)
1189 TransformTo(position, mSnapDuration, mSnapAlphaFunction, horizontalBias, verticalBias);
1192 void ScrollView::TransformTo(const Vector2& position, float duration, AlphaFunction alpha,
1193 DirectionBias horizontalBias, DirectionBias verticalBias)
1195 // If this is called while the timer is running, then cancel it
1196 StopTouchDownTimer();
1198 Actor self( Self() );
1200 // Guard against destruction during signal emission
1201 // Note that Emit() methods are called indirectly e.g. from within ScrollView::AnimateTo()
1202 Toolkit::ScrollView handle( GetOwner() );
1204 DALI_LOG_SCROLL_STATE("[0x%X] pos[%.2f,%.2f], duration[%.2f] bias[%d, %d]",
1205 this, position.x, position.y, duration, int(horizontalBias), int(verticalBias));
1207 Vector2 currentScrollPosition = GetCurrentScrollPosition();
1208 self.SetProperty( Toolkit::ScrollView::Property::START_PAGE_POSITION, Vector3(currentScrollPosition) );
1210 if( mScrolling ) // are we interrupting a current scroll?
1212 // set mScrolling to false, in case user has code that interrogates mScrolling Getter() in complete.
1214 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignal 1 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
1215 mScrollCompletedSignal.Emit( currentScrollPosition );
1218 if( mPanning ) // are we interrupting a current pan?
1220 DALI_LOG_SCROLL_STATE("[0x%X] Interrupting Pan, set to false", this );
1222 mGestureStackDepth = 0;
1223 self.SetProperty( Toolkit::ScrollView::Property::PANNING, false );
1225 if( mScrollMainInternalPrePositionConstraint )
1227 mScrollMainInternalPrePositionConstraint.Remove();
1231 self.SetProperty(Toolkit::ScrollView::Property::SCROLLING, true);
1234 DALI_LOG_SCROLL_STATE("[0x%X] mScrollStartedSignal 1 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
1235 mScrollStartedSignal.Emit( currentScrollPosition );
1236 bool animating = AnimateTo(-position,
1237 Vector2::ONE * duration,
1246 // if not animating, then this pan has completed right now.
1247 self.SetProperty(Toolkit::ScrollView::Property::SCROLLING, false);
1250 // If we have no duration, then in the next update frame, we will be at the position specified as we just set.
1251 // In this scenario, we cannot return the currentScrollPosition as this is out-of-date and should instead return the requested final position
1252 Vector2 completedPosition( currentScrollPosition );
1253 if( duration <= Math::MACHINE_EPSILON_10 )
1255 completedPosition = position;
1258 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignal 2 [%.2f, %.2f]", this, completedPosition.x, completedPosition.y);
1259 SetScrollUpdateNotification(false);
1260 mScrollCompletedSignal.Emit( completedPosition );
1264 void ScrollView::ScrollTo(const Vector2& position)
1266 ScrollTo(position, mSnapDuration );
1269 void ScrollView::ScrollTo(const Vector2& position, float duration)
1271 ScrollTo(position, duration, DIRECTION_BIAS_NONE, DIRECTION_BIAS_NONE);
1274 void ScrollView::ScrollTo(const Vector2& position, float duration, AlphaFunction alpha)
1276 ScrollTo(position, duration, alpha, DIRECTION_BIAS_NONE, DIRECTION_BIAS_NONE);
1279 void ScrollView::ScrollTo(const Vector2& position, float duration,
1280 DirectionBias horizontalBias, DirectionBias verticalBias)
1282 ScrollTo(position, duration, mSnapAlphaFunction, horizontalBias, verticalBias);
1285 void ScrollView::ScrollTo(const Vector2& position, float duration, AlphaFunction alpha,
1286 DirectionBias horizontalBias, DirectionBias verticalBias)
1288 DALI_LOG_SCROLL_STATE("[0x%X] position[%.2f, %.2f] duration[%.2f], bias[%d, %d]", this, position.x, position.y, duration, int(horizontalBias), int(verticalBias));
1289 TransformTo(position, duration, alpha, horizontalBias, verticalBias);
1292 void ScrollView::ScrollTo(unsigned int page)
1294 ScrollTo(page, mSnapDuration);
1297 void ScrollView::ScrollTo(unsigned int page, float duration, DirectionBias bias)
1300 unsigned int volume;
1301 unsigned int libraries;
1303 // The position to scroll to is continuous and linear
1304 // unless a domain has been enabled on the X axis.
1305 // or if WrapMode has been enabled.
1306 bool carryX = mRulerX->GetDomain().enabled | mWrapMode;
1307 bool carryY = mRulerY->GetDomain().enabled | mWrapMode;
1309 position.x = mRulerX->GetPositionFromPage(page, volume, carryX);
1310 position.y = mRulerY->GetPositionFromPage(volume, libraries, carryY);
1312 ScrollTo(position, duration, bias, bias);
1315 void ScrollView::ScrollTo(Actor &actor)
1317 ScrollTo(actor, mSnapDuration);
1320 void ScrollView::ScrollTo(Actor &actor, float duration)
1322 DALI_ASSERT_ALWAYS(actor.GetParent() == Self());
1324 Actor self = Self();
1325 Vector3 size = self.GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
1326 Vector3 position = actor.GetCurrentProperty< Vector3 >( Actor::Property::POSITION );
1327 Vector2 prePosition = GetPropertyPrePosition();
1328 position.GetVectorXY() -= prePosition;
1330 ScrollTo(Vector2(position.x - size.width * 0.5f, position.y - size.height * 0.5f), duration);
1333 Actor ScrollView::FindClosestActor()
1335 Actor self = Self();
1336 Vector3 size = self.GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
1338 return FindClosestActorToPosition(Vector3(size.width * 0.5f,size.height * 0.5f,0.0f));
1341 Actor ScrollView::FindClosestActorToPosition(const Vector3& position, FindDirection dirX, FindDirection dirY, FindDirection dirZ)
1344 float closestDistance2 = 0.0f;
1345 Vector3 actualPosition = position;
1347 unsigned int numChildren = Self().GetChildCount();
1349 for(unsigned int i = 0; i < numChildren; ++i)
1351 Actor child = Self().GetChildAt(i);
1353 if(mInternalActor == child) // ignore internal actor.
1358 Vector3 childPosition = GetPositionOfAnchor(child, AnchorPoint::CENTER);
1360 Vector3 delta = childPosition - actualPosition;
1362 // X-axis checking (only find Actors to the [dirX] of actualPosition)
1363 if(dirX > All) // != All,None
1365 FindDirection deltaH = delta.x > 0 ? Right : Left;
1372 // Y-axis checking (only find Actors to the [dirY] of actualPosition)
1373 if(dirY > All) // != All,None
1375 FindDirection deltaV = delta.y > 0 ? Down : Up;
1382 // Z-axis checking (only find Actors to the [dirZ] of actualPosition)
1383 if(dirZ > All) // != All,None
1385 FindDirection deltaV = delta.y > 0 ? In : Out;
1392 // compare child to closest child in terms of distance.
1393 float distance2 = 0.0f;
1395 // distance2 = the Square of the relevant dimensions of delta
1398 distance2 += delta.x * delta.x;
1403 distance2 += delta.y * delta.y;
1408 distance2 += delta.z * delta.z;
1411 if(closestChild) // Next time.
1413 if(distance2 < closestDistance2)
1415 closestChild = child;
1416 closestDistance2 = distance2;
1421 closestChild = child;
1422 closestDistance2 = distance2;
1426 return closestChild;
1429 bool ScrollView::ScrollToSnapPoint()
1431 DALI_LOG_SCROLL_STATE("[0x%X]", this );
1432 Vector2 stationaryVelocity = Vector2(0.0f, 0.0f);
1433 return SnapWithVelocity( stationaryVelocity );
1436 // TODO: In situations where axes are different (X snap, Y free)
1437 // Each axis should really have their own independent animation (time and equation)
1438 // Consider, X axis snapping to nearest grid point (EaseOut over fixed time)
1439 // Consider, Y axis simulating physics to arrive at a point (Physics equation over variable time)
1440 // Currently, the axes have been split however, they both use the same EaseOut equation.
1441 bool ScrollView::SnapWithVelocity(Vector2 velocity)
1443 // Animator takes over now, touches are assumed not to interfere.
1444 // And if touches do interfere, then we'll stop animation, update PrePosition
1445 // to current mScroll's properties, and then resume.
1446 // Note: For Flicking this may work a bit different...
1448 float angle = atan2(velocity.y, velocity.x);
1449 float speed2 = velocity.LengthSquared();
1450 AlphaFunction alphaFunction = mSnapAlphaFunction;
1451 Vector2 positionDuration = Vector2::ONE * mSnapDuration;
1454 FindDirection horizontal = None;
1455 FindDirection vertical = None;
1457 // orthoAngleRange = Angle tolerance within the Exact N,E,S,W direction
1458 // that will be accepted as a general N,E,S,W flick direction.
1460 const float orthoAngleRange = FLICK_ORTHO_ANGLE_RANGE * M_PI / 180.0f;
1461 const float flickSpeedThreshold2 = mFlickSpeedThreshold * mFlickSpeedThreshold;
1463 Vector2 positionSnap = mScrollPrePosition;
1465 // Flick logic X Axis
1467 if(mRulerX->IsEnabled() && mLockAxis != LockHorizontal)
1471 if( speed2 > flickSpeedThreshold2 || // exceeds flick threshold
1472 mInAccessibilityPan ) // With AccessibilityPan its easier to move between snap positions
1474 if((angle >= -orthoAngleRange) && (angle < orthoAngleRange)) // Swiping East
1476 biasX = 0.0f, horizontal = Left;
1478 // This guards against an error where no movement occurs, due to the flick finishing
1479 // before the update-thread has advanced mScrollPostPosition past the the previous snap point.
1480 positionSnap.x += 1.0f;
1482 else if((angle >= M_PI-orthoAngleRange) || (angle < -M_PI+orthoAngleRange)) // Swiping West
1484 biasX = 1.0f, horizontal = Right;
1486 // This guards against an error where no movement occurs, due to the flick finishing
1487 // before the update-thread has advanced mScrollPostPosition past the the previous snap point.
1488 positionSnap.x -= 1.0f;
1493 // Flick logic Y Axis
1495 if(mRulerY->IsEnabled() && mLockAxis != LockVertical)
1499 if( speed2 > flickSpeedThreshold2 || // exceeds flick threshold
1500 mInAccessibilityPan ) // With AccessibilityPan its easier to move between snap positions
1502 if((angle >= M_PI_2-orthoAngleRange) && (angle < M_PI_2+orthoAngleRange)) // Swiping South
1504 biasY = 0.0f, vertical = Up;
1506 else if((angle >= -M_PI_2-orthoAngleRange) && (angle < -M_PI_2+orthoAngleRange)) // Swiping North
1508 biasY = 1.0f, vertical = Down;
1513 // isFlick: Whether this gesture is a flick or not.
1514 bool isFlick = (horizontal != All || vertical != All);
1515 // isFreeFlick: Whether this gesture is a flick under free panning criteria.
1516 bool isFreeFlick = velocity.LengthSquared() > (FREE_FLICK_SPEED_THRESHOLD*FREE_FLICK_SPEED_THRESHOLD);
1518 if(isFlick || isFreeFlick)
1520 positionDuration = Vector2::ONE * mFlickDuration;
1521 alphaFunction = mFlickAlphaFunction;
1524 // Calculate next positionSnap ////////////////////////////////////////////////////////////
1526 if(mActorAutoSnapEnabled)
1528 Vector3 size = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
1530 Actor child = FindClosestActorToPosition( Vector3(size.width * 0.5f,size.height * 0.5f,0.0f), horizontal, vertical );
1532 if(!child && isFlick )
1534 // If we conducted a direction limited search and found no actor, then just snap to the closest actor.
1535 child = FindClosestActorToPosition( Vector3(size.width * 0.5f,size.height * 0.5f,0.0f) );
1540 Vector2 position = Self().GetCurrentProperty<Vector2>( Toolkit::ScrollView::Property::SCROLL_POSITION );
1542 // Get center-point of the Actor.
1543 Vector3 childPosition = GetPositionOfAnchor(child, AnchorPoint::CENTER);
1545 if(mRulerX->IsEnabled())
1547 positionSnap.x = position.x - childPosition.x + size.width * 0.5f;
1549 if(mRulerY->IsEnabled())
1551 positionSnap.y = position.y - childPosition.y + size.height * 0.5f;
1556 Vector2 startPosition = positionSnap;
1557 positionSnap.x = -mRulerX->Snap(-positionSnap.x, biasX); // NOTE: X & Y rulers think in -ve coordinate system.
1558 positionSnap.y = -mRulerY->Snap(-positionSnap.y, biasY); // That is scrolling RIGHT (e.g. 100.0, 0.0) means moving LEFT.
1560 Vector2 clampDelta(Vector2::ZERO);
1561 ClampPosition(positionSnap);
1563 if( (mRulerX->GetType() == Ruler::FREE || mRulerY->GetType() == Ruler::FREE)
1564 && isFreeFlick && !mActorAutoSnapEnabled)
1566 // Calculate target position based on velocity of flick.
1568 // a = Deceleration (Set to diagonal stage length * friction coefficient)
1569 // u = Initial Velocity (Flick velocity)
1570 // v = 0 (Final Velocity)
1571 // t = Time (Velocity / Deceleration)
1572 Vector2 stageSize = Stage::GetCurrent().GetSize();
1573 float stageLength = Vector3(stageSize.x, stageSize.y, 0.0f).Length();
1574 float a = (stageLength * mFrictionCoefficient);
1575 Vector3 u = Vector3(velocity.x, velocity.y, 0.0f) * mFlickSpeedCoefficient;
1576 float speed = u.Length();
1579 // TODO: Change this to a decay function. (faster you flick, the slower it should be)
1580 speed = std::min(speed, stageLength * mMaxFlickSpeed );
1582 alphaFunction = ConstantDecelerationAlphaFunction;
1584 float t = speed / a;
1586 if(mRulerX->IsEnabled() && mRulerX->GetType() == Ruler::FREE)
1588 positionSnap.x += t*u.x*0.5f;
1591 if(mRulerY->IsEnabled() && mRulerY->GetType() == Ruler::FREE)
1593 positionSnap.y += t*u.y*0.5f;
1596 clampDelta = positionSnap;
1597 ClampPosition(positionSnap);
1598 if((positionSnap - startPosition).LengthSquared() > Math::MACHINE_EPSILON_0)
1600 clampDelta -= positionSnap;
1601 clampDelta.x = clampDelta.x > 0.0f ? std::min(clampDelta.x, mMaxOvershoot.x) : std::max(clampDelta.x, -mMaxOvershoot.x);
1602 clampDelta.y = clampDelta.y > 0.0f ? std::min(clampDelta.y, mMaxOvershoot.y) : std::max(clampDelta.y, -mMaxOvershoot.y);
1606 clampDelta = Vector2::ZERO;
1609 // If Axis is Free and has velocity, then calculate time taken
1610 // to reach target based on velocity in axis.
1611 if(mRulerX->IsEnabled() && mRulerX->GetType() == Ruler::FREE)
1613 float deltaX = fabsf(startPosition.x - positionSnap.x);
1615 if(fabsf(u.x) > Math::MACHINE_EPSILON_1)
1617 positionDuration.x = fabsf(deltaX / u.x);
1621 positionDuration.x = 0;
1625 if(mRulerY->IsEnabled() && mRulerY->GetType() == Ruler::FREE)
1627 float deltaY = fabsf(startPosition.y - positionSnap.y);
1629 if(fabsf(u.y) > Math::MACHINE_EPSILON_1)
1631 positionDuration.y = fabsf(deltaY / u.y);
1635 positionDuration.y = 0;
1640 if(IsOvershootEnabled())
1642 // Scroll to the end of the overshoot only when overshoot is enabled.
1643 positionSnap += clampDelta;
1646 bool animating = AnimateTo(positionSnap, positionDuration,
1647 alphaFunction, false,
1648 DIRECTION_BIAS_NONE, DIRECTION_BIAS_NONE,
1649 isFlick || isFreeFlick ? FLICK : SNAP);
1654 void ScrollView::StopAnimation(void)
1656 // Clear Snap animation if exists.
1657 StopAnimation(mInternalXAnimation);
1658 StopAnimation(mInternalYAnimation);
1659 mScrollStateFlags = 0;
1660 // remove scroll animation flags
1661 HandleStoppedAnimation();
1664 void ScrollView::StopAnimation(Animation& animation)
1673 bool ScrollView::AnimateTo(const Vector2& position, const Vector2& positionDuration,
1674 AlphaFunction alpha, bool findShortcuts,
1675 DirectionBias horizontalBias, DirectionBias verticalBias,
1678 // Here we perform an animation on a number of properties (depending on which have changed)
1679 // The animation is applied to all ScrollBases
1680 Actor self = Self();
1681 mScrollTargetPosition = position;
1682 float totalDuration = 0.0f;
1684 bool positionChanged = (mScrollTargetPosition != mScrollPostPosition);
1688 totalDuration = std::max(totalDuration, positionDuration.x);
1689 totalDuration = std::max(totalDuration, positionDuration.y);
1693 // try to animate for a frame, on some occasions update will be changing scroll value while event side thinks it hasnt changed
1694 totalDuration = 0.01f;
1695 positionChanged = true;
1700 // Position Delta ///////////////////////////////////////////////////////
1703 UpdateMainInternalConstraint();
1704 if(mWrapMode && findShortcuts)
1706 // In Wrap Mode, the shortest distance is a little less intuitive...
1707 const RulerDomain rulerDomainX = mRulerX->GetDomain();
1708 const RulerDomain rulerDomainY = mRulerY->GetDomain();
1710 if(mRulerX->IsEnabled())
1712 float dir = VectorInDomain(-mScrollPrePosition.x, -mScrollTargetPosition.x, rulerDomainX.min, rulerDomainX.max, horizontalBias);
1713 mScrollTargetPosition.x = mScrollPrePosition.x + -dir;
1716 if(mRulerY->IsEnabled())
1718 float dir = VectorInDomain(-mScrollPrePosition.y, -mScrollTargetPosition.y, rulerDomainY.min, rulerDomainY.max, verticalBias);
1719 mScrollTargetPosition.y = mScrollPrePosition.y + -dir;
1723 // note we have two separate animations for X & Y, this deals with sliding diagonally and hitting
1724 // a horizonal/vertical wall.delay
1725 AnimateInternalXTo(mScrollTargetPosition.x, positionDuration.x, alpha);
1726 AnimateInternalYTo(mScrollTargetPosition.y, positionDuration.y, alpha);
1728 if( !(mScrollStateFlags & SCROLL_ANIMATION_FLAGS) )
1730 DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollTargetPosition.x, mScrollTargetPosition.y );
1731 self.SetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, mScrollTargetPosition);
1732 mScrollPrePosition = mScrollTargetPosition;
1733 mScrollPostPosition = mScrollTargetPosition;
1734 WrapPosition(mScrollPostPosition);
1737 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 );
1738 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 );
1741 SetScrollUpdateNotification(true);
1743 // Always send a snap event when AnimateTo is called.
1744 Toolkit::ScrollView::SnapEvent snapEvent;
1745 snapEvent.type = snapType;
1746 snapEvent.position = -mScrollTargetPosition;
1747 snapEvent.duration = totalDuration;
1749 DALI_LOG_SCROLL_STATE("[0x%X] mSnapStartedSignal [%.2f, %.2f]", this, snapEvent.position.x, snapEvent.position.y);
1750 mSnapStartedSignal.Emit( snapEvent );
1752 return (mScrollStateFlags & SCROLL_ANIMATION_FLAGS) != 0;
1755 void ScrollView::EnableScrollOvershoot(bool enable)
1759 if (!mOvershootIndicator)
1761 mOvershootIndicator = ScrollOvershootIndicator::New();
1764 mOvershootIndicator->AttachToScrollable(*this);
1768 mMaxOvershoot = mUserMaxOvershoot;
1770 if (mOvershootIndicator)
1772 mOvershootIndicator->DetachFromScrollable(*this);
1776 UpdateMainInternalConstraint();
1779 void ScrollView::AddOverlay(Actor actor)
1781 actor.SetProperty( Actor::Property::DRAW_MODE, DrawMode::OVERLAY_2D );
1782 mInternalActor.Add( actor );
1785 void ScrollView::RemoveOverlay(Actor actor)
1787 mInternalActor.Remove( actor );
1790 void ScrollView::SetOvershootSize( const Vector2& size )
1792 mOvershootSize = size;
1793 if( IsOvershootEnabled() && mOvershootIndicator )
1795 mOvershootIndicator->AttachToScrollable(*this);
1799 void ScrollView::SetOvershootEffectColor( const Vector4& color )
1801 mOvershootEffectColor = color;
1802 if( mOvershootIndicator )
1804 mOvershootIndicator->SetOvershootEffectColor( color );
1808 void ScrollView::SetScrollingDirection( Radian direction, Radian threshold )
1810 PanGestureDetector panGesture( GetPanGestureDetector() );
1812 // First remove just in case we have some set, then add.
1813 panGesture.RemoveDirection( direction );
1814 panGesture.AddDirection( direction, threshold );
1817 void ScrollView::RemoveScrollingDirection( Radian direction )
1819 PanGestureDetector panGesture( GetPanGestureDetector() );
1820 panGesture.RemoveDirection( direction );
1823 Toolkit::ScrollView::SnapStartedSignalType& ScrollView::SnapStartedSignal()
1825 return mSnapStartedSignal;
1828 void ScrollView::FindAndUnbindActor(Actor child)
1833 Vector2 ScrollView::GetPropertyPrePosition() const
1835 Vector2 position = Self().GetCurrentProperty< Vector2 >( Toolkit::ScrollView::Property::SCROLL_PRE_POSITION );
1836 WrapPosition(position);
1840 Vector2 ScrollView::GetPropertyPosition() const
1842 Vector2 position = Self().GetCurrentProperty< Vector2 >( Toolkit::ScrollView::Property::SCROLL_POSITION );
1843 WrapPosition(position);
1848 void ScrollView::HandleStoppedAnimation()
1850 SetScrollUpdateNotification(false);
1853 void ScrollView::HandleSnapAnimationFinished()
1855 // Emit Signal that scrolling has completed.
1857 Actor self = Self();
1858 self.SetProperty(Toolkit::ScrollView::Property::SCROLLING, false);
1860 Vector2 deltaPosition(mScrollPrePosition);
1862 UpdateLocalScrollProperties();
1863 WrapPosition(mScrollPrePosition);
1864 DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y );
1865 self.SetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, mScrollPrePosition);
1867 Vector2 currentScrollPosition = GetCurrentScrollPosition();
1868 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignal 3 current[%.2f, %.2f], mScrollTargetPosition[%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y, -mScrollTargetPosition.x, -mScrollTargetPosition.y );
1869 mScrollCompletedSignal.Emit( currentScrollPosition );
1871 mDomainOffset += deltaPosition - mScrollPostPosition;
1872 self.SetProperty(Toolkit::ScrollView::Property::SCROLL_DOMAIN_OFFSET, mDomainOffset);
1873 HandleStoppedAnimation();
1876 void ScrollView::SetScrollUpdateNotification( bool enabled )
1878 Actor self = Self();
1879 if( mScrollXUpdateNotification )
1881 // disconnect now to avoid a notification before removed from update thread
1882 mScrollXUpdateNotification.NotifySignal().Disconnect(this, &ScrollView::OnScrollUpdateNotification);
1883 self.RemovePropertyNotification(mScrollXUpdateNotification);
1884 mScrollXUpdateNotification.Reset();
1886 if( enabled && !mScrollUpdatedSignal.Empty())
1888 // Only set up the notification when the application has connected to the updated signal
1889 mScrollXUpdateNotification = self.AddPropertyNotification(Toolkit::ScrollView::Property::SCROLL_POSITION, 0, StepCondition(mScrollUpdateDistance, 0.0f));
1890 mScrollXUpdateNotification.NotifySignal().Connect( this, &ScrollView::OnScrollUpdateNotification );
1892 if( mScrollYUpdateNotification )
1894 // disconnect now to avoid a notification before removed from update thread
1895 mScrollYUpdateNotification.NotifySignal().Disconnect(this, &ScrollView::OnScrollUpdateNotification);
1896 self.RemovePropertyNotification(mScrollYUpdateNotification);
1897 mScrollYUpdateNotification.Reset();
1899 if( enabled && !mScrollUpdatedSignal.Empty())
1901 // Only set up the notification when the application has connected to the updated signal
1902 mScrollYUpdateNotification = self.AddPropertyNotification(Toolkit::ScrollView::Property::SCROLL_POSITION, 1, StepCondition(mScrollUpdateDistance, 0.0f));
1903 mScrollYUpdateNotification.NotifySignal().Connect( this, &ScrollView::OnScrollUpdateNotification );
1907 void ScrollView::OnScrollUpdateNotification(Dali::PropertyNotification& source)
1909 // Guard against destruction during signal emission
1910 Toolkit::ScrollView handle( GetOwner() );
1912 Vector2 currentScrollPosition = GetCurrentScrollPosition();
1913 mScrollUpdatedSignal.Emit( currentScrollPosition );
1916 bool ScrollView::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
1918 Dali::BaseHandle handle( object );
1920 bool connected( true );
1921 Toolkit::ScrollView view = Toolkit::ScrollView::DownCast( handle );
1923 if( 0 == strcmp( signalName.c_str(), SIGNAL_SNAP_STARTED ) )
1925 view.SnapStartedSignal().Connect( tracker, functor );
1929 // signalName does not match any signal
1936 void ScrollView::OnSizeAnimation(Animation& animation, const Vector3& targetSize)
1938 // need to update domain properties for new size
1939 UpdatePropertyDomain();
1942 void ScrollView::OnSizeSet( const Vector3& size )
1944 // need to update domain properties for new size
1945 if( mDefaultMaxOvershoot )
1947 mUserMaxOvershoot.x = size.x * 0.5f;
1948 mUserMaxOvershoot.y = size.y * 0.5f;
1949 if( !IsOvershootEnabled() )
1951 mMaxOvershoot = mUserMaxOvershoot;
1954 UpdatePropertyDomain();
1955 UpdateMainInternalConstraint();
1956 if( IsOvershootEnabled() )
1958 mOvershootIndicator->Reset();
1961 ScrollBase::OnSizeSet( size );
1964 void ScrollView::OnChildAdd(Actor& child)
1966 ScrollBase::OnChildAdd( child );
1968 Dali::Toolkit::ScrollBar scrollBar = Dali::Toolkit::ScrollBar::DownCast(child);
1971 mScrollBar = scrollBar;
1972 scrollBar.SetProperty( Dali::Actor::Property::NAME,"ScrollBar");
1974 mInternalActor.Add( scrollBar );
1975 if( scrollBar.GetScrollDirection() == Toolkit::ScrollBar::HORIZONTAL )
1977 scrollBar.SetScrollPropertySource( Self(),
1978 Toolkit::ScrollView::Property::SCROLL_PRE_POSITION_X,
1979 Toolkit::Scrollable::Property::SCROLL_POSITION_MIN_X,
1980 Toolkit::ScrollView::Property::SCROLL_PRE_POSITION_MAX_X,
1981 Toolkit::ScrollView::Property::SCROLL_DOMAIN_SIZE_X );
1985 scrollBar.SetScrollPropertySource( Self(),
1986 Toolkit::ScrollView::Property::SCROLL_PRE_POSITION_Y,
1987 Toolkit::Scrollable::Property::SCROLL_POSITION_MIN_Y,
1988 Toolkit::ScrollView::Property::SCROLL_PRE_POSITION_MAX_Y,
1989 Toolkit::ScrollView::Property::SCROLL_DOMAIN_SIZE_Y );
1992 if( mTransientScrollBar )
1994 // Show the scroll-indicator for a brief period
1995 Property::Map emptyMap;
1996 scrollBar.DoAction( "ShowTransientIndicator", emptyMap );
1999 else if(mAlterChild)
2005 void ScrollView::OnChildRemove(Actor& child)
2007 // TODO: Actor needs a RemoveConstraint method to take out an individual constraint.
2010 ScrollBase::OnChildRemove( child );
2013 void ScrollView::StartTouchDownTimer()
2015 if ( !mTouchDownTimer )
2017 mTouchDownTimer = Timer::New( TOUCH_DOWN_TIMER_INTERVAL );
2018 mTouchDownTimer.TickSignal().Connect( this, &ScrollView::OnTouchDownTimeout );
2021 mTouchDownTimer.Start();
2024 void ScrollView::StopTouchDownTimer()
2026 if ( mTouchDownTimer )
2028 mTouchDownTimer.Stop();
2032 bool ScrollView::OnTouchDownTimeout()
2034 DALI_LOG_SCROLL_STATE("[0x%X]", this);
2036 mTouchDownTimeoutReached = true;
2038 unsigned int currentScrollStateFlags( mScrollStateFlags ); // Cleared in StopAnimation so keep local copy for comparison
2039 if( currentScrollStateFlags & (SCROLL_ANIMATION_FLAGS | SNAP_ANIMATION_FLAGS) )
2041 DALI_LOG_SCROLL_STATE("[0x%X] Scrolling Or snapping flags set, stopping animation", this);
2044 if( currentScrollStateFlags & SCROLL_ANIMATION_FLAGS )
2046 DALI_LOG_SCROLL_STATE("[0x%X] Scrolling flags set, emitting signal", this);
2048 mScrollInterrupted = true;
2049 // reset domain offset as scrolling from original plane.
2050 mDomainOffset = Vector2::ZERO;
2051 Self().SetProperty(Toolkit::ScrollView::Property::SCROLL_DOMAIN_OFFSET, Vector2::ZERO);
2053 UpdateLocalScrollProperties();
2054 Vector2 currentScrollPosition = GetCurrentScrollPosition();
2055 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignal 4 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
2056 mScrollCompletedSignal.Emit( currentScrollPosition );
2063 bool ScrollView::OnTouch( Actor actor, const TouchEvent& touch )
2067 DALI_LOG_SCROLL_STATE("[0x%X], Not Sensitive, ignoring", this);
2069 // Ignore this touch event, if scrollview is insensitive.
2073 // Ignore events with multiple-touch points
2074 if (touch.GetPointCount() != 1)
2076 DALI_LOG_SCROLL_STATE("[0x%X], multiple touch, ignoring", this);
2081 const PointState::Type pointState = touch.GetState( 0 );
2082 if( pointState == PointState::DOWN )
2084 DALI_LOG_SCROLL_STATE("[0x%X] Down", this);
2086 if(mGestureStackDepth==0)
2088 mTouchDownTime = touch.GetTime();
2090 // This allows time for a pan-gesture to start, to avoid breaking snap-animation behavior with fast flicks.
2091 // If touch-down does not become a pan (after timeout interval), then snap-animation can be interrupted.
2092 mTouchDownTimeoutReached = false;
2093 mScrollInterrupted = false;
2094 StartTouchDownTimer();
2097 else if( ( pointState == PointState::UP ) ||
2098 ( ( pointState == PointState::INTERRUPTED ) && ( touch.GetHitActor( 0 )== Self() ) ) )
2100 DALI_LOG_SCROLL_STATE("[0x%X] %s", this, ( ( pointState == PointState::UP ) ? "Up" : "Interrupted" ) );
2102 StopTouchDownTimer();
2104 // if the user touches and releases without enough movement to go
2105 // into a gesture state, then we should snap to nearest point.
2106 // otherwise our scroll could be stopped (interrupted) half way through an animation.
2107 if(mGestureStackDepth==0 && mTouchDownTimeoutReached)
2109 if( ( pointState == PointState::INTERRUPTED ) ||
2110 ( ( touch.GetTime() - mTouchDownTime ) >= MINIMUM_TIME_BETWEEN_DOWN_AND_UP_FOR_RESET ) )
2112 // Reset the velocity only if down was received a while ago
2113 mLastVelocity = Vector2( 0.0f, 0.0f );
2116 UpdateLocalScrollProperties();
2117 // Only finish the transform if scrolling was interrupted on down or if we are scrolling
2118 if ( mScrollInterrupted || mScrolling )
2120 DALI_LOG_SCROLL_STATE("[0x%X] Calling FinishTransform", this);
2125 mTouchDownTimeoutReached = false;
2126 mScrollInterrupted = false;
2132 bool ScrollView::OnWheelEvent(const WheelEvent& event)
2136 // Ignore this wheel event, if scrollview is insensitive.
2140 Vector2 targetScrollPosition = GetPropertyPosition();
2142 if(mRulerX->IsEnabled() && !mRulerY->IsEnabled())
2144 // If only the ruler in the X axis is enabled, scroll in the X axis.
2145 if(mRulerX->GetType() == Ruler::FREE)
2147 // Free panning mode
2148 targetScrollPosition.x += event.GetDelta() * mWheelScrollDistanceStep.x;
2149 ClampPosition(targetScrollPosition);
2150 ScrollTo(-targetScrollPosition);
2152 else if(!mScrolling)
2154 // Snap mode, only respond to the event when the previous snap animation is finished.
2155 ScrollTo(GetCurrentPage() - event.GetDelta());
2160 // If the ruler in the Y axis is enabled, scroll in the Y axis.
2161 if(mRulerY->GetType() == Ruler::FREE)
2163 // Free panning mode
2164 targetScrollPosition.y += event.GetDelta() * mWheelScrollDistanceStep.y;
2165 ClampPosition(targetScrollPosition);
2166 ScrollTo(-targetScrollPosition);
2168 else if(!mScrolling)
2170 // Snap mode, only respond to the event when the previous snap animation is finished.
2171 ScrollTo(GetCurrentPage() - event.GetDelta() * mRulerX->GetTotalPages());
2178 void ScrollView::ResetScrolling()
2180 Actor self = Self();
2181 self.GetCurrentProperty( Toolkit::ScrollView::Property::SCROLL_POSITION ).Get( mScrollPostPosition );
2182 mScrollPrePosition = mScrollPostPosition;
2183 DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPostPosition.x, mScrollPostPosition.y );
2184 self.SetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, mScrollPostPosition);
2187 void ScrollView::UpdateLocalScrollProperties()
2189 Actor self = Self();
2190 self.GetCurrentProperty( Toolkit::ScrollView::Property::SCROLL_PRE_POSITION ).Get( mScrollPrePosition );
2191 self.GetCurrentProperty( Toolkit::ScrollView::Property::SCROLL_POSITION ).Get( mScrollPostPosition );
2194 // private functions
2196 void ScrollView::PreAnimatedScrollSetup()
2198 // SCROLL_PRE_POSITION is our unclamped property with wrapping
2199 // SCROLL_POSITION is our final scroll position after clamping
2201 Actor self = Self();
2203 Vector2 deltaPosition(mScrollPostPosition);
2204 WrapPosition(mScrollPostPosition);
2205 mDomainOffset += deltaPosition - mScrollPostPosition;
2206 Self().SetProperty(Toolkit::ScrollView::Property::SCROLL_DOMAIN_OFFSET, mDomainOffset);
2208 if( mScrollStateFlags & SCROLL_X_STATE_MASK )
2210 // already performing animation on internal x position
2211 StopAnimation(mInternalXAnimation);
2214 if( mScrollStateFlags & SCROLL_Y_STATE_MASK )
2216 // already performing animation on internal y position
2217 StopAnimation(mInternalYAnimation);
2220 mScrollStateFlags = 0;
2222 // Update Actor position with this wrapped value.
2225 void ScrollView::FinaliseAnimatedScroll()
2227 // TODO - common animation finishing code in here
2230 void ScrollView::AnimateInternalXTo( float position, float duration, AlphaFunction alpha )
2232 StopAnimation(mInternalXAnimation);
2234 if( duration > Math::MACHINE_EPSILON_10 )
2236 Actor self = Self();
2237 DALI_LOG_SCROLL_STATE("[0x%X], Animating from[%.2f] to[%.2f]", this, self.GetCurrentProperty( Toolkit::ScrollView::Property::SCROLL_PRE_POSITION ).Get< Vector2 >().x, position );
2238 mInternalXAnimation = Animation::New(duration);
2239 DALI_LOG_SCROLL_STATE("[0x%X], mInternalXAnimation[0x%X]", this, mInternalXAnimation.GetObjectPtr() );
2240 mInternalXAnimation.FinishedSignal().Connect(this, &ScrollView::OnScrollAnimationFinished);
2241 mInternalXAnimation.AnimateTo( Property(self, Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, 0), position, alpha, TimePeriod(duration));
2242 mInternalXAnimation.Play();
2244 // erase current state flags
2245 mScrollStateFlags &= ~SCROLL_X_STATE_MASK;
2246 // add internal animation state flag
2247 mScrollStateFlags |= AnimatingInternalX;
2251 void ScrollView::AnimateInternalYTo( float position, float duration, AlphaFunction alpha )
2253 StopAnimation(mInternalYAnimation);
2255 if( duration > Math::MACHINE_EPSILON_10 )
2257 Actor self = Self();
2258 DALI_LOG_SCROLL_STATE("[0x%X], Animating from[%.2f] to[%.2f]", this, self.GetCurrentProperty( Toolkit::ScrollView::Property::SCROLL_PRE_POSITION ).Get< Vector2 >().y, position );
2259 mInternalYAnimation = Animation::New(duration);
2260 DALI_LOG_SCROLL_STATE("[0x%X], mInternalYAnimation[0x%X]", this, mInternalYAnimation.GetObjectPtr() );
2261 mInternalYAnimation.FinishedSignal().Connect(this, &ScrollView::OnScrollAnimationFinished);
2262 mInternalYAnimation.AnimateTo( Property(self, Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, 1), position, alpha, TimePeriod(duration));
2263 mInternalYAnimation.Play();
2265 // erase current state flags
2266 mScrollStateFlags &= ~SCROLL_Y_STATE_MASK;
2267 // add internal animation state flag
2268 mScrollStateFlags |= AnimatingInternalY;
2272 void ScrollView::OnScrollAnimationFinished( Animation& source )
2274 // Guard against destruction during signal emission
2275 // Note that ScrollCompletedSignal is emitted from HandleSnapAnimationFinished()
2276 Toolkit::ScrollView handle( GetOwner() );
2278 bool scrollingFinished = false;
2280 // update our local scroll positions
2281 UpdateLocalScrollProperties();
2283 if( source == mInternalXAnimation )
2285 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 );
2287 if( !(mScrollStateFlags & AnimatingInternalY) )
2289 scrollingFinished = true;
2291 mInternalXAnimation.Reset();
2292 // wrap pre scroll x position and set it
2295 const RulerDomain rulerDomain = mRulerX->GetDomain();
2296 mScrollPrePosition.x = -WrapInDomain(-mScrollPrePosition.x, rulerDomain.min, rulerDomain.max);
2297 DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y );
2298 handle.SetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, mScrollPrePosition);
2300 SnapInternalXTo(mScrollPostPosition.x);
2303 if( source == mInternalYAnimation )
2305 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 );
2307 if( !(mScrollStateFlags & AnimatingInternalX) )
2309 scrollingFinished = true;
2311 mInternalYAnimation.Reset();
2314 // wrap pre scroll y position and set it
2315 const RulerDomain rulerDomain = mRulerY->GetDomain();
2316 mScrollPrePosition.y = -WrapInDomain(-mScrollPrePosition.y, rulerDomain.min, rulerDomain.max);
2317 DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y );
2318 handle.SetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, mScrollPrePosition);
2320 SnapInternalYTo(mScrollPostPosition.y);
2323 DALI_LOG_SCROLL_STATE("[0x%X] scrollingFinished[%d] Animation[0x%X]", this, scrollingFinished, source.GetObjectPtr());
2325 if(scrollingFinished)
2327 HandleSnapAnimationFinished();
2331 void ScrollView::OnSnapInternalPositionFinished( Animation& source )
2333 Actor self = Self();
2334 UpdateLocalScrollProperties();
2335 if( source == mInternalXAnimation )
2337 DALI_LOG_SCROLL_STATE("[0x%X] Finished X PostPosition Animation", this );
2339 // clear internal x animation flags
2340 mScrollStateFlags &= ~SCROLL_X_STATE_MASK;
2341 mInternalXAnimation.Reset();
2342 WrapPosition(mScrollPrePosition);
2344 if( source == mInternalYAnimation )
2346 DALI_LOG_SCROLL_STATE("[0x%X] Finished Y PostPosition Animation", this );
2348 mScrollStateFlags &= ~SCROLL_Y_STATE_MASK;
2349 mInternalYAnimation.Reset();
2350 WrapPosition(mScrollPrePosition);
2354 void ScrollView::SnapInternalXTo(float position)
2356 Actor self = Self();
2358 StopAnimation(mInternalXAnimation);
2360 // erase current state flags
2361 mScrollStateFlags &= ~SCROLL_X_STATE_MASK;
2363 // if internal x not equal to inputed parameter, animate it
2364 float duration = std::min(fabsf((position - mScrollPrePosition.x) / mMaxOvershoot.x) * mSnapOvershootDuration, mSnapOvershootDuration);
2365 DALI_LOG_SCROLL_STATE("[0x%X] duration[%.2f]", this, duration );
2366 if( duration > Math::MACHINE_EPSILON_1 )
2368 DALI_LOG_SCROLL_STATE("[0x%X] Starting X Snap Animation to[%.2f]", this, position );
2370 mInternalXAnimation = Animation::New(duration);
2371 mInternalXAnimation.FinishedSignal().Connect(this, &ScrollView::OnSnapInternalPositionFinished);
2372 mInternalXAnimation.AnimateTo(Property(self, Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, 0), position);
2373 mInternalXAnimation.Play();
2375 // add internal animation state flag
2376 mScrollStateFlags |= SnappingInternalX;
2380 void ScrollView::SnapInternalYTo(float position)
2382 Actor self = Self();
2384 StopAnimation(mInternalYAnimation);
2386 // erase current state flags
2387 mScrollStateFlags &= ~SCROLL_Y_STATE_MASK;
2389 // if internal y not equal to inputed parameter, animate it
2390 float duration = std::min(fabsf((position - mScrollPrePosition.y) / mMaxOvershoot.y) * mSnapOvershootDuration, mSnapOvershootDuration);
2391 DALI_LOG_SCROLL_STATE("[0x%X] duration[%.2f]", this, duration );
2392 if( duration > Math::MACHINE_EPSILON_1 )
2394 DALI_LOG_SCROLL_STATE("[0x%X] Starting Y Snap Animation to[%.2f]", this, position );
2396 mInternalYAnimation = Animation::New(duration);
2397 mInternalYAnimation.FinishedSignal().Connect(this, &ScrollView::OnSnapInternalPositionFinished);
2398 mInternalYAnimation.AnimateTo(Property(self, Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, 1), position);
2399 mInternalYAnimation.Play();
2401 // add internal animation state flag
2402 mScrollStateFlags |= SnappingInternalY;
2406 void ScrollView::GestureStarted()
2408 // we handle the first gesture.
2409 // if we're currently doing a gesture and receive another
2410 // we continue and combine the effects of the gesture instead of reseting.
2411 if(mGestureStackDepth++==0)
2413 Actor self = Self();
2414 StopTouchDownTimer();
2416 mPanDelta = Vector2::ZERO;
2417 mLastVelocity = Vector2::ZERO;
2420 mLockAxis = LockPossible;
2423 if( mScrollStateFlags & SCROLL_X_STATE_MASK )
2425 StopAnimation(mInternalXAnimation);
2427 if( mScrollStateFlags & SCROLL_Y_STATE_MASK )
2429 StopAnimation(mInternalYAnimation);
2431 mScrollStateFlags = 0;
2433 if(mScrolling) // are we interrupting a current scroll?
2435 // set mScrolling to false, in case user has code that interrogates mScrolling Getter() in complete.
2437 // send negative scroll position since scroll internal scroll position works as an offset for actors,
2438 // give applications the position within the domain from the scroll view's anchor position
2439 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignal 5 [%.2f, %.2f]", this, -mScrollPostPosition.x, -mScrollPostPosition.y);
2440 mScrollCompletedSignal.Emit( -mScrollPostPosition );
2445 void ScrollView::GestureContinuing(const Vector2& panDelta)
2447 mPanDelta.x+= panDelta.x;
2448 mPanDelta.y+= panDelta.y;
2450 // Save the velocity, there is a bug in PanGesture
2451 // Whereby the Gesture::Finished's velocity is either:
2452 // NaN (due to time delta of zero between the last two events)
2453 // or 0 (due to position being the same between the last two events)
2455 // Axis Auto Lock - locks the panning to the horizontal or vertical axis if the pan
2456 // appears mostly horizontal or mostly vertical respectively.
2459 mLockAxis = GetLockAxis(mPanDelta, mLockAxis, mAxisAutoLockGradient);
2460 } // end if mAxisAutoLock
2463 // TODO: Upgrade to use a more powerful gesture detector (one that supports multiple touches on pan - so works as pan and flick gesture)
2464 // BUG: Gesture::Finished doesn't always return velocity on release (due to
2465 // timeDelta between last two events being 0 sometimes, or posiiton being the same)
2466 void ScrollView::OnPan( const PanGesture& gesture )
2468 // Guard against destruction during signal emission
2469 // Note that Emit() methods are called indirectly e.g. from within ScrollView::OnGestureEx()
2470 Actor self( Self() );
2474 DALI_LOG_SCROLL_STATE("[0x%X] Pan Ignored, Insensitive", this);
2476 // If another callback on the same original signal disables sensitivity,
2477 // this callback will still be called, so we must suppress it.
2481 // translate Gesture input to get useful data...
2482 switch(gesture.GetState())
2484 case Gesture::Started:
2486 DALI_LOG_SCROLL_STATE("[0x%X] Pan Started", this);
2487 const Vector2& position = gesture.GetPosition();
2488 mPanStartPosition = position - gesture.GetDisplacement();
2489 UpdateLocalScrollProperties();
2492 self.SetProperty( Toolkit::ScrollView::Property::PANNING, true );
2493 self.SetProperty( Toolkit::ScrollView::Property::START_PAGE_POSITION, Vector3(position.x, position.y, 0.0f) );
2495 UpdateMainInternalConstraint();
2496 Toolkit::ScrollBar scrollBar = mScrollBar.GetHandle();
2497 if( scrollBar && mTransientScrollBar )
2499 Vector3 size = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
2500 const Toolkit::RulerDomain& rulerDomainX = mRulerX->GetDomain();
2501 const Toolkit::RulerDomain& rulerDomainY = mRulerY->GetDomain();
2503 if( ( rulerDomainX.max > size.width ) || ( rulerDomainY.max > size.height ) )
2505 scrollBar.ShowIndicator();
2511 case Gesture::Continuing:
2515 DALI_LOG_SCROLL_STATE("[0x%X] Pan Continuing", this);
2516 GestureContinuing(gesture.GetScreenDisplacement());
2520 // If we do not think we are panning, then we should not do anything here
2526 case Gesture::Finished:
2527 case Gesture::Cancelled:
2531 DALI_LOG_SCROLL_STATE("[0x%X] Pan %s", this, ( ( gesture.GetState() == Gesture::Finished ) ? "Finished" : "Cancelled" ) );
2533 UpdateLocalScrollProperties();
2534 mLastVelocity = gesture.GetVelocity();
2536 self.SetProperty( Toolkit::ScrollView::Property::PANNING, false );
2538 if( mScrollMainInternalPrePositionConstraint )
2540 mScrollMainInternalPrePositionConstraint.Remove();
2543 Toolkit::ScrollBar scrollBar = mScrollBar.GetHandle();
2544 if( scrollBar && mTransientScrollBar )
2546 scrollBar.HideIndicator();
2551 // If we do not think we are panning, then we should not do anything here
2557 case Gesture::Possible:
2558 case Gesture::Clear:
2560 // Nothing to do, not needed.
2564 } // end switch(gesture.state)
2566 OnGestureEx(gesture.GetState());
2569 void ScrollView::OnGestureEx(Gesture::State state)
2571 // call necessary signals for application developer
2573 if(state == Gesture::Started)
2575 Vector2 currentScrollPosition = GetCurrentScrollPosition();
2576 Self().SetProperty(Toolkit::ScrollView::Property::SCROLLING, true);
2578 DALI_LOG_SCROLL_STATE("[0x%X] mScrollStartedSignal 2 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
2579 mScrollStartedSignal.Emit( currentScrollPosition );
2581 else if( (state == Gesture::Finished) ||
2582 (state == Gesture::Cancelled) ) // Finished/default
2584 // when all the gestures have finished, we finish the transform.
2585 // so if a user decides to pan (1 gesture), and then pan+zoom (2 gestures)
2586 // then stop panning (back to 1 gesture), and then stop zooming (0 gestures).
2587 // this is the point we end, and perform necessary snapping.
2588 mGestureStackDepth--;
2589 if(mGestureStackDepth==0)
2591 // no flick if we have not exceeded min flick distance
2592 if( (fabsf(mPanDelta.x) < mMinFlickDistance.x)
2593 && (fabsf(mPanDelta.y) < mMinFlickDistance.y) )
2595 // reset flick velocity
2596 mLastVelocity = Vector2::ZERO;
2602 DALI_LOG_SCROLL_STATE("[0x%X] mGestureStackDepth[%d]", this, mGestureStackDepth);
2607 void ScrollView::FinishTransform()
2609 // at this stage internal x and x scroll position should have followed prescroll position exactly
2610 Actor self = Self();
2612 PreAnimatedScrollSetup();
2614 // convert pixels/millisecond to pixels per second
2615 bool animating = SnapWithVelocity(mLastVelocity * 1000.0f);
2619 // if not animating, then this pan has completed right now.
2620 SetScrollUpdateNotification(false);
2622 Self().SetProperty(Toolkit::ScrollView::Property::SCROLLING, false);
2624 if( fabs(mScrollPrePosition.x - mScrollTargetPosition.x) > Math::MACHINE_EPSILON_10 )
2626 SnapInternalXTo(mScrollTargetPosition.x);
2628 if( fabs(mScrollPrePosition.y - mScrollTargetPosition.y) > Math::MACHINE_EPSILON_10 )
2630 SnapInternalYTo(mScrollTargetPosition.y);
2632 Vector2 currentScrollPosition = GetCurrentScrollPosition();
2633 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignal 6 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
2634 mScrollCompletedSignal.Emit( currentScrollPosition );
2638 Vector2 ScrollView::GetOvershoot(Vector2& position) const
2640 Vector3 size = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
2643 const RulerDomain rulerDomainX = mRulerX->GetDomain();
2644 const RulerDomain rulerDomainY = mRulerY->GetDomain();
2646 if(mRulerX->IsEnabled() && rulerDomainX.enabled)
2648 const float left = rulerDomainX.min - position.x;
2649 const float right = size.width - rulerDomainX.max - position.x;
2656 overshoot.x = right;
2660 if(mRulerY->IsEnabled() && rulerDomainY.enabled)
2662 const float top = rulerDomainY.min - position.y;
2663 const float bottom = size.height - rulerDomainY.max - position.y;
2670 overshoot.y = bottom;
2677 bool ScrollView::OnAccessibilityPan(PanGesture gesture)
2679 // Keep track of whether this is an AccessibilityPan
2680 mInAccessibilityPan = true;
2682 mInAccessibilityPan = false;
2687 void ScrollView::ClampPosition(Vector2& position) const
2689 ClampState2D clamped;
2690 ClampPosition(position, clamped);
2693 void ScrollView::ClampPosition(Vector2& position, ClampState2D &clamped) const
2695 Vector3 size = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
2697 position.x = -mRulerX->Clamp(-position.x, size.width, 1.0f, clamped.x); // NOTE: X & Y rulers think in -ve coordinate system.
2698 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.
2701 void ScrollView::WrapPosition(Vector2& position) const
2705 const RulerDomain rulerDomainX = mRulerX->GetDomain();
2706 const RulerDomain rulerDomainY = mRulerY->GetDomain();
2708 if(mRulerX->IsEnabled())
2710 position.x = -WrapInDomain(-position.x, rulerDomainX.min, rulerDomainX.max);
2713 if(mRulerY->IsEnabled())
2715 position.y = -WrapInDomain(-position.y, rulerDomainY.min, rulerDomainY.max);
2720 void ScrollView::UpdateMainInternalConstraint()
2722 // TODO: Only update the constraints which have changed, rather than remove all and add all again.
2723 // Requires a dali-core ApplyConstraintAt, or a ReplaceConstraint. The former is probably more flexible.
2724 Actor self = Self();
2725 PanGestureDetector detector( GetPanGestureDetector() );
2727 if(mScrollMainInternalPositionConstraint)
2729 mScrollMainInternalPositionConstraint.Remove();
2730 mScrollMainInternalDeltaConstraint.Remove();
2731 mScrollMainInternalFinalConstraint.Remove();
2732 mScrollMainInternalRelativeConstraint.Remove();
2733 mScrollMainInternalDomainConstraint.Remove();
2734 mScrollMainInternalPrePositionMaxConstraint.Remove();
2736 if( mScrollMainInternalPrePositionConstraint )
2738 mScrollMainInternalPrePositionConstraint.Remove();
2741 // TODO: It's probably better to use a local displacement value as this will give a displacement when scrolling just commences
2742 // but we need to make sure than the gesture system gives displacement since last frame (60Hz), not displacement since last touch event (90Hz).
2744 // 1. First calculate the pre-position (this is the scroll position if no clamping has taken place)
2745 Vector2 initialPanMask = Vector2(mRulerX->IsEnabled() ? 1.0f : 0.0f, mRulerY->IsEnabled() ? 1.0f : 0.0f);
2747 if( mLockAxis == LockVertical )
2749 initialPanMask.y = 0.0f;
2751 else if( mLockAxis == LockHorizontal )
2753 initialPanMask.x = 0.0f;
2758 mScrollMainInternalPrePositionConstraint = Constraint::New<Vector2>( self,
2759 Toolkit::ScrollView::Property::SCROLL_PRE_POSITION,
2760 InternalPrePositionConstraint( mPanStartPosition,
2763 mAxisAutoLockGradient,
2768 mScrollMainInternalPrePositionConstraint.AddSource( Source( detector, PanGestureDetector::Property::LOCAL_POSITION ) );
2769 mScrollMainInternalPrePositionConstraint.AddSource( Source( detector, PanGestureDetector::Property::PANNING ) );
2770 mScrollMainInternalPrePositionConstraint.AddSource( Source( self, Actor::Property::SIZE ) );
2771 mScrollMainInternalPrePositionConstraint.Apply();
2774 // 2. Second calculate the clamped position (actual position)
2775 mScrollMainInternalPositionConstraint = Constraint::New<Vector2>( self,
2776 Toolkit::ScrollView::Property::SCROLL_POSITION,
2777 InternalPositionConstraint( mRulerX->GetDomain(),
2778 mRulerY->GetDomain(),
2780 mScrollMainInternalPositionConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_PRE_POSITION ) );
2781 mScrollMainInternalPositionConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::SCROLL_POSITION_MIN ) );
2782 mScrollMainInternalPositionConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::SCROLL_POSITION_MAX ) );
2783 mScrollMainInternalPositionConstraint.AddSource( Source( self, Actor::Property::SIZE ) );
2784 mScrollMainInternalPositionConstraint.Apply();
2786 mScrollMainInternalDeltaConstraint = Constraint::New<Vector2>( self, Toolkit::ScrollView::Property::SCROLL_POSITION_DELTA, InternalPositionDeltaConstraint );
2787 mScrollMainInternalDeltaConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_POSITION ) );
2788 mScrollMainInternalDeltaConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_DOMAIN_OFFSET ) );
2789 mScrollMainInternalDeltaConstraint.Apply();
2791 mScrollMainInternalFinalConstraint = Constraint::New<Vector2>( self, Toolkit::ScrollView::Property::SCROLL_FINAL,
2792 InternalFinalConstraint( FinalDefaultAlphaFunction,
2793 FinalDefaultAlphaFunction ) );
2794 mScrollMainInternalFinalConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_POSITION ) );
2795 mScrollMainInternalFinalConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::OVERSHOOT_X ) );
2796 mScrollMainInternalFinalConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::OVERSHOOT_Y ) );
2797 mScrollMainInternalFinalConstraint.Apply();
2799 mScrollMainInternalRelativeConstraint = Constraint::New<Vector2>( self, Toolkit::Scrollable::Property::SCROLL_RELATIVE_POSITION, InternalRelativePositionConstraint );
2800 mScrollMainInternalRelativeConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_POSITION ) );
2801 mScrollMainInternalRelativeConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::SCROLL_POSITION_MIN ) );
2802 mScrollMainInternalRelativeConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::SCROLL_POSITION_MAX ) );
2803 mScrollMainInternalRelativeConstraint.AddSource( LocalSource( Actor::Property::SIZE ) );
2804 mScrollMainInternalRelativeConstraint.Apply();
2806 mScrollMainInternalDomainConstraint = Constraint::New<Vector2>( self, Toolkit::ScrollView::Property::SCROLL_DOMAIN_SIZE, InternalScrollDomainConstraint );
2807 mScrollMainInternalDomainConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::SCROLL_POSITION_MIN ) );
2808 mScrollMainInternalDomainConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::SCROLL_POSITION_MAX ) );
2809 mScrollMainInternalDomainConstraint.AddSource( LocalSource( Actor::Property::SIZE ) );
2810 mScrollMainInternalDomainConstraint.Apply();
2812 mScrollMainInternalPrePositionMaxConstraint = Constraint::New<Vector2>( self, Toolkit::ScrollView::Property::SCROLL_PRE_POSITION_MAX, InternalPrePositionMaxConstraint );
2813 mScrollMainInternalPrePositionMaxConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::SCROLL_POSITION_MAX ) );
2814 mScrollMainInternalPrePositionMaxConstraint.AddSource( LocalSource( Actor::Property::SIZE ) );
2815 mScrollMainInternalPrePositionMaxConstraint.Apply();
2817 // When panning we want to make sure overshoot values are affected by pre position and post position
2818 SetOvershootConstraintsEnabled(!mWrapMode);
2821 void ScrollView::SetOvershootConstraintsEnabled(bool enabled)
2823 Actor self( Self() );
2824 // remove and reset, it may now be in wrong order with the main internal constraints
2825 if( mScrollMainInternalOvershootXConstraint )
2827 mScrollMainInternalOvershootXConstraint.Remove();
2828 mScrollMainInternalOvershootXConstraint.Reset();
2829 mScrollMainInternalOvershootYConstraint.Remove();
2830 mScrollMainInternalOvershootYConstraint.Reset();
2834 mScrollMainInternalOvershootXConstraint= Constraint::New<float>( self, Toolkit::ScrollView::Property::OVERSHOOT_X, OvershootXConstraint(mMaxOvershoot.x) );
2835 mScrollMainInternalOvershootXConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_PRE_POSITION ) );
2836 mScrollMainInternalOvershootXConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_POSITION ) );
2837 mScrollMainInternalOvershootXConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::CAN_SCROLL_HORIZONTAL ) );
2838 mScrollMainInternalOvershootXConstraint.Apply();
2840 mScrollMainInternalOvershootYConstraint = Constraint::New<float>( self, Toolkit::ScrollView::Property::OVERSHOOT_Y, OvershootYConstraint(mMaxOvershoot.y) );
2841 mScrollMainInternalOvershootYConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_PRE_POSITION ) );
2842 mScrollMainInternalOvershootYConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_POSITION ) );
2843 mScrollMainInternalOvershootYConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::CAN_SCROLL_VERTICAL ) );
2844 mScrollMainInternalOvershootYConstraint.Apply();
2848 self.SetProperty(Toolkit::ScrollView::Property::OVERSHOOT_X, 0.0f);
2849 self.SetProperty(Toolkit::ScrollView::Property::OVERSHOOT_Y, 0.0f);
2853 void ScrollView::SetInternalConstraints()
2855 // Internal constraints (applied to target ScrollBase Actor itself) /////////
2856 UpdateMainInternalConstraint();
2858 // User definable constraints to apply to all child actors //////////////////
2859 Actor self = Self();
2861 // Apply some default constraints to ScrollView & its bound actors
2862 // Movement + Wrap function
2864 Constraint constraint;
2866 // MoveActor (scrolling)
2867 constraint = Constraint::New<Vector3>( self, Actor::Property::POSITION, MoveActorConstraint );
2868 constraint.AddSource( Source( self, Toolkit::ScrollView::Property::SCROLL_POSITION ) );
2869 constraint.SetRemoveAction(Constraint::DISCARD);
2870 ApplyConstraintToBoundActors(constraint);
2872 // WrapActor (wrap functionality)
2873 constraint = Constraint::New<Vector3>( self, Actor::Property::POSITION, WrapActorConstraint );
2874 constraint.AddSource( LocalSource( Actor::Property::SCALE ) );
2875 constraint.AddSource( LocalSource( Actor::Property::ANCHOR_POINT ) );
2876 constraint.AddSource( LocalSource( Actor::Property::SIZE ) );
2877 constraint.AddSource( Source( self, Toolkit::Scrollable::Property::SCROLL_POSITION_MIN ) );
2878 constraint.AddSource( Source( self, Toolkit::Scrollable::Property::SCROLL_POSITION_MAX ) );
2879 constraint.AddSource( Source( self, Toolkit::ScrollView::Property::WRAP ) );
2880 constraint.SetRemoveAction(Constraint::DISCARD);
2881 ApplyConstraintToBoundActors(constraint);
2884 void ScrollView::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
2886 Toolkit::ScrollView scrollView = Toolkit::ScrollView::DownCast( Dali::BaseHandle( object ) );
2890 ScrollView& scrollViewImpl( GetImpl( scrollView ) );
2893 case Toolkit::ScrollView::Property::WRAP_ENABLED:
2895 scrollViewImpl.SetWrapMode( value.Get<bool>() );
2898 case Toolkit::ScrollView::Property::PANNING_ENABLED:
2900 scrollViewImpl.SetScrollSensitive( value.Get<bool>() );
2903 case Toolkit::ScrollView::Property::AXIS_AUTO_LOCK_ENABLED:
2905 scrollViewImpl.SetAxisAutoLock( value.Get<bool>() );
2908 case Toolkit::ScrollView::Property::WHEEL_SCROLL_DISTANCE_STEP:
2910 scrollViewImpl.SetWheelScrollDistanceStep( value.Get<Vector2>() );
2913 case Toolkit::ScrollView::Property::SCROLL_MODE:
2915 Property::Map* map = value.GetMap();
2918 scrollViewImpl.SetScrollMode( *map );
2925 Property::Value ScrollView::GetProperty( BaseObject* object, Property::Index index )
2927 Property::Value value;
2929 Toolkit::ScrollView scrollView = Toolkit::ScrollView::DownCast( Dali::BaseHandle( object ) );
2933 ScrollView& scrollViewImpl( GetImpl( scrollView ) );
2936 case Toolkit::ScrollView::Property::WRAP_ENABLED:
2938 value = scrollViewImpl.GetWrapMode();
2941 case Toolkit::ScrollView::Property::PANNING_ENABLED:
2943 value = scrollViewImpl.GetScrollSensitive();
2946 case Toolkit::ScrollView::Property::AXIS_AUTO_LOCK_ENABLED:
2948 value = scrollViewImpl.GetAxisAutoLock();
2951 case Toolkit::ScrollView::Property::WHEEL_SCROLL_DISTANCE_STEP:
2953 value = scrollViewImpl.GetWheelScrollDistanceStep();
2962 void ScrollView::SetScrollMode( const Property::Map& scrollModeMap )
2964 Toolkit::RulerPtr rulerX, rulerY;
2966 // Check the scroll mode in the X axis
2967 bool xAxisScrollEnabled = true;
2968 Property::Value* valuePtr = scrollModeMap.Find( Toolkit::ScrollMode::X_AXIS_SCROLL_ENABLED, "xAxisScrollEnabled" );
2969 if( valuePtr && valuePtr->GetType() == Property::BOOLEAN )
2971 valuePtr->Get( xAxisScrollEnabled );
2974 if( !xAxisScrollEnabled )
2976 // Default ruler and disabled
2977 rulerX = new Toolkit::DefaultRuler();
2982 valuePtr = scrollModeMap.Find( Toolkit::ScrollMode::X_AXIS_SNAP_TO_INTERVAL, "xAxisSnapToInterval" );
2983 float xAxisSnapToInterval = 0.0f;
2984 if( valuePtr && valuePtr->Get( xAxisSnapToInterval ) )
2986 // Fixed ruler and enabled
2987 rulerX = new Toolkit::FixedRuler( xAxisSnapToInterval );
2991 // Default ruler and enabled
2992 rulerX = new Toolkit::DefaultRuler();
2995 valuePtr = scrollModeMap.Find( Toolkit::ScrollMode::X_AXIS_SCROLL_BOUNDARY, "xAxisScrollBoundary" );
2996 float xAxisScrollBoundary = 0.0f;
2997 if( valuePtr && valuePtr->Get( xAxisScrollBoundary ) )
2999 // By default ruler domain is disabled unless set
3000 rulerX->SetDomain( Toolkit::RulerDomain( 0, xAxisScrollBoundary, true ) );
3004 // Check the scroll mode in the Y axis
3005 bool yAxisScrollEnabled = true;
3006 valuePtr = scrollModeMap.Find( Toolkit::ScrollMode::Y_AXIS_SCROLL_ENABLED, "yAxisScrollEnabled" );
3007 if( valuePtr && valuePtr->GetType() == Property::BOOLEAN )
3009 valuePtr->Get( yAxisScrollEnabled );
3012 if( !yAxisScrollEnabled )
3014 // Default ruler and disabled
3015 rulerY = new Toolkit::DefaultRuler();
3020 valuePtr = scrollModeMap.Find( Toolkit::ScrollMode::Y_AXIS_SNAP_TO_INTERVAL, "yAxisSnapToInterval" );
3021 float yAxisSnapToInterval = 0.0f;
3022 if( valuePtr && valuePtr->Get( yAxisSnapToInterval ) )
3024 // Fixed ruler and enabled
3025 rulerY = new Toolkit::FixedRuler(yAxisSnapToInterval);
3029 // Default ruler and enabled
3030 rulerY = new Toolkit::DefaultRuler();
3033 valuePtr = scrollModeMap.Find( Toolkit::ScrollMode::Y_AXIS_SCROLL_BOUNDARY, "yAxisScrollBoundary" );
3034 float yAxisScrollBoundary = 0.0f;
3035 if( valuePtr && valuePtr->Get( yAxisScrollBoundary ) )
3037 // By default ruler domain is disabled unless set
3038 rulerY->SetDomain( Toolkit::RulerDomain( 0, yAxisScrollBoundary, true ) );
3046 } // namespace Internal
3048 } // namespace Toolkit