2 * Copyright (c) 2017 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/public-api/common/stage.h>
25 #include <dali/public-api/events/wheel-event.h>
26 #include <dali/public-api/events/touch-data.h>
27 #include <dali/public-api/object/type-registry.h>
28 #include <dali/public-api/object/type-registry-helper.h>
29 #include <dali/public-api/object/property-map.h>
30 #include <dali/devel-api/object/handle-devel.h>
31 #include <dali/integration-api/debug.h>
34 #include <dali-toolkit/public-api/controls/scroll-bar/scroll-bar.h>
35 #include <dali-toolkit/public-api/controls/scrollable/scroll-view/scroll-view.h>
36 #include <dali-toolkit/public-api/controls/scrollable/scroll-view/scroll-view-constraints.h>
37 #include <dali-toolkit/internal/controls/scrollable/scroll-view/scroll-overshoot-indicator-impl.h>
38 #include <dali-toolkit/internal/controls/scrollable/scroll-view/scroll-view-effect-impl.h>
40 //#define ENABLED_SCROLL_STATE_LOGGING
42 #ifdef ENABLED_SCROLL_STATE_LOGGING
43 #define DALI_LOG_SCROLL_STATE(format, args...) Dali::Integration::Log::LogMessage(Dali::Integration::Log::DebugInfo, "%s:%d " format "\n", __PRETTY_FUNCTION__, __LINE__, ## args)
45 #define DALI_LOG_SCROLL_STATE(format, args...)
48 // TODO: Change to two class system:
49 // 1. DraggableActor (is an actor which can be dragged anywhere, can be set to range using the ruler)
50 // 2. ScrollView (contains a draggable actor that can a) be dragged in the negative X, and Y domain, b) has a hitArea for touches)
51 // TODO: external components (page and status overlays).
53 // TODO: upgrade Vector2/3 to support returning Unit vectors, normals, & cross product (dot product is already provided)
59 const float DEFAULT_SLOW_SNAP_ANIMATION_DURATION(0.5f); ///< Default Drag-Release animation time.
60 const float DEFAULT_FAST_SNAP_ANIMATION_DURATION(0.25f); ///< Default Drag-Flick animation time.
61 const float DEFAULT_SNAP_OVERSHOOT_DURATION(0.5f); ///< Default Overshoot snapping animation time.
62 const float DEFAULT_MAX_OVERSHOOT(100.0f); ///< Default maximum allowed overshoot in pixels
64 const float DEFAULT_AXIS_AUTO_LOCK_GRADIENT(0.36f); ///< Default Axis-AutoLock gradient threshold. default is 0.36:1 (20 degrees)
65 const float DEFAULT_FRICTION_COEFFICIENT(1.0f); ///< Default Friction Co-efficient. (in stage diagonals per second)
66 const float DEFAULT_FLICK_SPEED_COEFFICIENT(1.0f); ///< Default Flick speed coefficient (multiples input touch velocity)
67 const float DEFAULT_MAX_FLICK_SPEED(3.0f); ///< Default Maximum flick speed. (in stage diagonals per second)
69 const Vector2 DEFAULT_MIN_FLICK_DISTANCE(30.0f, 30.0f); ///< minimum distance for pan before flick allowed
70 const float DEFAULT_MIN_FLICK_SPEED_THRESHOLD(500.0f); ///< Minimum pan speed required for flick in pixels/s
71 const float FREE_FLICK_SPEED_THRESHOLD = 200.0f; ///< Free-Flick threshold in pixels/ms
72 const float AUTOLOCK_AXIS_MINIMUM_DISTANCE2 = 100.0f; ///< Auto-lock axis after minimum distance squared.
73 const float FLICK_ORTHO_ANGLE_RANGE = 75.0f; ///< degrees. (if >45, then supports diagonal flicking)
74 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.
75 const unsigned long MINIMUM_TIME_BETWEEN_DOWN_AND_UP_FOR_RESET( 150u );
76 const float TOUCH_DOWN_TIMER_INTERVAL = 100.0f;
77 const float DEFAULT_SCROLL_UPDATE_DISTANCE( 30.0f ); ///< Default distance to travel in pixels for scroll update signal
79 const std::string INTERNAL_MAX_POSITION_PROPERTY_NAME( "internalMaxPosition" );
81 // Helpers ////////////////////////////////////////////////////////////////////////////////////////
84 * Find the vector (distance) from (a) to (b)
85 * in domain (start) to (end)
86 * (\ / start) (\ / end)
89 * @note assumes both (a) and (b) are already with the domain
92 * @param[in] a the current point
93 * @param[in] b the target point
94 * @param[in] start the start of the domain
95 * @param[in] end the end of the domain
96 * @param[in] bias whether to only take the right direction or the left direction,
97 * or the shortest direction.
98 * @return the shortest direction and distance
100 float VectorInDomain(float a, float b, float start, float end, Dali::Toolkit::DirectionBias bias)
102 if(bias == Dali::Toolkit::DirectionBiasNone)
104 return ShortestDistanceInDomain( a, b, start, end );
107 float size = end-start;
113 if(bias == Dali::Toolkit::DirectionBiasRight) // going right, take the vector.
119 float aRight = a+size;
126 if(bias == Dali::Toolkit::DirectionBiasLeft) // going left, take the vector.
132 float aLeft = a-size;
139 * Returns the position of the anchor within actor
141 * @param actor The Actor
142 * @param anchor The Anchor point of interest.
143 * @return The position of the Anchor
145 Vector3 GetPositionOfAnchor(Actor &actor, const Vector3 &anchor)
147 Vector3 childPosition = actor.GetCurrentPosition();
148 Vector3 childAnchor = - actor.GetCurrentAnchorPoint() + anchor;
149 Vector3 childSize = actor.GetCurrentSize();
151 return childPosition + childAnchor * childSize;
154 // AlphaFunctions /////////////////////////////////////////////////////////////////////////////////
156 float FinalDefaultAlphaFunction(float offset)
158 return offset * 0.5f;
162 * ConstantDecelerationAlphaFunction
163 * Newtoninan distance for constant deceleration
164 * v = 1 - t, s = t - 1/2 t^2
165 * when t = 0, s = 0.0 (min distance)
166 * when t = 1, s = 0.5 (max distance)
167 * progress = s / (max-min) = 2t - t^2
169 * @param[in] offset The input progress
170 * @return The output progress
172 float ConstantDecelerationAlphaFunction(float progress)
174 return progress * 2.0f - progress * progress;
177 // Internal Constraints ///////////////////////////////////////////////////////////////////////////
180 * Internal Relative position Constraint
181 * Generates the relative position value of the scroll view
182 * based on the absolute position, and it's relation to the
183 * scroll domain. This is a value from 0.0f to 1.0f in each
184 * scroll position axis.
186 void InternalRelativePositionConstraint( Vector2& relativePosition, const PropertyInputContainer& inputs)
188 Vector2 position = -inputs[0]->GetVector2();
189 const Vector2& min = inputs[1]->GetVector2();
190 const Vector2& max = inputs[2]->GetVector2();
191 const Vector3& size = inputs[3]->GetVector3();
193 position.x = WrapInDomain(position.x, min.x, max.x);
194 position.y = WrapInDomain(position.y, min.y, max.y);
196 Vector2 domainSize = (max - min) - size.GetVectorXY();
198 relativePosition.x = domainSize.x > Math::MACHINE_EPSILON_1 ? fabsf((position.x - min.x) / domainSize.x) : 0.0f;
199 relativePosition.y = domainSize.y > Math::MACHINE_EPSILON_1 ? fabsf((position.y - min.y) / domainSize.y) : 0.0f;
203 * Internal scroll domain Constraint
204 * Generates the scroll domain of the scroll view.
206 void InternalScrollDomainConstraint( Vector2& scrollDomain, const PropertyInputContainer& inputs)
208 const Vector2& min = inputs[0]->GetVector2();
209 const Vector2& max = inputs[1]->GetVector2();
210 const Vector3& size = inputs[2]->GetVector3();
212 scrollDomain = (max - min) - size.GetVectorXY();
216 * Internal maximum scroll position Constraint
217 * Generates the maximum scroll position of the scroll view.
219 void InternalPrePositionMaxConstraint( Vector2& scrollMax, const PropertyInputContainer& inputs)
221 const Vector2& max = inputs[0]->GetVector2();
222 const Vector3& size = inputs[1]->GetVector3();
224 scrollMax = max - size.GetVectorXY();
227 } // unnamed namespace
243 return Toolkit::ScrollView::New();
246 // Setup properties, signals and actions using the type-registry.
247 DALI_TYPE_REGISTRATION_BEGIN( Toolkit::ScrollView, Toolkit::Scrollable, Create )
249 DALI_PROPERTY_REGISTRATION( Toolkit, ScrollView, "wrapEnabled", BOOLEAN, WRAP_ENABLED )
250 DALI_PROPERTY_REGISTRATION( Toolkit, ScrollView, "panningEnabled", BOOLEAN, PANNING_ENABLED )
251 DALI_PROPERTY_REGISTRATION( Toolkit, ScrollView, "axisAutoLockEnabled", BOOLEAN, AXIS_AUTO_LOCK_ENABLED )
252 DALI_PROPERTY_REGISTRATION( Toolkit, ScrollView, "wheelScrollDistanceStep", VECTOR2, WHEEL_SCROLL_DISTANCE_STEP )
254 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "scrollPosition", VECTOR2, SCROLL_POSITION)
255 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "scrollPrePosition", VECTOR2, SCROLL_PRE_POSITION)
256 DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, ScrollView, "scrollPrePositionX", SCROLL_PRE_POSITION_X, SCROLL_PRE_POSITION, 0)
257 DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, ScrollView, "scrollPrePositionY", SCROLL_PRE_POSITION_Y, SCROLL_PRE_POSITION, 1)
258 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "scrollPrePositionMax", VECTOR2, SCROLL_PRE_POSITION_MAX)
259 DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, ScrollView, "scrollPrePositionMaxX", SCROLL_PRE_POSITION_MAX_X, SCROLL_PRE_POSITION_MAX, 0)
260 DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, ScrollView, "scrollPrePositionMaxY", SCROLL_PRE_POSITION_MAX_Y, SCROLL_PRE_POSITION_MAX, 1)
261 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "overshootX", FLOAT, OVERSHOOT_X)
262 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "overshootY", FLOAT, OVERSHOOT_Y)
263 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "scrollFinal", VECTOR2, SCROLL_FINAL)
264 DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, ScrollView, "scrollFinalX", SCROLL_FINAL_X, SCROLL_FINAL,0)
265 DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, ScrollView, "scrollFinalY", SCROLL_FINAL_Y, SCROLL_FINAL,1)
266 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "wrap", BOOLEAN, WRAP)
267 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "panning", BOOLEAN, PANNING)
268 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "scrolling", BOOLEAN, SCROLLING)
269 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "scrollDomainSize", VECTOR2, SCROLL_DOMAIN_SIZE)
270 DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, ScrollView, "scrollDomainSizeX", SCROLL_DOMAIN_SIZE_X, SCROLL_DOMAIN_SIZE, 0)
271 DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, ScrollView, "scrollDomainSizeY", SCROLL_DOMAIN_SIZE_Y, SCROLL_DOMAIN_SIZE, 1)
272 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "scrollDomainOffset", VECTOR2, SCROLL_DOMAIN_OFFSET)
273 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "scrollPositionDelta", VECTOR2, SCROLL_POSITION_DELTA)
274 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "startPagePosition", VECTOR3, START_PAGE_POSITION)
276 DALI_SIGNAL_REGISTRATION( Toolkit, ScrollView, "valueChanged", SIGNAL_SNAP_STARTED )
278 DALI_TYPE_REGISTRATION_END()
281 * Returns whether to lock scrolling to a particular axis
283 * @param[in] panDelta Distance panned since gesture started
284 * @param[in] currentLockAxis The current lock axis value
285 * @param[in] lockGradient How quickly to lock to a particular axis
287 * @return The new axis lock state
289 ScrollView::LockAxis GetLockAxis(const Vector2& panDelta, ScrollView::LockAxis currentLockAxis, float lockGradient)
291 if(panDelta.LengthSquared() > AUTOLOCK_AXIS_MINIMUM_DISTANCE2 &&
292 currentLockAxis == ScrollView::LockPossible)
294 float dx = fabsf(panDelta.x);
295 float dy = fabsf(panDelta.y);
296 if(dx * lockGradient >= dy)
298 // 0.36:1 gradient to the horizontal (deviate < 20 degrees)
299 currentLockAxis = ScrollView::LockVertical;
301 else if(dy * lockGradient > dx)
303 // 0.36:1 gradient to the vertical (deviate < 20 degrees)
304 currentLockAxis = ScrollView::LockHorizontal;
308 currentLockAxis = ScrollView::LockNone;
311 return currentLockAxis;
315 * Internal Pre-Position Property Constraint.
317 * Generates position property based on current position + gesture displacement.
318 * Or generates position property based on positionX/Y.
319 * Note: This is the position prior to any clamping at scroll boundaries.
321 struct InternalPrePositionConstraint
323 InternalPrePositionConstraint( const Vector2& initialPanPosition,
324 const Vector2& initialPanMask,
326 float axisAutoLockGradient,
327 ScrollView::LockAxis initialLockAxis,
328 const Vector2& maxOvershoot,
329 const RulerPtr& rulerX, const RulerPtr& rulerY )
330 : mLocalStart( initialPanPosition ),
331 mInitialPanMask( initialPanMask ),
332 mMaxOvershoot( maxOvershoot ),
333 mAxisAutoLockGradient( axisAutoLockGradient ),
334 mLockAxis( initialLockAxis ),
335 mAxisAutoLock( axisAutoLock ),
338 const RulerDomain& rulerDomainX = rulerX->GetDomain();
339 const RulerDomain& rulerDomainY = rulerY->GetDomain();
340 mDomainMin = Vector2( rulerDomainX.min, -rulerDomainY.min );
341 mDomainMax = Vector2( -rulerDomainX.max, -rulerDomainY.max );
342 mClampX = rulerDomainX.enabled;
343 mClampY = rulerDomainY.enabled;
344 mFixedRulerX = rulerX->GetType() == Ruler::Fixed;
345 mFixedRulerY = rulerY->GetType() == Ruler::Fixed;
348 void operator()( Vector2& scrollPostPosition, const PropertyInputContainer& inputs )
350 const Vector2& panPosition = inputs[0]->GetVector2();
351 const bool& inGesture = inputs[1]->GetBoolean();
353 // First check if we are within a gesture.
354 // The ScrollView may have received a start gesture from ::OnPan()
355 // while the finish gesture is received now in this constraint.
356 // This gesture must then be rejected as the value will be "old".
357 // Typically the last value from the end of the last gesture.
358 // If we are rejecting the gesture, we simply don't modify the constraint target.
363 mPrePosition = scrollPostPosition;
364 mStartPosition = mPrePosition;
365 mCurrentPanMask = mInitialPanMask;
369 // Calculate Deltas...
370 const Vector2& currentPosition = panPosition;
371 Vector2 panDelta( currentPosition - mLocalStart );
373 // Axis Auto Lock - locks the panning to the horizontal or vertical axis if the pan
374 // appears mostly horizontal or mostly vertical respectively...
377 mLockAxis = GetLockAxis( panDelta, mLockAxis, mAxisAutoLockGradient );
378 if( mLockAxis == ScrollView::LockVertical )
380 mCurrentPanMask.y = 0.0f;
382 else if( mLockAxis == ScrollView::LockHorizontal )
384 mCurrentPanMask.x = 0.0f;
388 // Restrict deltas based on ruler enable/disable and axis-lock state...
389 panDelta *= mCurrentPanMask;
391 // Perform Position transform based on input deltas...
392 scrollPostPosition = mPrePosition;
393 scrollPostPosition += panDelta;
395 // if no wrapping then clamp preposition to maximum overshoot amount
396 const Vector3& size = inputs[2]->GetVector3();
399 float newXPosition = Clamp( scrollPostPosition.x, ( mDomainMax.x + size.x ) - mMaxOvershoot.x, mDomainMin.x + mMaxOvershoot.x );
400 if( (newXPosition < scrollPostPosition.x - Math::MACHINE_EPSILON_1)
401 || (newXPosition > scrollPostPosition.x + Math::MACHINE_EPSILON_1) )
403 mPrePosition.x = newXPosition;
404 mLocalStart.x = panPosition.x;
406 scrollPostPosition.x = newXPosition;
410 float newYPosition = Clamp( scrollPostPosition.y, ( mDomainMax.y + size.y ) - mMaxOvershoot.y, mDomainMin.y + mMaxOvershoot.y );
411 if( ( newYPosition < scrollPostPosition.y - Math::MACHINE_EPSILON_1 )
412 || ( newYPosition > scrollPostPosition.y + Math::MACHINE_EPSILON_1 ) )
414 mPrePosition.y = newYPosition;
415 mLocalStart.y = panPosition.y;
417 scrollPostPosition.y = newYPosition;
420 // If we are using a fixed ruler in a particular axis, limit the maximum pages scrolled on that axis.
421 if( mFixedRulerX || mFixedRulerY )
423 // Here we limit the maximum amount that can be moved from the starting position of the gesture to one page.
424 // We do this only if we have a fixed ruler (on that axis) and the mode is enabled.
425 // Note: 1.0f is subtracted to keep the value within one page size (otherwise we stray on to the page after).
426 // Note: A further 1.0f is subtracted to handle a compensation that happens later within the flick handling code in SnapWithVelocity().
427 // When a flick is completed, an adjustment of 1.0f is sometimes made to allow for the scenario where:
428 // A flick finishes before the update thread has advanced the scroll position past the previous snap point.
429 Vector2 pageSizeLimit( size.x - ( 1.0f + 1.0f ), size.y - ( 1.0f - 1.0f ) );
430 Vector2 minPosition( mStartPosition.x - pageSizeLimit.x, mStartPosition.y - pageSizeLimit.y );
431 Vector2 maxPosition( mStartPosition.x + pageSizeLimit.x, mStartPosition.y + pageSizeLimit.y );
435 scrollPostPosition.x = Clamp( scrollPostPosition.x, minPosition.x, maxPosition.x );
439 scrollPostPosition.y = Clamp( scrollPostPosition.y, minPosition.y, maxPosition.y );
445 Vector2 mPrePosition;
447 Vector2 mStartPosition; ///< The start position of the gesture - used to limit scroll amount (not modified by clamping).
448 Vector2 mInitialPanMask; ///< Initial pan mask (based on ruler settings).
449 Vector2 mCurrentPanMask; ///< Current pan mask that can be altered by axis lock mode.
452 Vector2 mMaxOvershoot;
454 float mAxisAutoLockGradient; ///< Set by ScrollView
455 ScrollView::LockAxis mLockAxis;
457 bool mAxisAutoLock:1; ///< Set by ScrollView
466 * Internal Position Property Constraint.
468 * Generates position property based on pre-position
469 * Note: This is the position after clamping.
470 * (uses result of InternalPrePositionConstraint)
472 struct InternalPositionConstraint
474 InternalPositionConstraint(const RulerDomain& domainX, const RulerDomain& domainY, bool wrap)
475 : mDomainMin( -domainX.min, -domainY.min ),
476 mDomainMax( -domainX.max, -domainY.max ),
477 mClampX( domainX.enabled ),
478 mClampY( domainY.enabled ),
483 void operator()( Vector2& position, const PropertyInputContainer& inputs )
485 position = inputs[0]->GetVector2();
486 const Vector2& size = inputs[3]->GetVector3().GetVectorXY();
487 const Vector2& min = inputs[1]->GetVector2();
488 const Vector2& max = inputs[2]->GetVector2();
492 position.x = -WrapInDomain(-position.x, min.x, max.x);
493 position.y = -WrapInDomain(-position.y, min.y, max.y);
497 // clamp post position to domain
498 position.x = mClampX ? Clamp(position.x, mDomainMax.x + size.x, mDomainMin.x ) : position.x;
499 position.y = mClampY ? Clamp(position.y, mDomainMax.y + size.y, mDomainMin.y ) : position.y;
512 * This constraint updates the X overshoot property using the difference
513 * SCROLL_PRE_POSITION.x and SCROLL_POSITION.x, returning a relative value between 0.0f and 1.0f
515 struct OvershootXConstraint
517 OvershootXConstraint(float maxOvershoot) : mMaxOvershoot(maxOvershoot) {}
519 void operator()( float& current, const PropertyInputContainer& inputs )
521 if( inputs[2]->GetBoolean() )
523 const Vector2& scrollPrePosition = inputs[0]->GetVector2();
524 const Vector2& scrollPostPosition = inputs[1]->GetVector2();
525 float newOvershoot = scrollPrePosition.x - scrollPostPosition.x;
526 current = (newOvershoot > 0.0f ? std::min(newOvershoot, mMaxOvershoot) : std::max(newOvershoot, -mMaxOvershoot)) / mMaxOvershoot;
538 * This constraint updates the Y overshoot property using the difference
539 * SCROLL_PRE_POSITION.y and SCROLL_POSITION.y, returning a relative value between 0.0f and 1.0f
541 struct OvershootYConstraint
543 OvershootYConstraint(float maxOvershoot) : mMaxOvershoot(maxOvershoot) {}
545 void operator()( float& current, const PropertyInputContainer& inputs )
547 if( inputs[2]->GetBoolean() )
549 const Vector2& scrollPrePosition = inputs[0]->GetVector2();
550 const Vector2& scrollPostPosition = inputs[1]->GetVector2();
551 float newOvershoot = scrollPrePosition.y - scrollPostPosition.y;
552 current = (newOvershoot > 0.0f ? std::min(newOvershoot, mMaxOvershoot) : std::max(newOvershoot, -mMaxOvershoot)) / mMaxOvershoot;
564 * Internal Position-Delta Property Constraint.
566 * Generates position-delta property based on scroll-position + scroll-offset properties.
568 void InternalPositionDeltaConstraint( Vector2& current, const PropertyInputContainer& inputs )
570 const Vector2& scrollPosition = inputs[0]->GetVector2();
571 const Vector2& scrollOffset = inputs[1]->GetVector2();
573 current = scrollPosition + scrollOffset;
577 * Internal Final Position Constraint
578 * The position of content is:
579 * of scroll-position + f(scroll-overshoot)
580 * where f(...) function defines how overshoot
581 * should affect final-position.
583 struct InternalFinalConstraint
585 InternalFinalConstraint(AlphaFunctionPrototype functionX,
586 AlphaFunctionPrototype functionY)
587 : mFunctionX(functionX),
588 mFunctionY(functionY)
592 void operator()( Vector2& current, const PropertyInputContainer& inputs )
594 const float& overshootx = inputs[1]->GetFloat();
595 const float& overshooty = inputs[2]->GetFloat();
596 Vector2 offset( mFunctionX(overshootx),
597 mFunctionY(overshooty) );
599 current = inputs[0]->GetVector2() - offset;
602 AlphaFunctionPrototype mFunctionX;
603 AlphaFunctionPrototype mFunctionY;
609 ///////////////////////////////////////////////////////////////////////////////////////////////////
611 ///////////////////////////////////////////////////////////////////////////////////////////////////
613 Dali::Toolkit::ScrollView ScrollView::New()
615 // Create the implementation
616 ScrollViewPtr scrollView(new ScrollView());
618 // Pass ownership to CustomActor via derived handle
619 Dali::Toolkit::ScrollView handle(*scrollView);
621 // Second-phase init of the implementation
622 // This can only be done after the CustomActor connection has been made...
623 scrollView->Initialize();
628 ScrollView::ScrollView()
629 : ScrollBase( ControlBehaviour( REQUIRES_WHEEL_EVENTS | DISABLE_STYLE_CHANGE_SIGNALS ) ), // Enable size negotiation
631 mGestureStackDepth(0),
632 mScrollStateFlags(0),
633 mLockAxis(LockPossible),
634 mScrollUpdateDistance(DEFAULT_SCROLL_UPDATE_DISTANCE),
635 mMaxOvershoot(DEFAULT_MAX_OVERSHOOT, DEFAULT_MAX_OVERSHOOT),
636 mUserMaxOvershoot(DEFAULT_MAX_OVERSHOOT, DEFAULT_MAX_OVERSHOOT),
637 mSnapOvershootDuration(DEFAULT_SNAP_OVERSHOOT_DURATION),
638 mSnapOvershootAlphaFunction(AlphaFunction::EASE_OUT),
639 mSnapDuration(DEFAULT_SLOW_SNAP_ANIMATION_DURATION),
640 mSnapAlphaFunction(AlphaFunction::EASE_OUT),
641 mMinFlickDistance(DEFAULT_MIN_FLICK_DISTANCE),
642 mFlickSpeedThreshold(DEFAULT_MIN_FLICK_SPEED_THRESHOLD),
643 mFlickDuration(DEFAULT_FAST_SNAP_ANIMATION_DURATION),
644 mFlickAlphaFunction(AlphaFunction::EASE_OUT),
645 mAxisAutoLockGradient(DEFAULT_AXIS_AUTO_LOCK_GRADIENT),
646 mFrictionCoefficient(DEFAULT_FRICTION_COEFFICIENT),
647 mFlickSpeedCoefficient(DEFAULT_FLICK_SPEED_COEFFICIENT),
648 mMaxFlickSpeed(DEFAULT_MAX_FLICK_SPEED),
649 mWheelScrollDistanceStep(Vector2::ZERO),
650 mInAccessibilityPan(false),
652 mScrollInterrupted(false),
655 mTouchDownTimeoutReached(false),
656 mActorAutoSnapEnabled(false),
657 mAutoResizeContainerEnabled(false),
659 mAxisAutoLock(false),
661 mDefaultMaxOvershoot(true),
662 mCanScrollHorizontal(true),
663 mCanScrollVertical(true),
664 mTransientScrollBar(true)
668 void ScrollView::OnInitialize()
672 // Internal Actor, used to hide actors from enumerations.
673 // Also actors added to Internal actor appear as overlays e.g. ScrollBar components.
674 mInternalActor = Actor::New();
675 self.Add(mInternalActor);
677 mInternalActor.SetParentOrigin(ParentOrigin::CENTER);
678 mInternalActor.SetAnchorPoint(AnchorPoint::CENTER);
679 mInternalActor.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS );
683 mScrollPostPosition = mScrollPrePosition = Vector2::ZERO;
685 mWheelScrollDistanceStep = Stage::GetCurrent().GetSize() * DEFAULT_WHEEL_SCROLL_DISTANCE_STEP_PROPORTION;
687 mGestureStackDepth = 0;
689 self.TouchSignal().Connect( this, &ScrollView::OnTouch );
690 EnableGestureDetection( Gesture::Type( Gesture::Pan ) );
692 // By default we'll allow the user to freely drag the scroll view,
693 // while disabling the other rulers.
694 RulerPtr ruler = new DefaultRuler();
698 self.SetProperty(Toolkit::Scrollable::Property::CAN_SCROLL_VERTICAL, mCanScrollVertical);
699 self.SetProperty(Toolkit::Scrollable::Property::CAN_SCROLL_HORIZONTAL, mCanScrollHorizontal);
701 UpdatePropertyDomain();
702 SetInternalConstraints();
705 void ScrollView::OnStageConnection( int depth )
707 DALI_LOG_SCROLL_STATE("[0x%X]", this);
711 SetScrollSensitive( false );
712 SetScrollSensitive( true );
715 if(IsOvershootEnabled())
717 // try and make sure property notifications are set
718 EnableScrollOvershoot(true);
721 ScrollBase::OnStageConnection( depth );
724 void ScrollView::OnStageDisconnection()
726 DALI_LOG_SCROLL_STATE("[0x%X]", this);
730 ScrollBase::OnStageDisconnection();
733 ScrollView::~ScrollView()
735 DALI_LOG_SCROLL_STATE("[0x%X]", this);
738 AlphaFunction ScrollView::GetScrollSnapAlphaFunction() const
740 return mSnapAlphaFunction;
743 void ScrollView::SetScrollSnapAlphaFunction(AlphaFunction alpha)
745 mSnapAlphaFunction = alpha;
748 AlphaFunction ScrollView::GetScrollFlickAlphaFunction() const
750 return mFlickAlphaFunction;
753 void ScrollView::SetScrollFlickAlphaFunction(AlphaFunction alpha)
755 mFlickAlphaFunction = alpha;
758 float ScrollView::GetScrollSnapDuration() const
760 return mSnapDuration;
763 void ScrollView::SetScrollSnapDuration(float time)
765 mSnapDuration = time;
768 float ScrollView::GetScrollFlickDuration() const
770 return mFlickDuration;
773 void ScrollView::SetScrollFlickDuration(float time)
775 mFlickDuration = time;
778 void ScrollView::ApplyEffect(Toolkit::ScrollViewEffect effect)
780 Dali::Toolkit::ScrollView self = Dali::Toolkit::ScrollView::DownCast(Self());
782 // Assertion check to ensure effect doesn't already exist in this scrollview
783 bool effectAlreadyExistsInScrollView(false);
784 for (ScrollViewEffectIter iter = mEffects.begin(); iter != mEffects.end(); ++iter)
788 effectAlreadyExistsInScrollView = true;
793 DALI_ASSERT_ALWAYS(!effectAlreadyExistsInScrollView);
795 // add effect to effects list
796 mEffects.push_back(effect);
798 // invoke Attachment request to ScrollView first
799 GetImpl(effect).Attach(self);
802 void ScrollView::RemoveEffect(Toolkit::ScrollViewEffect effect)
804 Dali::Toolkit::ScrollView self = Dali::Toolkit::ScrollView::DownCast(Self());
806 // remove effect from effects list
807 bool effectExistedInScrollView(false);
808 for (ScrollViewEffectIter iter = mEffects.begin(); iter != mEffects.end(); ++iter)
812 mEffects.erase(iter);
813 effectExistedInScrollView = true;
818 // Assertion check to ensure effect existed.
819 DALI_ASSERT_ALWAYS(effectExistedInScrollView);
821 // invoke Detachment request to ScrollView last
822 GetImpl(effect).Detach(self);
825 void ScrollView::RemoveAllEffects()
827 Dali::Toolkit::ScrollView self = Dali::Toolkit::ScrollView::DownCast(Self());
829 for (ScrollViewEffectIter effectIter = mEffects.begin(); effectIter != mEffects.end(); ++effectIter)
831 Toolkit::ScrollViewEffect effect = *effectIter;
833 // invoke Detachment request to ScrollView last
834 GetImpl(effect).Detach(self);
840 void ScrollView::ApplyConstraintToChildren(Constraint constraint)
842 ApplyConstraintToBoundActors(constraint);
845 void ScrollView::RemoveConstraintsFromChildren()
847 RemoveConstraintsFromBoundActors();
850 const RulerPtr ScrollView::GetRulerX() const
855 const RulerPtr ScrollView::GetRulerY() const
860 void ScrollView::SetRulerX(RulerPtr ruler)
864 UpdatePropertyDomain();
865 UpdateMainInternalConstraint();
868 void ScrollView::SetRulerY(RulerPtr ruler)
872 UpdatePropertyDomain();
873 UpdateMainInternalConstraint();
876 void ScrollView::UpdatePropertyDomain()
879 Vector3 size = self.GetTargetSize();
880 Vector2 min = mMinScroll;
881 Vector2 max = mMaxScroll;
882 bool scrollPositionChanged = false;
883 bool domainChanged = false;
885 bool canScrollVertical = false;
886 bool canScrollHorizontal = false;
887 UpdateLocalScrollProperties();
888 if(mRulerX->IsEnabled())
890 const Toolkit::RulerDomain& rulerDomain = mRulerX->GetDomain();
891 if( fabsf(min.x - rulerDomain.min) > Math::MACHINE_EPSILON_100
892 || fabsf(max.x - rulerDomain.max) > Math::MACHINE_EPSILON_100 )
894 domainChanged = true;
895 min.x = rulerDomain.min;
896 max.x = rulerDomain.max;
898 // make sure new scroll value is within new domain
899 if( mScrollPrePosition.x < min.x
900 || mScrollPrePosition.x > max.x )
902 scrollPositionChanged = true;
903 mScrollPrePosition.x = Clamp(mScrollPrePosition.x, -(max.x - size.x), -min.x);
906 if( (fabsf(rulerDomain.max - rulerDomain.min) - size.x) > Math::MACHINE_EPSILON_100 )
908 canScrollHorizontal = true;
911 else if( fabs(min.x) > Math::MACHINE_EPSILON_100
912 || fabs(max.x) > Math::MACHINE_EPSILON_100 )
914 // need to reset to 0
915 domainChanged = true;
918 canScrollHorizontal = false;
921 if(mRulerY->IsEnabled())
923 const Toolkit::RulerDomain& rulerDomain = mRulerY->GetDomain();
924 if( fabsf(min.y - rulerDomain.min) > Math::MACHINE_EPSILON_100
925 || fabsf(max.y - rulerDomain.max) > Math::MACHINE_EPSILON_100 )
927 domainChanged = true;
928 min.y = rulerDomain.min;
929 max.y = rulerDomain.max;
931 // make sure new scroll value is within new domain
932 if( mScrollPrePosition.y < min.y
933 || mScrollPrePosition.y > max.y )
935 scrollPositionChanged = true;
936 mScrollPrePosition.y = Clamp(mScrollPrePosition.y, -(max.y - size.y), -min.y);
939 if( (fabsf(rulerDomain.max - rulerDomain.min) - size.y) > Math::MACHINE_EPSILON_100 )
941 canScrollVertical = true;
944 else if( fabs(min.y) > Math::MACHINE_EPSILON_100
945 || fabs(max.y) > Math::MACHINE_EPSILON_100 )
947 // need to reset to 0
948 domainChanged = true;
951 canScrollVertical = false;
954 // avoid setting properties if possible, otherwise this will cause an entire update as well as triggering constraints using each property we update
955 if( mCanScrollVertical != canScrollVertical )
957 mCanScrollVertical = canScrollVertical;
958 self.SetProperty(Toolkit::Scrollable::Property::CAN_SCROLL_VERTICAL, canScrollVertical);
960 if( mCanScrollHorizontal != canScrollHorizontal )
962 mCanScrollHorizontal = canScrollHorizontal;
963 self.SetProperty(Toolkit::Scrollable::Property::CAN_SCROLL_HORIZONTAL, canScrollHorizontal);
965 if( scrollPositionChanged )
967 DALI_LOG_SCROLL_STATE("[0x%X] Domain Changed, setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y );
968 self.SetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, mScrollPrePosition);
974 self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MIN, mMinScroll );
975 self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX, mMaxScroll );
979 bool ScrollView::GetScrollSensitive()
984 void ScrollView::SetScrollSensitive(bool sensitive)
987 PanGestureDetector panGesture( GetPanGestureDetector() );
989 DALI_LOG_SCROLL_STATE("[0x%X] sensitive: before:[%d] setting[%d]", this, int(mSensitive), int(sensitive));
991 if((!mSensitive) && (sensitive))
993 mSensitive = sensitive;
994 panGesture.Attach(self);
996 else if((mSensitive) && (!sensitive))
998 DALI_LOG_SCROLL_STATE("[0x%X] BEFORE: panning:[%d]", this, int(mPanning));
1000 // while the scroll view is panning, the state needs to be reset.
1003 PanGesture cancelGesture( Gesture::Cancelled );
1004 OnPan( cancelGesture );
1007 panGesture.Detach(self);
1008 mSensitive = sensitive;
1010 mGestureStackDepth = 0;
1011 DALI_LOG_SCROLL_STATE("[0x%X] AFTER: panning:[%d]", this, int(mPanning));
1015 void ScrollView::SetMaxOvershoot(float overshootX, float overshootY)
1017 mMaxOvershoot.x = overshootX;
1018 mMaxOvershoot.y = overshootY;
1019 mUserMaxOvershoot = mMaxOvershoot;
1020 mDefaultMaxOvershoot = false;
1021 UpdateMainInternalConstraint();
1024 void ScrollView::SetSnapOvershootAlphaFunction(AlphaFunction alpha)
1026 mSnapOvershootAlphaFunction = alpha;
1029 float ScrollView::GetSnapOvershootDuration()
1031 return mSnapOvershootDuration;
1034 void ScrollView::SetSnapOvershootDuration(float duration)
1036 mSnapOvershootDuration = duration;
1039 bool ScrollView::GetActorAutoSnap()
1041 return mActorAutoSnapEnabled;
1044 void ScrollView::SetActorAutoSnap(bool enable)
1046 mActorAutoSnapEnabled = enable;
1049 void ScrollView::SetAutoResize(bool enable)
1051 mAutoResizeContainerEnabled = enable;
1052 // TODO: This needs a lot of issues to be addressed before working.
1055 bool ScrollView::GetWrapMode() const
1060 void ScrollView::SetWrapMode(bool enable)
1063 Self().SetProperty(Toolkit::ScrollView::Property::WRAP, enable);
1066 int ScrollView::GetScrollUpdateDistance() const
1068 return mScrollUpdateDistance;
1071 void ScrollView::SetScrollUpdateDistance(int distance)
1073 mScrollUpdateDistance = distance;
1076 bool ScrollView::GetAxisAutoLock() const
1078 return mAxisAutoLock;
1081 void ScrollView::SetAxisAutoLock(bool enable)
1083 mAxisAutoLock = enable;
1084 UpdateMainInternalConstraint();
1087 float ScrollView::GetAxisAutoLockGradient() const
1089 return mAxisAutoLockGradient;
1092 void ScrollView::SetAxisAutoLockGradient(float gradient)
1094 DALI_ASSERT_DEBUG( gradient >= 0.0f && gradient <= 1.0f );
1095 mAxisAutoLockGradient = gradient;
1096 UpdateMainInternalConstraint();
1099 float ScrollView::GetFrictionCoefficient() const
1101 return mFrictionCoefficient;
1104 void ScrollView::SetFrictionCoefficient(float friction)
1106 DALI_ASSERT_DEBUG( friction > 0.0f );
1107 mFrictionCoefficient = friction;
1110 float ScrollView::GetFlickSpeedCoefficient() const
1112 return mFlickSpeedCoefficient;
1115 void ScrollView::SetFlickSpeedCoefficient(float speed)
1117 mFlickSpeedCoefficient = speed;
1120 Vector2 ScrollView::GetMinimumDistanceForFlick() const
1122 return mMinFlickDistance;
1125 void ScrollView::SetMinimumDistanceForFlick( const Vector2& distance )
1127 mMinFlickDistance = distance;
1130 float ScrollView::GetMinimumSpeedForFlick() const
1132 return mFlickSpeedThreshold;
1135 void ScrollView::SetMinimumSpeedForFlick( float speed )
1137 mFlickSpeedThreshold = speed;
1140 float ScrollView::GetMaxFlickSpeed() const
1142 return mMaxFlickSpeed;
1145 void ScrollView::SetMaxFlickSpeed(float speed)
1147 mMaxFlickSpeed = speed;
1150 void ScrollView::SetWheelScrollDistanceStep(Vector2 step)
1152 mWheelScrollDistanceStep = step;
1155 Vector2 ScrollView::GetWheelScrollDistanceStep() const
1157 return mWheelScrollDistanceStep;
1160 unsigned int ScrollView::GetCurrentPage() const
1162 // in case animation is currently taking place.
1163 Vector2 position = GetPropertyPosition();
1165 Actor self = Self();
1166 unsigned int page = 0;
1167 unsigned int pagesPerVolume = 1;
1168 unsigned int volume = 0;
1170 // if rulerX is enabled, then get page count (columns)
1171 page = mRulerX->GetPageFromPosition(-position.x, mWrapMode);
1172 volume = mRulerY->GetPageFromPosition(-position.y, mWrapMode);
1173 pagesPerVolume = mRulerX->GetTotalPages();
1175 return volume * pagesPerVolume + page;
1178 Vector2 ScrollView::GetCurrentScrollPosition() const
1180 return -GetPropertyPosition();
1183 void ScrollView::TransformTo(const Vector2& position,
1184 DirectionBias horizontalBias, DirectionBias verticalBias)
1186 TransformTo(position, mSnapDuration, mSnapAlphaFunction, horizontalBias, verticalBias);
1189 void ScrollView::TransformTo(const Vector2& position, float duration, AlphaFunction alpha,
1190 DirectionBias horizontalBias, DirectionBias verticalBias)
1192 // If this is called while the timer is running, then cancel it
1193 StopTouchDownTimer();
1195 Actor self( Self() );
1197 // Guard against destruction during signal emission
1198 // Note that Emit() methods are called indirectly e.g. from within ScrollView::AnimateTo()
1199 Toolkit::ScrollView handle( GetOwner() );
1201 DALI_LOG_SCROLL_STATE("[0x%X] pos[%.2f,%.2f], duration[%.2f] bias[%d, %d]",
1202 this, position.x, position.y, duration, int(horizontalBias), int(verticalBias));
1204 Vector2 currentScrollPosition = GetCurrentScrollPosition();
1205 self.SetProperty( Toolkit::ScrollView::Property::START_PAGE_POSITION, Vector3(currentScrollPosition) );
1207 if( mScrolling ) // are we interrupting a current scroll?
1209 // set mScrolling to false, in case user has code that interrogates mScrolling Getter() in complete.
1211 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignal 1 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
1212 mScrollCompletedSignal.Emit( currentScrollPosition );
1215 if( mPanning ) // are we interrupting a current pan?
1217 DALI_LOG_SCROLL_STATE("[0x%X] Interrupting Pan, set to false", this );
1219 mGestureStackDepth = 0;
1220 self.SetProperty( Toolkit::ScrollView::Property::PANNING, false );
1222 if( mScrollMainInternalPrePositionConstraint )
1224 mScrollMainInternalPrePositionConstraint.Remove();
1228 self.SetProperty(Toolkit::ScrollView::Property::SCROLLING, true);
1231 DALI_LOG_SCROLL_STATE("[0x%X] mScrollStartedSignal 1 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
1232 mScrollStartedSignal.Emit( currentScrollPosition );
1233 bool animating = AnimateTo(-position,
1234 Vector2::ONE * duration,
1243 // if not animating, then this pan has completed right now.
1244 self.SetProperty(Toolkit::ScrollView::Property::SCROLLING, false);
1247 // If we have no duration, then in the next update frame, we will be at the position specified as we just set.
1248 // In this scenario, we cannot return the currentScrollPosition as this is out-of-date and should instead return the requested final position
1249 Vector2 completedPosition( currentScrollPosition );
1250 if( duration <= Math::MACHINE_EPSILON_10 )
1252 completedPosition = position;
1255 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignal 2 [%.2f, %.2f]", this, completedPosition.x, completedPosition.y);
1256 SetScrollUpdateNotification(false);
1257 mScrollCompletedSignal.Emit( completedPosition );
1261 void ScrollView::ScrollTo(const Vector2& position)
1263 ScrollTo(position, mSnapDuration );
1266 void ScrollView::ScrollTo(const Vector2& position, float duration)
1268 ScrollTo(position, duration, DirectionBiasNone, DirectionBiasNone);
1271 void ScrollView::ScrollTo(const Vector2& position, float duration, AlphaFunction alpha)
1273 ScrollTo(position, duration, alpha, DirectionBiasNone, DirectionBiasNone);
1276 void ScrollView::ScrollTo(const Vector2& position, float duration,
1277 DirectionBias horizontalBias, DirectionBias verticalBias)
1279 ScrollTo(position, duration, mSnapAlphaFunction, horizontalBias, verticalBias);
1282 void ScrollView::ScrollTo(const Vector2& position, float duration, AlphaFunction alpha,
1283 DirectionBias horizontalBias, DirectionBias verticalBias)
1285 DALI_LOG_SCROLL_STATE("[0x%X] position[%.2f, %.2f] duration[%.2f], bias[%d, %d]", this, position.x, position.y, duration, int(horizontalBias), int(verticalBias));
1286 TransformTo(position, duration, alpha, horizontalBias, verticalBias);
1289 void ScrollView::ScrollTo(unsigned int page)
1291 ScrollTo(page, mSnapDuration);
1294 void ScrollView::ScrollTo(unsigned int page, float duration, DirectionBias bias)
1297 unsigned int volume;
1298 unsigned int libraries;
1300 // The position to scroll to is continuous and linear
1301 // unless a domain has been enabled on the X axis.
1302 // or if WrapMode has been enabled.
1303 bool carryX = mRulerX->GetDomain().enabled | mWrapMode;
1304 bool carryY = mRulerY->GetDomain().enabled | mWrapMode;
1306 position.x = mRulerX->GetPositionFromPage(page, volume, carryX);
1307 position.y = mRulerY->GetPositionFromPage(volume, libraries, carryY);
1309 ScrollTo(position, duration, bias, bias);
1312 void ScrollView::ScrollTo(Actor &actor)
1314 ScrollTo(actor, mSnapDuration);
1317 void ScrollView::ScrollTo(Actor &actor, float duration)
1319 DALI_ASSERT_ALWAYS(actor.GetParent() == Self());
1321 Actor self = Self();
1322 Vector3 size = self.GetCurrentSize();
1323 Vector3 position = actor.GetCurrentPosition();
1324 Vector2 prePosition = GetPropertyPrePosition();
1325 position.GetVectorXY() -= prePosition;
1327 ScrollTo(Vector2(position.x - size.width * 0.5f, position.y - size.height * 0.5f), duration);
1330 Actor ScrollView::FindClosestActor()
1332 Actor self = Self();
1333 Vector3 size = self.GetCurrentSize();
1335 return FindClosestActorToPosition(Vector3(size.width * 0.5f,size.height * 0.5f,0.0f));
1338 Actor ScrollView::FindClosestActorToPosition(const Vector3& position, FindDirection dirX, FindDirection dirY, FindDirection dirZ)
1341 float closestDistance2 = 0.0f;
1342 Vector3 actualPosition = position;
1344 unsigned int numChildren = Self().GetChildCount();
1346 for(unsigned int i = 0; i < numChildren; ++i)
1348 Actor child = Self().GetChildAt(i);
1350 if(mInternalActor == child) // ignore internal actor.
1355 Vector3 childPosition = GetPositionOfAnchor(child, AnchorPoint::CENTER);
1357 Vector3 delta = childPosition - actualPosition;
1359 // X-axis checking (only find Actors to the [dirX] of actualPosition)
1360 if(dirX > All) // != All,None
1362 FindDirection deltaH = delta.x > 0 ? Right : Left;
1369 // Y-axis checking (only find Actors to the [dirY] of actualPosition)
1370 if(dirY > All) // != All,None
1372 FindDirection deltaV = delta.y > 0 ? Down : Up;
1379 // Z-axis checking (only find Actors to the [dirZ] of actualPosition)
1380 if(dirZ > All) // != All,None
1382 FindDirection deltaV = delta.y > 0 ? In : Out;
1389 // compare child to closest child in terms of distance.
1390 float distance2 = 0.0f;
1392 // distance2 = the Square of the relevant dimensions of delta
1395 distance2 += delta.x * delta.x;
1400 distance2 += delta.y * delta.y;
1405 distance2 += delta.z * delta.z;
1408 if(closestChild) // Next time.
1410 if(distance2 < closestDistance2)
1412 closestChild = child;
1413 closestDistance2 = distance2;
1418 closestChild = child;
1419 closestDistance2 = distance2;
1423 return closestChild;
1426 bool ScrollView::ScrollToSnapPoint()
1428 DALI_LOG_SCROLL_STATE("[0x%X]", this );
1429 Vector2 stationaryVelocity = Vector2(0.0f, 0.0f);
1430 return SnapWithVelocity( stationaryVelocity );
1433 // TODO: In situations where axes are different (X snap, Y free)
1434 // Each axis should really have their own independent animation (time and equation)
1435 // Consider, X axis snapping to nearest grid point (EaseOut over fixed time)
1436 // Consider, Y axis simulating physics to arrive at a point (Physics equation over variable time)
1437 // Currently, the axes have been split however, they both use the same EaseOut equation.
1438 bool ScrollView::SnapWithVelocity(Vector2 velocity)
1440 // Animator takes over now, touches are assumed not to interfere.
1441 // And if touches do interfere, then we'll stop animation, update PrePosition
1442 // to current mScroll's properties, and then resume.
1443 // Note: For Flicking this may work a bit different...
1445 float angle = atan2(velocity.y, velocity.x);
1446 float speed2 = velocity.LengthSquared();
1447 AlphaFunction alphaFunction = mSnapAlphaFunction;
1448 Vector2 positionDuration = Vector2::ONE * mSnapDuration;
1451 FindDirection horizontal = None;
1452 FindDirection vertical = None;
1454 // orthoAngleRange = Angle tolerance within the Exact N,E,S,W direction
1455 // that will be accepted as a general N,E,S,W flick direction.
1457 const float orthoAngleRange = FLICK_ORTHO_ANGLE_RANGE * M_PI / 180.0f;
1458 const float flickSpeedThreshold2 = mFlickSpeedThreshold * mFlickSpeedThreshold;
1460 Vector2 positionSnap = mScrollPrePosition;
1462 // Flick logic X Axis
1464 if(mRulerX->IsEnabled() && mLockAxis != LockHorizontal)
1468 if( speed2 > flickSpeedThreshold2 || // exceeds flick threshold
1469 mInAccessibilityPan ) // With AccessibilityPan its easier to move between snap positions
1471 if((angle >= -orthoAngleRange) && (angle < orthoAngleRange)) // Swiping East
1473 biasX = 0.0f, horizontal = Left;
1475 // This guards against an error where no movement occurs, due to the flick finishing
1476 // before the update-thread has advanced mScrollPostPosition past the the previous snap point.
1477 positionSnap.x += 1.0f;
1479 else if((angle >= M_PI-orthoAngleRange) || (angle < -M_PI+orthoAngleRange)) // Swiping West
1481 biasX = 1.0f, horizontal = Right;
1483 // This guards against an error where no movement occurs, due to the flick finishing
1484 // before the update-thread has advanced mScrollPostPosition past the the previous snap point.
1485 positionSnap.x -= 1.0f;
1490 // Flick logic Y Axis
1492 if(mRulerY->IsEnabled() && mLockAxis != LockVertical)
1496 if( speed2 > flickSpeedThreshold2 || // exceeds flick threshold
1497 mInAccessibilityPan ) // With AccessibilityPan its easier to move between snap positions
1499 if((angle >= M_PI_2-orthoAngleRange) && (angle < M_PI_2+orthoAngleRange)) // Swiping South
1501 biasY = 0.0f, vertical = Up;
1503 else if((angle >= -M_PI_2-orthoAngleRange) && (angle < -M_PI_2+orthoAngleRange)) // Swiping North
1505 biasY = 1.0f, vertical = Down;
1510 // isFlick: Whether this gesture is a flick or not.
1511 bool isFlick = (horizontal != All || vertical != All);
1512 // isFreeFlick: Whether this gesture is a flick under free panning criteria.
1513 bool isFreeFlick = velocity.LengthSquared() > (FREE_FLICK_SPEED_THRESHOLD*FREE_FLICK_SPEED_THRESHOLD);
1515 if(isFlick || isFreeFlick)
1517 positionDuration = Vector2::ONE * mFlickDuration;
1518 alphaFunction = mFlickAlphaFunction;
1521 // Calculate next positionSnap ////////////////////////////////////////////////////////////
1523 if(mActorAutoSnapEnabled)
1525 Vector3 size = Self().GetCurrentSize();
1527 Actor child = FindClosestActorToPosition( Vector3(size.width * 0.5f,size.height * 0.5f,0.0f), horizontal, vertical );
1529 if(!child && isFlick )
1531 // If we conducted a direction limited search and found no actor, then just snap to the closest actor.
1532 child = FindClosestActorToPosition( Vector3(size.width * 0.5f,size.height * 0.5f,0.0f) );
1537 Vector2 position = DevelHandle::GetCurrentProperty<Vector2>( Self(), Toolkit::ScrollView::Property::SCROLL_POSITION );
1539 // Get center-point of the Actor.
1540 Vector3 childPosition = GetPositionOfAnchor(child, AnchorPoint::CENTER);
1542 if(mRulerX->IsEnabled())
1544 positionSnap.x = position.x - childPosition.x + size.width * 0.5f;
1546 if(mRulerY->IsEnabled())
1548 positionSnap.y = position.y - childPosition.y + size.height * 0.5f;
1553 Vector2 startPosition = positionSnap;
1554 positionSnap.x = -mRulerX->Snap(-positionSnap.x, biasX); // NOTE: X & Y rulers think in -ve coordinate system.
1555 positionSnap.y = -mRulerY->Snap(-positionSnap.y, biasY); // That is scrolling RIGHT (e.g. 100.0, 0.0) means moving LEFT.
1557 Vector2 clampDelta(Vector2::ZERO);
1558 ClampPosition(positionSnap);
1560 if( (mRulerX->GetType() == Ruler::Free || mRulerY->GetType() == Ruler::Free)
1561 && isFreeFlick && !mActorAutoSnapEnabled)
1563 // Calculate target position based on velocity of flick.
1565 // a = Deceleration (Set to diagonal stage length * friction coefficient)
1566 // u = Initial Velocity (Flick velocity)
1567 // v = 0 (Final Velocity)
1568 // t = Time (Velocity / Deceleration)
1569 Vector2 stageSize = Stage::GetCurrent().GetSize();
1570 float stageLength = Vector3(stageSize.x, stageSize.y, 0.0f).Length();
1571 float a = (stageLength * mFrictionCoefficient);
1572 Vector3 u = Vector3(velocity.x, velocity.y, 0.0f) * mFlickSpeedCoefficient;
1573 float speed = u.Length();
1576 // TODO: Change this to a decay function. (faster you flick, the slower it should be)
1577 speed = std::min(speed, stageLength * mMaxFlickSpeed );
1579 alphaFunction = ConstantDecelerationAlphaFunction;
1581 float t = speed / a;
1583 if(mRulerX->IsEnabled() && mRulerX->GetType() == Ruler::Free)
1585 positionSnap.x += t*u.x*0.5f;
1588 if(mRulerY->IsEnabled() && mRulerY->GetType() == Ruler::Free)
1590 positionSnap.y += t*u.y*0.5f;
1593 clampDelta = positionSnap;
1594 ClampPosition(positionSnap);
1595 if((positionSnap - startPosition).LengthSquared() > Math::MACHINE_EPSILON_0)
1597 clampDelta -= positionSnap;
1598 clampDelta.x = clampDelta.x > 0.0f ? std::min(clampDelta.x, mMaxOvershoot.x) : std::max(clampDelta.x, -mMaxOvershoot.x);
1599 clampDelta.y = clampDelta.y > 0.0f ? std::min(clampDelta.y, mMaxOvershoot.y) : std::max(clampDelta.y, -mMaxOvershoot.y);
1603 clampDelta = Vector2::ZERO;
1606 // If Axis is Free and has velocity, then calculate time taken
1607 // to reach target based on velocity in axis.
1608 if(mRulerX->IsEnabled() && mRulerX->GetType() == Ruler::Free)
1610 float deltaX = fabsf(startPosition.x - positionSnap.x);
1612 if(fabsf(u.x) > Math::MACHINE_EPSILON_1)
1614 positionDuration.x = fabsf(deltaX / u.x);
1618 positionDuration.x = 0;
1622 if(mRulerY->IsEnabled() && mRulerY->GetType() == Ruler::Free)
1624 float deltaY = fabsf(startPosition.y - positionSnap.y);
1626 if(fabsf(u.y) > Math::MACHINE_EPSILON_1)
1628 positionDuration.y = fabsf(deltaY / u.y);
1632 positionDuration.y = 0;
1637 if(IsOvershootEnabled())
1639 // Scroll to the end of the overshoot only when overshoot is enabled.
1640 positionSnap += clampDelta;
1643 bool animating = AnimateTo(positionSnap, positionDuration,
1644 alphaFunction, false,
1645 DirectionBiasNone, DirectionBiasNone,
1646 isFlick || isFreeFlick ? Flick : Snap);
1651 void ScrollView::StopAnimation(void)
1653 // Clear Snap animation if exists.
1654 StopAnimation(mInternalXAnimation);
1655 StopAnimation(mInternalYAnimation);
1656 mScrollStateFlags = 0;
1657 // remove scroll animation flags
1658 HandleStoppedAnimation();
1661 void ScrollView::StopAnimation(Animation& animation)
1670 bool ScrollView::AnimateTo(const Vector2& position, const Vector2& positionDuration,
1671 AlphaFunction alpha, bool findShortcuts,
1672 DirectionBias horizontalBias, DirectionBias verticalBias,
1675 // Here we perform an animation on a number of properties (depending on which have changed)
1676 // The animation is applied to all ScrollBases
1677 Actor self = Self();
1678 mScrollTargetPosition = position;
1679 float totalDuration = 0.0f;
1681 bool positionChanged = (mScrollTargetPosition != mScrollPostPosition);
1685 totalDuration = std::max(totalDuration, positionDuration.x);
1686 totalDuration = std::max(totalDuration, positionDuration.y);
1690 // try to animate for a frame, on some occasions update will be changing scroll value while event side thinks it hasnt changed
1691 totalDuration = 0.01f;
1692 positionChanged = true;
1697 // Position Delta ///////////////////////////////////////////////////////
1700 UpdateMainInternalConstraint();
1701 if(mWrapMode && findShortcuts)
1703 // In Wrap Mode, the shortest distance is a little less intuitive...
1704 const RulerDomain rulerDomainX = mRulerX->GetDomain();
1705 const RulerDomain rulerDomainY = mRulerY->GetDomain();
1707 if(mRulerX->IsEnabled())
1709 float dir = VectorInDomain(-mScrollPrePosition.x, -mScrollTargetPosition.x, rulerDomainX.min, rulerDomainX.max, horizontalBias);
1710 mScrollTargetPosition.x = mScrollPrePosition.x + -dir;
1713 if(mRulerY->IsEnabled())
1715 float dir = VectorInDomain(-mScrollPrePosition.y, -mScrollTargetPosition.y, rulerDomainY.min, rulerDomainY.max, verticalBias);
1716 mScrollTargetPosition.y = mScrollPrePosition.y + -dir;
1720 // note we have two separate animations for X & Y, this deals with sliding diagonally and hitting
1721 // a horizonal/vertical wall.delay
1722 AnimateInternalXTo(mScrollTargetPosition.x, positionDuration.x, alpha);
1723 AnimateInternalYTo(mScrollTargetPosition.y, positionDuration.y, alpha);
1725 if( !(mScrollStateFlags & SCROLL_ANIMATION_FLAGS) )
1727 DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollTargetPosition.x, mScrollTargetPosition.y );
1728 self.SetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, mScrollTargetPosition);
1729 mScrollPrePosition = mScrollTargetPosition;
1730 mScrollPostPosition = mScrollTargetPosition;
1731 WrapPosition(mScrollPostPosition);
1734 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 );
1735 DALI_LOG_SCROLL_STATE("[0x%X] SCROLL_PRE_POSITION[%.2f, %.2f], SCROLL_POSITION[%.2f, %.2f]", this, DevelHandle::GetCurrentProperty( self, Toolkit::ScrollView::Property::SCROLL_PRE_POSITION ).Get<Vector2>().x, DevelHandle::GetCurrentProperty( self, Toolkit::ScrollView::Property::SCROLL_PRE_POSITION ).Get<Vector2>().y, DevelHandle::GetCurrentProperty( self, Toolkit::ScrollView::Property::SCROLL_POSITION ).Get<Vector2>().x, DevelHandle::GetCurrentProperty( self, Toolkit::ScrollView::Property::SCROLL_POSITION ).Get<Vector2>().y );
1738 SetScrollUpdateNotification(true);
1740 // Always send a snap event when AnimateTo is called.
1741 Toolkit::ScrollView::SnapEvent snapEvent;
1742 snapEvent.type = snapType;
1743 snapEvent.position = -mScrollTargetPosition;
1744 snapEvent.duration = totalDuration;
1746 DALI_LOG_SCROLL_STATE("[0x%X] mSnapStartedSignal [%.2f, %.2f]", this, snapEvent.position.x, snapEvent.position.y);
1747 mSnapStartedSignal.Emit( snapEvent );
1749 return (mScrollStateFlags & SCROLL_ANIMATION_FLAGS) != 0;
1752 void ScrollView::EnableScrollOvershoot(bool enable)
1756 if (!mOvershootIndicator)
1758 mOvershootIndicator = ScrollOvershootIndicator::New();
1761 mOvershootIndicator->AttachToScrollable(*this);
1765 mMaxOvershoot = mUserMaxOvershoot;
1767 if (mOvershootIndicator)
1769 mOvershootIndicator->DetachFromScrollable(*this);
1773 UpdateMainInternalConstraint();
1776 void ScrollView::AddOverlay(Actor actor)
1778 actor.SetDrawMode( DrawMode::OVERLAY_2D );
1779 mInternalActor.Add( actor );
1782 void ScrollView::RemoveOverlay(Actor actor)
1784 mInternalActor.Remove( actor );
1787 void ScrollView::SetOvershootSize( const Vector2& size )
1789 mOvershootSize = size;
1790 if( IsOvershootEnabled() && mOvershootIndicator )
1792 mOvershootIndicator->AttachToScrollable(*this);
1796 void ScrollView::SetOvershootEffectColor( const Vector4& color )
1798 mOvershootEffectColor = color;
1799 if( mOvershootIndicator )
1801 mOvershootIndicator->SetOvershootEffectColor( color );
1805 void ScrollView::SetScrollingDirection( Radian direction, Radian threshold )
1807 PanGestureDetector panGesture( GetPanGestureDetector() );
1809 // First remove just in case we have some set, then add.
1810 panGesture.RemoveDirection( direction );
1811 panGesture.AddDirection( direction, threshold );
1814 void ScrollView::RemoveScrollingDirection( Radian direction )
1816 PanGestureDetector panGesture( GetPanGestureDetector() );
1817 panGesture.RemoveDirection( direction );
1820 Toolkit::ScrollView::SnapStartedSignalType& ScrollView::SnapStartedSignal()
1822 return mSnapStartedSignal;
1825 void ScrollView::FindAndUnbindActor(Actor child)
1830 Vector2 ScrollView::GetPropertyPrePosition() const
1832 Vector2 position = DevelHandle::GetCurrentProperty< Vector2 >( Self(), Toolkit::ScrollView::Property::SCROLL_PRE_POSITION );
1833 WrapPosition(position);
1837 Vector2 ScrollView::GetPropertyPosition() const
1839 Vector2 position = DevelHandle::GetCurrentProperty< Vector2 >( Self(), Toolkit::ScrollView::Property::SCROLL_POSITION );
1840 WrapPosition(position);
1845 void ScrollView::HandleStoppedAnimation()
1847 SetScrollUpdateNotification(false);
1850 void ScrollView::HandleSnapAnimationFinished()
1852 // Emit Signal that scrolling has completed.
1854 Actor self = Self();
1855 self.SetProperty(Toolkit::ScrollView::Property::SCROLLING, false);
1857 Vector2 deltaPosition(mScrollPrePosition);
1859 UpdateLocalScrollProperties();
1860 WrapPosition(mScrollPrePosition);
1861 DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y );
1862 self.SetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, mScrollPrePosition);
1864 Vector2 currentScrollPosition = GetCurrentScrollPosition();
1865 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignal 3 current[%.2f, %.2f], mScrollTargetPosition[%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y, -mScrollTargetPosition.x, -mScrollTargetPosition.y );
1866 mScrollCompletedSignal.Emit( currentScrollPosition );
1868 mDomainOffset += deltaPosition - mScrollPostPosition;
1869 self.SetProperty(Toolkit::ScrollView::Property::SCROLL_DOMAIN_OFFSET, mDomainOffset);
1870 HandleStoppedAnimation();
1873 void ScrollView::SetScrollUpdateNotification( bool enabled )
1875 Actor self = Self();
1876 if( mScrollXUpdateNotification )
1878 // disconnect now to avoid a notification before removed from update thread
1879 mScrollXUpdateNotification.NotifySignal().Disconnect(this, &ScrollView::OnScrollUpdateNotification);
1880 self.RemovePropertyNotification(mScrollXUpdateNotification);
1881 mScrollXUpdateNotification.Reset();
1883 if( enabled && !mScrollUpdatedSignal.Empty())
1885 // Only set up the notification when the application has connected to the updated signal
1886 mScrollXUpdateNotification = self.AddPropertyNotification(Toolkit::ScrollView::Property::SCROLL_POSITION, 0, StepCondition(mScrollUpdateDistance, 0.0f));
1887 mScrollXUpdateNotification.NotifySignal().Connect( this, &ScrollView::OnScrollUpdateNotification );
1889 if( mScrollYUpdateNotification )
1891 // disconnect now to avoid a notification before removed from update thread
1892 mScrollYUpdateNotification.NotifySignal().Disconnect(this, &ScrollView::OnScrollUpdateNotification);
1893 self.RemovePropertyNotification(mScrollYUpdateNotification);
1894 mScrollYUpdateNotification.Reset();
1896 if( enabled && !mScrollUpdatedSignal.Empty())
1898 // Only set up the notification when the application has connected to the updated signal
1899 mScrollYUpdateNotification = self.AddPropertyNotification(Toolkit::ScrollView::Property::SCROLL_POSITION, 1, StepCondition(mScrollUpdateDistance, 0.0f));
1900 mScrollYUpdateNotification.NotifySignal().Connect( this, &ScrollView::OnScrollUpdateNotification );
1904 void ScrollView::OnScrollUpdateNotification(Dali::PropertyNotification& source)
1906 // Guard against destruction during signal emission
1907 Toolkit::ScrollView handle( GetOwner() );
1909 Vector2 currentScrollPosition = GetCurrentScrollPosition();
1910 mScrollUpdatedSignal.Emit( currentScrollPosition );
1913 bool ScrollView::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
1915 Dali::BaseHandle handle( object );
1917 bool connected( true );
1918 Toolkit::ScrollView view = Toolkit::ScrollView::DownCast( handle );
1920 if( 0 == strcmp( signalName.c_str(), SIGNAL_SNAP_STARTED ) )
1922 view.SnapStartedSignal().Connect( tracker, functor );
1926 // signalName does not match any signal
1933 void ScrollView::OnSizeAnimation(Animation& animation, const Vector3& targetSize)
1935 // need to update domain properties for new size
1936 UpdatePropertyDomain();
1939 void ScrollView::OnSizeSet( const Vector3& size )
1941 // need to update domain properties for new size
1942 if( mDefaultMaxOvershoot )
1944 mUserMaxOvershoot.x = size.x * 0.5f;
1945 mUserMaxOvershoot.y = size.y * 0.5f;
1946 if( !IsOvershootEnabled() )
1948 mMaxOvershoot = mUserMaxOvershoot;
1951 UpdatePropertyDomain();
1952 UpdateMainInternalConstraint();
1953 if( IsOvershootEnabled() )
1955 mOvershootIndicator->Reset();
1958 ScrollBase::OnSizeSet( size );
1961 void ScrollView::OnChildAdd(Actor& child)
1963 ScrollBase::OnChildAdd( child );
1965 Dali::Toolkit::ScrollBar scrollBar = Dali::Toolkit::ScrollBar::DownCast(child);
1968 mScrollBar = scrollBar;
1969 scrollBar.SetName("ScrollBar");
1971 mInternalActor.Add( scrollBar );
1972 if( scrollBar.GetScrollDirection() == Toolkit::ScrollBar::Horizontal )
1974 scrollBar.SetScrollPropertySource( Self(),
1975 Toolkit::ScrollView::Property::SCROLL_PRE_POSITION_X,
1976 Toolkit::Scrollable::Property::SCROLL_POSITION_MIN_X,
1977 Toolkit::ScrollView::Property::SCROLL_PRE_POSITION_MAX_X,
1978 Toolkit::ScrollView::Property::SCROLL_DOMAIN_SIZE_X );
1982 scrollBar.SetScrollPropertySource( Self(),
1983 Toolkit::ScrollView::Property::SCROLL_PRE_POSITION_Y,
1984 Toolkit::Scrollable::Property::SCROLL_POSITION_MIN_Y,
1985 Toolkit::ScrollView::Property::SCROLL_PRE_POSITION_MAX_Y,
1986 Toolkit::ScrollView::Property::SCROLL_DOMAIN_SIZE_Y );
1989 if( mTransientScrollBar )
1991 // Show the scroll-indicator for a brief period
1992 Property::Map emptyMap;
1993 scrollBar.DoAction( "ShowTransientIndicator", emptyMap );
1996 else if(mAlterChild)
2002 void ScrollView::OnChildRemove(Actor& child)
2004 // TODO: Actor needs a RemoveConstraint method to take out an individual constraint.
2007 ScrollBase::OnChildRemove( child );
2010 void ScrollView::StartTouchDownTimer()
2012 if ( !mTouchDownTimer )
2014 mTouchDownTimer = Timer::New( TOUCH_DOWN_TIMER_INTERVAL );
2015 mTouchDownTimer.TickSignal().Connect( this, &ScrollView::OnTouchDownTimeout );
2018 mTouchDownTimer.Start();
2021 void ScrollView::StopTouchDownTimer()
2023 if ( mTouchDownTimer )
2025 mTouchDownTimer.Stop();
2029 bool ScrollView::OnTouchDownTimeout()
2031 DALI_LOG_SCROLL_STATE("[0x%X]", this);
2033 mTouchDownTimeoutReached = true;
2035 unsigned int currentScrollStateFlags( mScrollStateFlags ); // Cleared in StopAnimation so keep local copy for comparison
2036 if( currentScrollStateFlags & (SCROLL_ANIMATION_FLAGS | SNAP_ANIMATION_FLAGS) )
2038 DALI_LOG_SCROLL_STATE("[0x%X] Scrolling Or snapping flags set, stopping animation", this);
2041 if( currentScrollStateFlags & SCROLL_ANIMATION_FLAGS )
2043 DALI_LOG_SCROLL_STATE("[0x%X] Scrolling flags set, emitting signal", this);
2045 mScrollInterrupted = true;
2046 // reset domain offset as scrolling from original plane.
2047 mDomainOffset = Vector2::ZERO;
2048 Self().SetProperty(Toolkit::ScrollView::Property::SCROLL_DOMAIN_OFFSET, Vector2::ZERO);
2050 UpdateLocalScrollProperties();
2051 Vector2 currentScrollPosition = GetCurrentScrollPosition();
2052 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignal 4 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
2053 mScrollCompletedSignal.Emit( currentScrollPosition );
2060 bool ScrollView::OnTouch( Actor actor, const TouchData& touch )
2064 DALI_LOG_SCROLL_STATE("[0x%X], Not Sensitive, ignoring", this);
2066 // Ignore this touch event, if scrollview is insensitive.
2070 // Ignore events with multiple-touch points
2071 if (touch.GetPointCount() != 1)
2073 DALI_LOG_SCROLL_STATE("[0x%X], multiple touch, ignoring", this);
2078 const PointState::Type pointState = touch.GetState( 0 );
2079 if( pointState == PointState::DOWN )
2081 DALI_LOG_SCROLL_STATE("[0x%X] Down", this);
2083 if(mGestureStackDepth==0)
2085 mTouchDownTime = touch.GetTime();
2087 // This allows time for a pan-gesture to start, to avoid breaking snap-animation behavior with fast flicks.
2088 // If touch-down does not become a pan (after timeout interval), then snap-animation can be interrupted.
2089 mTouchDownTimeoutReached = false;
2090 mScrollInterrupted = false;
2091 StartTouchDownTimer();
2094 else if( ( pointState == PointState::UP ) ||
2095 ( ( pointState == PointState::INTERRUPTED ) && ( touch.GetHitActor( 0 )== Self() ) ) )
2097 DALI_LOG_SCROLL_STATE("[0x%X] %s", this, ( ( pointState == TouchPoint::Up ) ? "Up" : "Interrupted" ) );
2099 StopTouchDownTimer();
2101 // if the user touches and releases without enough movement to go
2102 // into a gesture state, then we should snap to nearest point.
2103 // otherwise our scroll could be stopped (interrupted) half way through an animation.
2104 if(mGestureStackDepth==0 && mTouchDownTimeoutReached)
2106 if( ( pointState == PointState::INTERRUPTED ) ||
2107 ( ( touch.GetTime() - mTouchDownTime ) >= MINIMUM_TIME_BETWEEN_DOWN_AND_UP_FOR_RESET ) )
2109 // Reset the velocity only if down was received a while ago
2110 mLastVelocity = Vector2( 0.0f, 0.0f );
2113 UpdateLocalScrollProperties();
2114 // Only finish the transform if scrolling was interrupted on down or if we are scrolling
2115 if ( mScrollInterrupted || mScrolling )
2117 DALI_LOG_SCROLL_STATE("[0x%X] Calling FinishTransform", this);
2122 mTouchDownTimeoutReached = false;
2123 mScrollInterrupted = false;
2129 bool ScrollView::OnWheelEvent(const WheelEvent& event)
2133 // Ignore this wheel event, if scrollview is insensitive.
2137 Vector2 targetScrollPosition = GetPropertyPosition();
2139 if(mRulerX->IsEnabled() && !mRulerY->IsEnabled())
2141 // If only the ruler in the X axis is enabled, scroll in the X axis.
2142 if(mRulerX->GetType() == Ruler::Free)
2144 // Free panning mode
2145 targetScrollPosition.x += event.z * mWheelScrollDistanceStep.x;
2146 ClampPosition(targetScrollPosition);
2147 ScrollTo(-targetScrollPosition);
2149 else if(!mScrolling)
2151 // Snap mode, only respond to the event when the previous snap animation is finished.
2152 ScrollTo(GetCurrentPage() - event.z);
2157 // If the ruler in the Y axis is enabled, scroll in the Y axis.
2158 if(mRulerY->GetType() == Ruler::Free)
2160 // Free panning mode
2161 targetScrollPosition.y += event.z * mWheelScrollDistanceStep.y;
2162 ClampPosition(targetScrollPosition);
2163 ScrollTo(-targetScrollPosition);
2165 else if(!mScrolling)
2167 // Snap mode, only respond to the event when the previous snap animation is finished.
2168 ScrollTo(GetCurrentPage() - event.z * mRulerX->GetTotalPages());
2175 void ScrollView::ResetScrolling()
2177 Actor self = Self();
2178 DevelHandle::GetCurrentProperty( self, Toolkit::ScrollView::Property::SCROLL_POSITION ).Get( mScrollPostPosition );
2179 mScrollPrePosition = mScrollPostPosition;
2180 DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPostPosition.x, mScrollPostPosition.y );
2181 self.SetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, mScrollPostPosition);
2184 void ScrollView::UpdateLocalScrollProperties()
2186 Actor self = Self();
2187 DevelHandle::GetCurrentProperty( self, Toolkit::ScrollView::Property::SCROLL_PRE_POSITION ).Get( mScrollPrePosition );
2188 DevelHandle::GetCurrentProperty( self, Toolkit::ScrollView::Property::SCROLL_POSITION ).Get( mScrollPostPosition );
2191 // private functions
2193 void ScrollView::PreAnimatedScrollSetup()
2195 // SCROLL_PRE_POSITION is our unclamped property with wrapping
2196 // SCROLL_POSITION is our final scroll position after clamping
2198 Actor self = Self();
2200 Vector2 deltaPosition(mScrollPostPosition);
2201 WrapPosition(mScrollPostPosition);
2202 mDomainOffset += deltaPosition - mScrollPostPosition;
2203 Self().SetProperty(Toolkit::ScrollView::Property::SCROLL_DOMAIN_OFFSET, mDomainOffset);
2205 if( mScrollStateFlags & SCROLL_X_STATE_MASK )
2207 // already performing animation on internal x position
2208 StopAnimation(mInternalXAnimation);
2211 if( mScrollStateFlags & SCROLL_Y_STATE_MASK )
2213 // already performing animation on internal y position
2214 StopAnimation(mInternalYAnimation);
2217 mScrollStateFlags = 0;
2219 // Update Actor position with this wrapped value.
2222 void ScrollView::FinaliseAnimatedScroll()
2224 // TODO - common animation finishing code in here
2227 void ScrollView::AnimateInternalXTo( float position, float duration, AlphaFunction alpha )
2229 StopAnimation(mInternalXAnimation);
2231 if( duration > Math::MACHINE_EPSILON_10 )
2233 Actor self = Self();
2234 DALI_LOG_SCROLL_STATE("[0x%X], Animating from[%.2f] to[%.2f]", this, DevelHandle::GetCurrentProperty( self, Toolkit::ScrollView::Property::SCROLL_PRE_POSITION ).Get< Vector2 >().x, position );
2235 mInternalXAnimation = Animation::New(duration);
2236 DALI_LOG_SCROLL_STATE("[0x%X], mInternalXAnimation[0x%X]", this, mInternalXAnimation.GetObjectPtr() );
2237 mInternalXAnimation.FinishedSignal().Connect(this, &ScrollView::OnScrollAnimationFinished);
2238 mInternalXAnimation.AnimateTo( Property(self, Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, 0), position, alpha, TimePeriod(duration));
2239 mInternalXAnimation.Play();
2241 // erase current state flags
2242 mScrollStateFlags &= ~SCROLL_X_STATE_MASK;
2243 // add internal animation state flag
2244 mScrollStateFlags |= AnimatingInternalX;
2248 void ScrollView::AnimateInternalYTo( float position, float duration, AlphaFunction alpha )
2250 StopAnimation(mInternalYAnimation);
2252 if( duration > Math::MACHINE_EPSILON_10 )
2254 Actor self = Self();
2255 DALI_LOG_SCROLL_STATE("[0x%X], Animating from[%.2f] to[%.2f]", this, DevelHandle::GetCurrentProperty( self, Toolkit::ScrollView::Property::SCROLL_PRE_POSITION ).Get< Vector2 >().y, position );
2256 mInternalYAnimation = Animation::New(duration);
2257 DALI_LOG_SCROLL_STATE("[0x%X], mInternalYAnimation[0x%X]", this, mInternalYAnimation.GetObjectPtr() );
2258 mInternalYAnimation.FinishedSignal().Connect(this, &ScrollView::OnScrollAnimationFinished);
2259 mInternalYAnimation.AnimateTo( Property(self, Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, 1), position, alpha, TimePeriod(duration));
2260 mInternalYAnimation.Play();
2262 // erase current state flags
2263 mScrollStateFlags &= ~SCROLL_Y_STATE_MASK;
2264 // add internal animation state flag
2265 mScrollStateFlags |= AnimatingInternalY;
2269 void ScrollView::OnScrollAnimationFinished( Animation& source )
2271 // Guard against destruction during signal emission
2272 // Note that ScrollCompletedSignal is emitted from HandleSnapAnimationFinished()
2273 Toolkit::ScrollView handle( GetOwner() );
2275 bool scrollingFinished = false;
2277 // update our local scroll positions
2278 UpdateLocalScrollProperties();
2280 if( source == mInternalXAnimation )
2282 DALI_LOG_SCROLL_STATE("[0x%X] mInternalXAnimation[0x%X], expected[%.2f], actual[%.2f], post[%.2f]", this, mInternalXAnimation.GetObjectPtr(), mScrollTargetPosition.x, DevelHandle::GetCurrentProperty( Self(), SCROLL_PRE_POSITION ).Get< Vector2 >().x, mScrollPostPosition.x );
2284 if( !(mScrollStateFlags & AnimatingInternalY) )
2286 scrollingFinished = true;
2288 mInternalXAnimation.Reset();
2289 // wrap pre scroll x position and set it
2292 const RulerDomain rulerDomain = mRulerX->GetDomain();
2293 mScrollPrePosition.x = -WrapInDomain(-mScrollPrePosition.x, rulerDomain.min, rulerDomain.max);
2294 DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y );
2295 handle.SetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, mScrollPrePosition);
2297 SnapInternalXTo(mScrollPostPosition.x);
2300 if( source == mInternalYAnimation )
2302 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 );
2304 if( !(mScrollStateFlags & AnimatingInternalX) )
2306 scrollingFinished = true;
2308 mInternalYAnimation.Reset();
2311 // wrap pre scroll y position and set it
2312 const RulerDomain rulerDomain = mRulerY->GetDomain();
2313 mScrollPrePosition.y = -WrapInDomain(-mScrollPrePosition.y, rulerDomain.min, rulerDomain.max);
2314 DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y );
2315 handle.SetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, mScrollPrePosition);
2317 SnapInternalYTo(mScrollPostPosition.y);
2320 DALI_LOG_SCROLL_STATE("[0x%X] scrollingFinished[%d] Animation[0x%X]", this, scrollingFinished, source.GetObjectPtr());
2322 if(scrollingFinished)
2324 HandleSnapAnimationFinished();
2328 void ScrollView::OnSnapInternalPositionFinished( Animation& source )
2330 Actor self = Self();
2331 UpdateLocalScrollProperties();
2332 if( source == mInternalXAnimation )
2334 DALI_LOG_SCROLL_STATE("[0x%X] Finished X PostPosition Animation", this );
2336 // clear internal x animation flags
2337 mScrollStateFlags &= ~SCROLL_X_STATE_MASK;
2338 mInternalXAnimation.Reset();
2339 WrapPosition(mScrollPrePosition);
2341 if( source == mInternalYAnimation )
2343 DALI_LOG_SCROLL_STATE("[0x%X] Finished Y PostPosition Animation", this );
2345 mScrollStateFlags &= ~SCROLL_Y_STATE_MASK;
2346 mInternalYAnimation.Reset();
2347 WrapPosition(mScrollPrePosition);
2351 void ScrollView::SnapInternalXTo(float position)
2353 Actor self = Self();
2355 StopAnimation(mInternalXAnimation);
2357 // erase current state flags
2358 mScrollStateFlags &= ~SCROLL_X_STATE_MASK;
2360 // if internal x not equal to inputed parameter, animate it
2361 float duration = std::min(fabsf((position - mScrollPrePosition.x) / mMaxOvershoot.x) * mSnapOvershootDuration, mSnapOvershootDuration);
2362 DALI_LOG_SCROLL_STATE("[0x%X] duration[%.2f]", this, duration );
2363 if( duration > Math::MACHINE_EPSILON_1 )
2365 DALI_LOG_SCROLL_STATE("[0x%X] Starting X Snap Animation to[%.2f]", this, position );
2367 mInternalXAnimation = Animation::New(duration);
2368 mInternalXAnimation.FinishedSignal().Connect(this, &ScrollView::OnSnapInternalPositionFinished);
2369 mInternalXAnimation.AnimateTo(Property(self, Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, 0), position);
2370 mInternalXAnimation.Play();
2372 // add internal animation state flag
2373 mScrollStateFlags |= SnappingInternalX;
2377 void ScrollView::SnapInternalYTo(float position)
2379 Actor self = Self();
2381 StopAnimation(mInternalYAnimation);
2383 // erase current state flags
2384 mScrollStateFlags &= ~SCROLL_Y_STATE_MASK;
2386 // if internal y not equal to inputed parameter, animate it
2387 float duration = std::min(fabsf((position - mScrollPrePosition.y) / mMaxOvershoot.y) * mSnapOvershootDuration, mSnapOvershootDuration);
2388 DALI_LOG_SCROLL_STATE("[0x%X] duration[%.2f]", this, duration );
2389 if( duration > Math::MACHINE_EPSILON_1 )
2391 DALI_LOG_SCROLL_STATE("[0x%X] Starting Y Snap Animation to[%.2f]", this, position );
2393 mInternalYAnimation = Animation::New(duration);
2394 mInternalYAnimation.FinishedSignal().Connect(this, &ScrollView::OnSnapInternalPositionFinished);
2395 mInternalYAnimation.AnimateTo(Property(self, Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, 1), position);
2396 mInternalYAnimation.Play();
2398 // add internal animation state flag
2399 mScrollStateFlags |= SnappingInternalY;
2403 void ScrollView::GestureStarted()
2405 // we handle the first gesture.
2406 // if we're currently doing a gesture and receive another
2407 // we continue and combine the effects of the gesture instead of reseting.
2408 if(mGestureStackDepth++==0)
2410 Actor self = Self();
2411 StopTouchDownTimer();
2413 mPanDelta = Vector2::ZERO;
2414 mLastVelocity = Vector2::ZERO;
2417 mLockAxis = LockPossible;
2420 if( mScrollStateFlags & SCROLL_X_STATE_MASK )
2422 StopAnimation(mInternalXAnimation);
2424 if( mScrollStateFlags & SCROLL_Y_STATE_MASK )
2426 StopAnimation(mInternalYAnimation);
2428 mScrollStateFlags = 0;
2430 if(mScrolling) // are we interrupting a current scroll?
2432 // set mScrolling to false, in case user has code that interrogates mScrolling Getter() in complete.
2434 // send negative scroll position since scroll internal scroll position works as an offset for actors,
2435 // give applications the position within the domain from the scroll view's anchor position
2436 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignal 5 [%.2f, %.2f]", this, -mScrollPostPosition.x, -mScrollPostPosition.y);
2437 mScrollCompletedSignal.Emit( -mScrollPostPosition );
2442 void ScrollView::GestureContinuing(const Vector2& panDelta)
2444 mPanDelta.x+= panDelta.x;
2445 mPanDelta.y+= panDelta.y;
2447 // Save the velocity, there is a bug in PanGesture
2448 // Whereby the Gesture::Finished's velocity is either:
2449 // NaN (due to time delta of zero between the last two events)
2450 // or 0 (due to position being the same between the last two events)
2452 // Axis Auto Lock - locks the panning to the horizontal or vertical axis if the pan
2453 // appears mostly horizontal or mostly vertical respectively.
2456 mLockAxis = GetLockAxis(mPanDelta, mLockAxis, mAxisAutoLockGradient);
2457 } // end if mAxisAutoLock
2460 // TODO: Upgrade to use a more powerful gesture detector (one that supports multiple touches on pan - so works as pan and flick gesture)
2461 // BUG: Gesture::Finished doesn't always return velocity on release (due to
2462 // timeDelta between last two events being 0 sometimes, or posiiton being the same)
2463 void ScrollView::OnPan( const PanGesture& gesture )
2465 // Guard against destruction during signal emission
2466 // Note that Emit() methods are called indirectly e.g. from within ScrollView::OnGestureEx()
2467 Actor self( Self() );
2471 DALI_LOG_SCROLL_STATE("[0x%X] Pan Ignored, Insensitive", this);
2473 // If another callback on the same original signal disables sensitivity,
2474 // this callback will still be called, so we must suppress it.
2478 // translate Gesture input to get useful data...
2479 switch(gesture.state)
2481 case Gesture::Started:
2483 DALI_LOG_SCROLL_STATE("[0x%X] Pan Started", this);
2484 mPanStartPosition = gesture.position - gesture.displacement;
2485 UpdateLocalScrollProperties();
2488 self.SetProperty( Toolkit::ScrollView::Property::PANNING, true );
2489 self.SetProperty( Toolkit::ScrollView::Property::START_PAGE_POSITION, Vector3(gesture.position.x, gesture.position.y, 0.0f) );
2491 UpdateMainInternalConstraint();
2492 Toolkit::ScrollBar scrollBar = mScrollBar.GetHandle();
2493 if( scrollBar && mTransientScrollBar )
2495 Vector3 size = Self().GetCurrentSize();
2496 const Toolkit::RulerDomain& rulerDomainX = mRulerX->GetDomain();
2497 const Toolkit::RulerDomain& rulerDomainY = mRulerY->GetDomain();
2499 if( ( rulerDomainX.max > size.width ) || ( rulerDomainY.max > size.height ) )
2501 scrollBar.ShowIndicator();
2507 case Gesture::Continuing:
2511 DALI_LOG_SCROLL_STATE("[0x%X] Pan Continuing", this);
2512 GestureContinuing(gesture.screenDisplacement);
2516 // If we do not think we are panning, then we should not do anything here
2522 case Gesture::Finished:
2523 case Gesture::Cancelled:
2527 DALI_LOG_SCROLL_STATE("[0x%X] Pan %s", this, ( ( gesture.state == Gesture::Finished ) ? "Finished" : "Cancelled" ) );
2529 UpdateLocalScrollProperties();
2530 mLastVelocity = gesture.velocity;
2532 self.SetProperty( Toolkit::ScrollView::Property::PANNING, false );
2534 if( mScrollMainInternalPrePositionConstraint )
2536 mScrollMainInternalPrePositionConstraint.Remove();
2539 Toolkit::ScrollBar scrollBar = mScrollBar.GetHandle();
2540 if( scrollBar && mTransientScrollBar )
2542 scrollBar.HideIndicator();
2547 // If we do not think we are panning, then we should not do anything here
2553 case Gesture::Possible:
2554 case Gesture::Clear:
2556 // Nothing to do, not needed.
2560 } // end switch(gesture.state)
2562 OnGestureEx(gesture.state);
2565 void ScrollView::OnGestureEx(Gesture::State state)
2567 // call necessary signals for application developer
2569 if(state == Gesture::Started)
2571 Vector2 currentScrollPosition = GetCurrentScrollPosition();
2572 Self().SetProperty(Toolkit::ScrollView::Property::SCROLLING, true);
2574 DALI_LOG_SCROLL_STATE("[0x%X] mScrollStartedSignal 2 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
2575 mScrollStartedSignal.Emit( currentScrollPosition );
2577 else if( (state == Gesture::Finished) ||
2578 (state == Gesture::Cancelled) ) // Finished/default
2580 // when all the gestures have finished, we finish the transform.
2581 // so if a user decides to pan (1 gesture), and then pan+zoom (2 gestures)
2582 // then stop panning (back to 1 gesture), and then stop zooming (0 gestures).
2583 // this is the point we end, and perform necessary snapping.
2584 mGestureStackDepth--;
2585 if(mGestureStackDepth==0)
2587 // no flick if we have not exceeded min flick distance
2588 if( (fabsf(mPanDelta.x) < mMinFlickDistance.x)
2589 && (fabsf(mPanDelta.y) < mMinFlickDistance.y) )
2591 // reset flick velocity
2592 mLastVelocity = Vector2::ZERO;
2598 DALI_LOG_SCROLL_STATE("[0x%X] mGestureStackDepth[%d]", this, mGestureStackDepth);
2603 void ScrollView::FinishTransform()
2605 // at this stage internal x and x scroll position should have followed prescroll position exactly
2606 Actor self = Self();
2608 PreAnimatedScrollSetup();
2610 // convert pixels/millisecond to pixels per second
2611 bool animating = SnapWithVelocity(mLastVelocity * 1000.0f);
2615 // if not animating, then this pan has completed right now.
2616 SetScrollUpdateNotification(false);
2618 Self().SetProperty(Toolkit::ScrollView::Property::SCROLLING, false);
2620 if( fabs(mScrollPrePosition.x - mScrollTargetPosition.x) > Math::MACHINE_EPSILON_10 )
2622 SnapInternalXTo(mScrollTargetPosition.x);
2624 if( fabs(mScrollPrePosition.y - mScrollTargetPosition.y) > Math::MACHINE_EPSILON_10 )
2626 SnapInternalYTo(mScrollTargetPosition.y);
2628 Vector2 currentScrollPosition = GetCurrentScrollPosition();
2629 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignal 6 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
2630 mScrollCompletedSignal.Emit( currentScrollPosition );
2634 Vector2 ScrollView::GetOvershoot(Vector2& position) const
2636 Vector3 size = Self().GetCurrentSize();
2639 const RulerDomain rulerDomainX = mRulerX->GetDomain();
2640 const RulerDomain rulerDomainY = mRulerY->GetDomain();
2642 if(mRulerX->IsEnabled() && rulerDomainX.enabled)
2644 const float left = rulerDomainX.min - position.x;
2645 const float right = size.width - rulerDomainX.max - position.x;
2652 overshoot.x = right;
2656 if(mRulerY->IsEnabled() && rulerDomainY.enabled)
2658 const float top = rulerDomainY.min - position.y;
2659 const float bottom = size.height - rulerDomainY.max - position.y;
2666 overshoot.y = bottom;
2673 bool ScrollView::OnAccessibilityPan(PanGesture gesture)
2675 // Keep track of whether this is an AccessibilityPan
2676 mInAccessibilityPan = true;
2678 mInAccessibilityPan = false;
2683 void ScrollView::ClampPosition(Vector2& position) const
2685 ClampState2D clamped;
2686 ClampPosition(position, clamped);
2689 void ScrollView::ClampPosition(Vector2& position, ClampState2D &clamped) const
2691 Vector3 size = Self().GetCurrentSize();
2693 position.x = -mRulerX->Clamp(-position.x, size.width, 1.0f, clamped.x); // NOTE: X & Y rulers think in -ve coordinate system.
2694 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.
2697 void ScrollView::WrapPosition(Vector2& position) const
2701 const RulerDomain rulerDomainX = mRulerX->GetDomain();
2702 const RulerDomain rulerDomainY = mRulerY->GetDomain();
2704 if(mRulerX->IsEnabled())
2706 position.x = -WrapInDomain(-position.x, rulerDomainX.min, rulerDomainX.max);
2709 if(mRulerY->IsEnabled())
2711 position.y = -WrapInDomain(-position.y, rulerDomainY.min, rulerDomainY.max);
2716 void ScrollView::UpdateMainInternalConstraint()
2718 // TODO: Only update the constraints which have changed, rather than remove all and add all again.
2719 // Requires a dali-core ApplyConstraintAt, or a ReplaceConstraint. The former is probably more flexible.
2720 Actor self = Self();
2721 PanGestureDetector detector( GetPanGestureDetector() );
2723 if(mScrollMainInternalPositionConstraint)
2725 mScrollMainInternalPositionConstraint.Remove();
2726 mScrollMainInternalDeltaConstraint.Remove();
2727 mScrollMainInternalFinalConstraint.Remove();
2728 mScrollMainInternalRelativeConstraint.Remove();
2729 mScrollMainInternalDomainConstraint.Remove();
2730 mScrollMainInternalPrePositionMaxConstraint.Remove();
2732 if( mScrollMainInternalPrePositionConstraint )
2734 mScrollMainInternalPrePositionConstraint.Remove();
2737 // TODO: It's probably better to use a local displacement value as this will give a displacement when scrolling just commences
2738 // but we need to make sure than the gesture system gives displacement since last frame (60Hz), not displacement since last touch event (90Hz).
2740 // 1. First calculate the pre-position (this is the scroll position if no clamping has taken place)
2741 Vector2 initialPanMask = Vector2(mRulerX->IsEnabled() ? 1.0f : 0.0f, mRulerY->IsEnabled() ? 1.0f : 0.0f);
2743 if( mLockAxis == LockVertical )
2745 initialPanMask.y = 0.0f;
2747 else if( mLockAxis == LockHorizontal )
2749 initialPanMask.x = 0.0f;
2754 mScrollMainInternalPrePositionConstraint = Constraint::New<Vector2>( self,
2755 Toolkit::ScrollView::Property::SCROLL_PRE_POSITION,
2756 InternalPrePositionConstraint( mPanStartPosition,
2759 mAxisAutoLockGradient,
2764 mScrollMainInternalPrePositionConstraint.AddSource( Source( detector, PanGestureDetector::Property::LOCAL_POSITION ) );
2765 mScrollMainInternalPrePositionConstraint.AddSource( Source( detector, PanGestureDetector::Property::PANNING ) );
2766 mScrollMainInternalPrePositionConstraint.AddSource( Source( self, Actor::Property::SIZE ) );
2767 mScrollMainInternalPrePositionConstraint.Apply();
2770 // 2. Second calculate the clamped position (actual position)
2771 mScrollMainInternalPositionConstraint = Constraint::New<Vector2>( self,
2772 Toolkit::ScrollView::Property::SCROLL_POSITION,
2773 InternalPositionConstraint( mRulerX->GetDomain(),
2774 mRulerY->GetDomain(),
2776 mScrollMainInternalPositionConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_PRE_POSITION ) );
2777 mScrollMainInternalPositionConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::SCROLL_POSITION_MIN ) );
2778 mScrollMainInternalPositionConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::SCROLL_POSITION_MAX ) );
2779 mScrollMainInternalPositionConstraint.AddSource( Source( self, Actor::Property::SIZE ) );
2780 mScrollMainInternalPositionConstraint.Apply();
2782 mScrollMainInternalDeltaConstraint = Constraint::New<Vector2>( self, Toolkit::ScrollView::Property::SCROLL_POSITION_DELTA, InternalPositionDeltaConstraint );
2783 mScrollMainInternalDeltaConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_POSITION ) );
2784 mScrollMainInternalDeltaConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_DOMAIN_OFFSET ) );
2785 mScrollMainInternalDeltaConstraint.Apply();
2787 mScrollMainInternalFinalConstraint = Constraint::New<Vector2>( self, Toolkit::ScrollView::Property::SCROLL_FINAL,
2788 InternalFinalConstraint( FinalDefaultAlphaFunction,
2789 FinalDefaultAlphaFunction ) );
2790 mScrollMainInternalFinalConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_POSITION ) );
2791 mScrollMainInternalFinalConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::OVERSHOOT_X ) );
2792 mScrollMainInternalFinalConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::OVERSHOOT_Y ) );
2793 mScrollMainInternalFinalConstraint.Apply();
2795 mScrollMainInternalRelativeConstraint = Constraint::New<Vector2>( self, Toolkit::Scrollable::Property::SCROLL_RELATIVE_POSITION, InternalRelativePositionConstraint );
2796 mScrollMainInternalRelativeConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_POSITION ) );
2797 mScrollMainInternalRelativeConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::SCROLL_POSITION_MIN ) );
2798 mScrollMainInternalRelativeConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::SCROLL_POSITION_MAX ) );
2799 mScrollMainInternalRelativeConstraint.AddSource( LocalSource( Actor::Property::SIZE ) );
2800 mScrollMainInternalRelativeConstraint.Apply();
2802 mScrollMainInternalDomainConstraint = Constraint::New<Vector2>( self, Toolkit::ScrollView::Property::SCROLL_DOMAIN_SIZE, InternalScrollDomainConstraint );
2803 mScrollMainInternalDomainConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::SCROLL_POSITION_MIN ) );
2804 mScrollMainInternalDomainConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::SCROLL_POSITION_MAX ) );
2805 mScrollMainInternalDomainConstraint.AddSource( LocalSource( Actor::Property::SIZE ) );
2806 mScrollMainInternalDomainConstraint.Apply();
2808 mScrollMainInternalPrePositionMaxConstraint = Constraint::New<Vector2>( self, Toolkit::ScrollView::Property::SCROLL_PRE_POSITION_MAX, InternalPrePositionMaxConstraint );
2809 mScrollMainInternalPrePositionMaxConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::SCROLL_POSITION_MAX ) );
2810 mScrollMainInternalPrePositionMaxConstraint.AddSource( LocalSource( Actor::Property::SIZE ) );
2811 mScrollMainInternalPrePositionMaxConstraint.Apply();
2813 // When panning we want to make sure overshoot values are affected by pre position and post position
2814 SetOvershootConstraintsEnabled(!mWrapMode);
2817 void ScrollView::SetOvershootConstraintsEnabled(bool enabled)
2819 Actor self( Self() );
2820 // remove and reset, it may now be in wrong order with the main internal constraints
2821 if( mScrollMainInternalOvershootXConstraint )
2823 mScrollMainInternalOvershootXConstraint.Remove();
2824 mScrollMainInternalOvershootXConstraint.Reset();
2825 mScrollMainInternalOvershootYConstraint.Remove();
2826 mScrollMainInternalOvershootYConstraint.Reset();
2830 mScrollMainInternalOvershootXConstraint= Constraint::New<float>( self, Toolkit::ScrollView::Property::OVERSHOOT_X, OvershootXConstraint(mMaxOvershoot.x) );
2831 mScrollMainInternalOvershootXConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_PRE_POSITION ) );
2832 mScrollMainInternalOvershootXConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_POSITION ) );
2833 mScrollMainInternalOvershootXConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::CAN_SCROLL_HORIZONTAL ) );
2834 mScrollMainInternalOvershootXConstraint.Apply();
2836 mScrollMainInternalOvershootYConstraint = Constraint::New<float>( self, Toolkit::ScrollView::Property::OVERSHOOT_Y, OvershootYConstraint(mMaxOvershoot.y) );
2837 mScrollMainInternalOvershootYConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_PRE_POSITION ) );
2838 mScrollMainInternalOvershootYConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_POSITION ) );
2839 mScrollMainInternalOvershootYConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::CAN_SCROLL_VERTICAL ) );
2840 mScrollMainInternalOvershootYConstraint.Apply();
2844 self.SetProperty(Toolkit::ScrollView::Property::OVERSHOOT_X, 0.0f);
2845 self.SetProperty(Toolkit::ScrollView::Property::OVERSHOOT_Y, 0.0f);
2849 void ScrollView::SetInternalConstraints()
2851 // Internal constraints (applied to target ScrollBase Actor itself) /////////
2852 UpdateMainInternalConstraint();
2854 // User definable constraints to apply to all child actors //////////////////
2855 Actor self = Self();
2857 // Apply some default constraints to ScrollView & its bound actors
2858 // Movement + Wrap function
2860 Constraint constraint;
2862 // MoveActor (scrolling)
2863 constraint = Constraint::New<Vector3>( self, Actor::Property::POSITION, MoveActorConstraint );
2864 constraint.AddSource( Source( self, Toolkit::ScrollView::Property::SCROLL_POSITION ) );
2865 constraint.SetRemoveAction(Constraint::Discard);
2866 ApplyConstraintToBoundActors(constraint);
2868 // WrapActor (wrap functionality)
2869 constraint = Constraint::New<Vector3>( self, Actor::Property::POSITION, WrapActorConstraint );
2870 constraint.AddSource( LocalSource( Actor::Property::SCALE ) );
2871 constraint.AddSource( LocalSource( Actor::Property::ANCHOR_POINT ) );
2872 constraint.AddSource( LocalSource( Actor::Property::SIZE ) );
2873 constraint.AddSource( Source( self, Toolkit::Scrollable::Property::SCROLL_POSITION_MIN ) );
2874 constraint.AddSource( Source( self, Toolkit::Scrollable::Property::SCROLL_POSITION_MAX ) );
2875 constraint.AddSource( Source( self, Toolkit::ScrollView::Property::WRAP ) );
2876 constraint.SetRemoveAction(Constraint::Discard);
2877 ApplyConstraintToBoundActors(constraint);
2880 void ScrollView::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
2882 Toolkit::ScrollView scrollView = Toolkit::ScrollView::DownCast( Dali::BaseHandle( object ) );
2886 ScrollView& scrollViewImpl( GetImpl( scrollView ) );
2889 case Toolkit::ScrollView::Property::WRAP_ENABLED:
2891 scrollViewImpl.SetWrapMode( value.Get<bool>() );
2894 case Toolkit::ScrollView::Property::PANNING_ENABLED:
2896 scrollViewImpl.SetScrollSensitive( value.Get<bool>() );
2899 case Toolkit::ScrollView::Property::AXIS_AUTO_LOCK_ENABLED:
2901 scrollViewImpl.SetAxisAutoLock( value.Get<bool>() );
2904 case Toolkit::ScrollView::Property::WHEEL_SCROLL_DISTANCE_STEP:
2906 scrollViewImpl.SetWheelScrollDistanceStep( value.Get<Vector2>() );
2913 Property::Value ScrollView::GetProperty( BaseObject* object, Property::Index index )
2915 Property::Value value;
2917 Toolkit::ScrollView scrollView = Toolkit::ScrollView::DownCast( Dali::BaseHandle( object ) );
2921 ScrollView& scrollViewImpl( GetImpl( scrollView ) );
2924 case Toolkit::ScrollView::Property::WRAP_ENABLED:
2926 value = scrollViewImpl.GetWrapMode();
2929 case Toolkit::ScrollView::Property::PANNING_ENABLED:
2931 value = scrollViewImpl.GetScrollSensitive();
2934 case Toolkit::ScrollView::Property::AXIS_AUTO_LOCK_ENABLED:
2936 value = scrollViewImpl.GetAxisAutoLock();
2939 case Toolkit::ScrollView::Property::WHEEL_SCROLL_DISTANCE_STEP:
2941 value = scrollViewImpl.GetWheelScrollDistanceStep();
2950 } // namespace Internal
2952 } // namespace Toolkit