2 * Copyright (c) 2014 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 <dali/public-api/animation/constraints.h>
23 #include <dali/public-api/common/stage.h>
24 #include <dali/public-api/events/mouse-wheel-event.h>
25 #include <dali/public-api/events/touch-event.h>
26 #include <dali/public-api/object/type-registry.h>
27 #include <dali/integration-api/debug.h>
30 #include <dali-toolkit/public-api/controls/scrollable/scroll-view/scroll-view-constraints.h>
31 #include <dali-toolkit/public-api/controls/scrollable/scroll-component-impl.h>
32 #include <dali-toolkit/internal/controls/scrollable/scroll-view/scroll-view-effect-impl.h>
33 #include <dali-toolkit/internal/controls/scrollable/scroll-view/scroll-overshoot-indicator-impl.h>
35 //#define ENABLED_SCROLL_STATE_LOGGING
37 #ifdef ENABLED_SCROLL_STATE_LOGGING
38 #define DALI_LOG_SCROLL_STATE(format, args...) Dali::Integration::Log::LogMessage(Dali::Integration::Log::DebugInfo, "%s:%d " format "\n", __PRETTY_FUNCTION__, __LINE__, ## args)
40 #define DALI_LOG_SCROLL_STATE(format, args...)
43 // TODO: Change to two class system:
44 // 1. DraggableActor (is an actor which can be dragged anywhere, can be set to range using the ruler)
45 // 2. ScrollView (contains a draggable actor that can a) be dragged in the negative X, and Y domain, b) has a hitArea for touches)
46 // TODO: external components (page and status overlays).
48 // TODO: upgrade Vector2/3 to support returning Unit vectors, normals, & cross product (dot product is already provided)
55 const int DEFAULT_REFRESH_INTERVAL_MILLISECONDS = 50; ///< Refresh rate TODO: Animation should have an update signal (and see item-view-impl)
56 const Vector2 DEFAULT_MIN_FLICK_DISTANCE(30.0f, 30.0f); ///< minimum distance for pan before flick allowed
57 const float DEFAULT_MIN_FLICK_SPEED_THRESHOLD(500.0f); ///< Minimum pan speed required for flick in pixels/s
58 const float FREE_FLICK_SPEED_THRESHOLD = 200.0f; ///< Free-Flick threshold in pixels/ms
59 const float AUTOLOCK_AXIS_MINIMUM_DISTANCE2 = 100.0f; ///< Auto-lock axis after minimum distance squared.
60 const float FLICK_ORTHO_ANGLE_RANGE = 75.0f; ///< degrees. (if >45, then supports diagonal flicking)
61 const unsigned int MAXIMUM_NUMBER_OF_VALUES = 5; ///< Number of values to use for weighted pan calculation.
62 const Vector2 DEFAULT_MOUSE_WHEEL_SCROLL_DISTANCE_STEP_PROPORTION = Vector2(0.17f, 0.1f); ///< The step of horizontal scroll distance in the proportion of stage size for each mouse wheel event received.
63 const unsigned long MINIMUM_TIME_BETWEEN_DOWN_AND_UP_FOR_RESET( 150u );
64 const float DEFAULT_OVERSHOOT_ANIMATION_DURATION = 0.35f; // time in seconds
65 const Vector2 OVERSCROLL_CLAMP(1.0f, 1.0f); // maximum overscroll allowed in pixels when overshoot indicator is being used
66 const float TOUCH_DOWN_TIMER_INTERVAL = 100.0f;
67 const float DEFAULT_SCROLL_UPDATE_DISTANCE( 30.0f ); ///< Default distance to travel in pixels for scroll update signal
69 // predefined effect values
70 const Vector3 ANGLE_CAROUSEL_ROTATE(Math::PI * 0.5f, Math::PI * 0.5f, 0.0f);
71 const Vector3 ANGLE_CUBE_PAGE_ROTATE(Math::PI * 0.2f, Math::PI * 0.2f, 0.0f); ///< Cube page rotates as if it has ten sides with the camera positioned inside
72 const Vector2 ANGLE_CUSTOM_CUBE_SWING(-Math::PI * 0.45f, -Math::PI * 0.45f); ///< outer cube pages swing 90 degrees as they pan offscreen
73 const Vector2 ANGLE_SPIRAL_SWING_IN(Math::PI * 0.5f, Math::PI * 0.5f);
74 const Vector2 ANGLE_SPIRAL_SWING_OUT(Math::PI * 0.35f, Math::PI * 0.35f);
75 const Vector2 ANGLE_OUTER_CUBE_SWING(Math::PI * 0.5f, Math::PI * 0.5f); ///< outer cube pages swing 90 degrees as they pan offscreen
77 // Helpers ////////////////////////////////////////////////////////////////////////////////////////
80 * Find the vector (distance) from (a) to (b)
81 * in domain (start) to (end)
82 * (\ / start) (\ / end)
85 * @note assumes both (a) and (b) are already with the domain
88 * @param[in] a the current point
89 * @param[in] b the target point
90 * @param[in] start the start of the domain
91 * @param[in] end the end of the domain
92 * @param[in] bias whether to only take the right direction or the left direction,
93 * or the shortest direction.
94 * @return the shortest direction and distance
96 float VectorInDomain(float a, float b, float start, float end, Dali::Toolkit::DirectionBias bias)
98 if(bias == Dali::Toolkit::DirectionBiasNone)
100 return ShortestDistanceInDomain( a, b, start, end );
103 float size = end-start;
109 if(bias == Dali::Toolkit::DirectionBiasRight) // going right, take the vector.
115 float aRight = a+size;
122 if(bias == Dali::Toolkit::DirectionBiasLeft) // going left, take the vector.
128 float aLeft = a-size;
135 * Returns the position of the anchor within actor
137 * @param actor The Actor
138 * @param anchor The Anchor point of interest.
139 * @return The position of the Anchor
141 Vector3 GetPositionOfAnchor(Actor &actor, const Vector3 &anchor)
143 Vector3 childPosition = actor.GetCurrentPosition();
144 Vector3 childAnchor = - actor.GetCurrentAnchorPoint() + anchor;
145 Vector3 childSize = actor.GetCurrentSize();
147 return childPosition + childAnchor * childSize;
150 // AlphaFunctions /////////////////////////////////////////////////////////////////////////////////
152 float FinalDefaultAlphaFunction(float offset)
154 return offset * 0.5f;
158 * ConstantDecelerationAlphaFunction
159 * Newtoninan distance for constant deceleration
160 * v = 1 - t, s = t - 1/2 t^2
161 * when t = 0, s = 0.0 (min distance)
162 * when t = 1, s = 0.5 (max distance)
163 * progress = s / (max-min) = 2t - t^2
165 * @param[in] offset The input progress
166 * @return The output progress
168 float ConstantDecelerationAlphaFunction(float progress)
170 return progress * 2.0f - progress * progress;
173 // Internal Constraints ///////////////////////////////////////////////////////////////////////////
176 * Internal Relative position Constraint
177 * Generates the relative position value of the scroll view
178 * based on the absolute position, and it's relation to the
179 * scroll domain. This is a value from 0.0f to 1.0f in each
180 * scroll position axis.
182 Vector3 InternalRelativePositionConstraint(const Vector3& current,
183 const PropertyInput& scrollPositionProperty,
184 const PropertyInput& scrollMinProperty,
185 const PropertyInput& scrollMaxProperty,
186 const PropertyInput& scrollSizeProperty)
188 Vector3 position = -scrollPositionProperty.GetVector3();
189 const Vector3& min = scrollMinProperty.GetVector3();
190 const Vector3& max = scrollMaxProperty.GetVector3();
191 const Vector3& size = scrollSizeProperty.GetVector3();
193 position.x = WrapInDomain(position.x, min.x, max.x);
194 position.y = WrapInDomain(position.y, min.y, max.y);
196 Vector3 relativePosition;
197 Vector3 domainSize = (max - min) - size;
199 relativePosition.x = domainSize.x > Math::MACHINE_EPSILON_1 ? fabsf((position.x - min.x) / domainSize.x) : 0.0f;
200 relativePosition.y = domainSize.y > Math::MACHINE_EPSILON_1 ? fabsf((position.y - min.y) / domainSize.y) : 0.0f;
202 return relativePosition;
205 } // unnamed namespace
220 * Returns whether to lock scrolling to a particular axis
222 * @param[in] panDelta Distance panned since gesture started
223 * @param[in] currentLockAxis The current lock axis value
224 * @param[in] lockGradient How quickly to lock to a particular axis
226 * @return The new axis lock state
228 ScrollView::LockAxis GetLockAxis(const Vector2& panDelta, ScrollView::LockAxis currentLockAxis, float lockGradient)
230 if(panDelta.LengthSquared() > AUTOLOCK_AXIS_MINIMUM_DISTANCE2 &&
231 currentLockAxis == ScrollView::LockPossible)
233 float dx = fabsf(panDelta.x);
234 float dy = fabsf(panDelta.y);
235 if(dx * lockGradient >= dy)
237 // 0.36:1 gradient to the horizontal (deviate < 20 degrees)
238 currentLockAxis = ScrollView::LockVertical;
240 else if(dy * lockGradient > dx)
242 // 0.36:1 gradient to the vertical (deviate < 20 degrees)
243 currentLockAxis = ScrollView::LockHorizontal;
247 currentLockAxis = ScrollView::LockNone;
250 return currentLockAxis;
254 * Internal Pre-Position Property Constraint.
256 * Generates position property based on current position + gesture displacement.
257 * Or generates position property based on positionX/Y.
258 * Note: This is the position prior to any clamping at scroll boundaries.
260 struct InternalPrePositionConstraint
262 InternalPrePositionConstraint(const Vector2& initialPanPosition,
263 const Vector2& initialPanMask,
265 float axisAutoLockGradient,
266 ScrollView::LockAxis initialLockAxis,
267 const Vector2& maxOvershoot,
268 const RulerDomain& domainX, const RulerDomain& domainY)
269 : mLocalStart(initialPanPosition),
270 mInitialPanMask(initialPanMask),
271 mDomainMin( -domainX.min, -domainY.min ),
272 mDomainMax( -domainX.max, -domainY.max ),
273 mMaxOvershoot(maxOvershoot),
274 mAxisAutoLockGradient(axisAutoLockGradient),
275 mLockAxis(initialLockAxis),
276 mAxisAutoLock(axisAutoLock),
278 mClampX( domainX.enabled ),
279 mClampY( domainY.enabled )
283 Vector3 operator()(const Vector3& current,
284 const PropertyInput& gesturePositionProperty,
285 const PropertyInput& sizeProperty)
287 Vector3 scrollPostPosition = current;
288 Vector2 panPosition = gesturePositionProperty.GetVector2();
292 mPrePosition = current;
293 mCurrentPanMask = mInitialPanMask;
297 // Calculate Deltas...
298 Vector2 currentPosition = gesturePositionProperty.GetVector2();
299 Vector2 panDelta( currentPosition - mLocalStart );
301 // Axis Auto Lock - locks the panning to the horizontal or vertical axis if the pan
302 // appears mostly horizontal or mostly vertical respectively...
305 mLockAxis = GetLockAxis(panDelta, mLockAxis, mAxisAutoLockGradient);
306 if( mLockAxis == ScrollView::LockVertical )
308 mCurrentPanMask.y = 0.0f;
310 else if( mLockAxis == ScrollView::LockHorizontal )
312 mCurrentPanMask.x = 0.0f;
316 // Restrict deltas based on ruler enable/disable and axis-lock state...
317 panDelta *= mCurrentPanMask;
319 // Perform Position transform based on input deltas...
320 scrollPostPosition = mPrePosition;
321 scrollPostPosition.GetVectorXY() += panDelta;
323 // if no wrapping then clamp preposition to maximum overshoot amount
324 const Vector3& size = sizeProperty.GetVector3();
327 float newXPosition = Clamp(scrollPostPosition.x, (mDomainMax.x + size.x) - mMaxOvershoot.x, mDomainMin.x + mMaxOvershoot.x );
328 if( (newXPosition < scrollPostPosition.x - Math::MACHINE_EPSILON_1)
329 || (newXPosition > scrollPostPosition.x + Math::MACHINE_EPSILON_1) )
331 mPrePosition.x = newXPosition;
332 mLocalStart.x = panPosition.x;
334 scrollPostPosition.x = newXPosition;
338 float newYPosition = Clamp(scrollPostPosition.y, (mDomainMax.y + size.y) - mMaxOvershoot.y, mDomainMin.y + mMaxOvershoot.y );
339 if( (newYPosition < scrollPostPosition.y - Math::MACHINE_EPSILON_1)
340 || (newYPosition > scrollPostPosition.y + Math::MACHINE_EPSILON_1) )
342 mPrePosition.y = newYPosition;
343 mLocalStart.y = panPosition.y;
345 scrollPostPosition.y = newYPosition;
348 return scrollPostPosition;
351 Vector3 mPrePosition;
353 Vector2 mInitialPanMask; ///< Initial pan mask (based on ruler settings)
354 Vector2 mCurrentPanMask; ///< Current pan mask that can be altered by axis lock mode.
357 Vector2 mMaxOvershoot;
359 float mAxisAutoLockGradient; ///< Set by ScrollView
360 ScrollView::LockAxis mLockAxis;
362 bool mAxisAutoLock:1; ///< Set by ScrollView
369 * Internal Position Property Constraint.
371 * Generates position property based on pre-position
372 * Note: This is the position after clamping.
373 * (uses result of InternalPrePositionConstraint)
375 struct InternalPositionConstraint
377 InternalPositionConstraint(const RulerDomain& domainX, const RulerDomain& domainY, bool wrap)
378 : mDomainMin( -domainX.min, -domainY.min ),
379 mDomainMax( -domainX.max, -domainY.max ),
380 mClampX( domainX.enabled ),
381 mClampY( domainY.enabled ),
386 Vector3 operator()(const Vector3& current,
387 const PropertyInput& scrollPositionProperty,
388 const PropertyInput& scrollMinProperty,
389 const PropertyInput& scrollMaxProperty,
390 const PropertyInput& scrollSizeProperty)
392 Vector3 position = scrollPositionProperty.GetVector3();
393 const Vector2& size = scrollSizeProperty.GetVector3().GetVectorXY();
394 const Vector3& min = scrollMinProperty.GetVector3();
395 const Vector3& max = scrollMaxProperty.GetVector3();
399 position.x = -WrapInDomain(-position.x, min.x, max.x);
400 position.y = -WrapInDomain(-position.y, min.y, max.y);
404 // clamp post position to domain
405 position.x = mClampX ? Clamp(position.x, mDomainMax.x + size.x, mDomainMin.x ) : position.x;
406 position.y = mClampY ? Clamp(position.y, mDomainMax.y + size.y, mDomainMin.y ) : position.y;
421 * This constraint updates the X overshoot property using the difference
422 * mPropertyPrePosition.x and mPropertyPosition.x, returning a relative value between 0.0f and 1.0f
424 struct OvershootXConstraint
426 OvershootXConstraint(float maxOvershoot) : mMaxOvershoot(maxOvershoot) {}
428 float operator()(const float& current,
429 const PropertyInput& scrollPrePositionProperty,
430 const PropertyInput& scrollPostPositionProperty,
431 const PropertyInput& canScrollProperty)
433 if( canScrollProperty.GetBoolean() )
435 const Vector3& scrollPrePosition = scrollPrePositionProperty.GetVector3();
436 const Vector3& scrollPostPosition = scrollPostPositionProperty.GetVector3();
437 float newOvershoot = scrollPrePosition.x - scrollPostPosition.x;
438 return (newOvershoot > 0.0f ? std::min(newOvershoot, mMaxOvershoot) : std::max(newOvershoot, -mMaxOvershoot)) / mMaxOvershoot;
447 * This constraint updates the Y overshoot property using the difference
448 * mPropertyPrePosition.y and mPropertyPosition.y, returning a relative value between 0.0f and 1.0f
450 struct OvershootYConstraint
452 OvershootYConstraint(float maxOvershoot) : mMaxOvershoot(maxOvershoot) {}
454 float operator()(const float& current,
455 const PropertyInput& scrollPrePositionProperty,
456 const PropertyInput& scrollPostPositionProperty,
457 const PropertyInput& canScrollProperty)
459 if( canScrollProperty.GetBoolean() )
461 const Vector3& scrollPrePosition = scrollPrePositionProperty.GetVector3();
462 const Vector3& scrollPostPosition = scrollPostPositionProperty.GetVector3();
463 float newOvershoot = scrollPrePosition.y - scrollPostPosition.y;
464 return (newOvershoot > 0.0f ? std::min(newOvershoot, mMaxOvershoot) : std::max(newOvershoot, -mMaxOvershoot)) / mMaxOvershoot;
473 * Internal Position-Delta Property Constraint.
475 * Generates position-delta property based on scroll-position + scroll-offset properties.
477 Vector3 InternalPositionDeltaConstraint(const Vector3& current,
478 const PropertyInput& scrollPositionProperty,
479 const PropertyInput& scrollOffsetProperty)
481 const Vector3& scrollPosition = scrollPositionProperty.GetVector3();
482 const Vector3& scrollOffset = scrollOffsetProperty.GetVector3();
484 return scrollPosition + scrollOffset;
488 * Internal Final Position Constraint
489 * The position of content is:
490 * of scroll-position + f(scroll-overshoot)
491 * where f(...) function defines how overshoot
492 * should affect final-position.
494 struct InternalFinalConstraint
496 InternalFinalConstraint(AlphaFunction functionX,
497 AlphaFunction functionY)
498 : mFunctionX(functionX),
499 mFunctionY(functionY)
503 Vector3 operator()(const Vector3& current,
504 const PropertyInput& scrollPositionProperty,
505 const PropertyInput& scrollOvershootXProperty,
506 const PropertyInput& scrollOvershootYProperty)
508 const float& overshootx = scrollOvershootXProperty.GetFloat();
509 const float& overshooty = scrollOvershootYProperty.GetFloat();
510 Vector3 offset( mFunctionX(overshootx),
511 mFunctionY(overshooty),
514 return scrollPositionProperty.GetVector3() - offset;
517 AlphaFunction mFunctionX;
518 AlphaFunction mFunctionY;
524 return Toolkit::ScrollView::New();
527 TypeRegistration typeRegistration( typeid(Toolkit::ScrollView), typeid(Toolkit::Scrollable), Create );
529 SignalConnectorType signalConnector1( typeRegistration, Toolkit::ScrollView::SIGNAL_SNAP_STARTED, &ScrollView::DoConnectSignal );
534 ///////////////////////////////////////////////////////////////////////////////////////////////////
536 ///////////////////////////////////////////////////////////////////////////////////////////////////
538 Dali::Toolkit::ScrollView ScrollView::New()
540 // Create the implementation
541 ScrollViewPtr scrollView(new ScrollView());
543 // Pass ownership to CustomActor via derived handle
544 Dali::Toolkit::ScrollView handle(*scrollView);
546 // Second-phase init of the implementation
547 // This can only be done after the CustomActor connection has been made...
548 scrollView->Initialize();
553 ScrollView::ScrollView()
556 mGestureStackDepth(0),
557 mScrollStateFlags(0),
558 mMinTouchesForPanning(1),
559 mMaxTouchesForPanning(1),
560 mLockAxis(LockPossible),
561 mScrollUpdateDistance(DEFAULT_SCROLL_UPDATE_DISTANCE),
562 mOvershootDelay(1.0f),
563 mMaxOvershoot(Toolkit::ScrollView::DEFAULT_MAX_OVERSHOOT, Toolkit::ScrollView::DEFAULT_MAX_OVERSHOOT),
564 mUserMaxOvershoot(Toolkit::ScrollView::DEFAULT_MAX_OVERSHOOT, Toolkit::ScrollView::DEFAULT_MAX_OVERSHOOT),
565 mSnapOvershootDuration(Toolkit::ScrollView::DEFAULT_SNAP_OVERSHOOT_DURATION),
566 mSnapOvershootAlphaFunction(AlphaFunctions::EaseOut),
567 mSnapDuration(Toolkit::ScrollView::DEFAULT_SLOW_SNAP_ANIMATION_DURATION),
568 mSnapAlphaFunction(AlphaFunctions::EaseOut),
569 mMinFlickDistance(DEFAULT_MIN_FLICK_DISTANCE),
570 mFlickSpeedThreshold(DEFAULT_MIN_FLICK_SPEED_THRESHOLD),
571 mFlickDuration(Toolkit::ScrollView::DEFAULT_FAST_SNAP_ANIMATION_DURATION),
572 mFlickAlphaFunction(AlphaFunctions::EaseOut),
573 mAxisAutoLockGradient(Toolkit::ScrollView::DEFAULT_AXIS_AUTO_LOCK_GRADIENT),
574 mFrictionCoefficient(Toolkit::ScrollView::DEFAULT_FRICTION_COEFFICIENT),
575 mFlickSpeedCoefficient(Toolkit::ScrollView::DEFAULT_FLICK_SPEED_COEFFICIENT),
576 mMaxFlickSpeed(Toolkit::ScrollView::DEFAULT_MAX_FLICK_SPEED),
577 mInAccessibilityPan(false),
580 mScrollInterrupted(false),
583 mTouchDownTimeoutReached(false),
584 mActorAutoSnapEnabled(false),
585 mAutoResizeContainerEnabled(false),
587 mAxisAutoLock(false),
589 mDefaultMaxOvershoot(true),
590 mCanScrollHorizontal(true),
591 mCanScrollVertical(true)
593 SetRequiresMouseWheelEvents(true);
596 void ScrollView::OnInitialize()
600 // Internal Actor, used to hide actors from enumerations.
601 // Also actors added to Internal actor appear as overlays e.g. ScrollBar components.
602 mInternalActor = Actor::New();
603 mInternalActor.SetDrawMode(DrawMode::OVERLAY);
604 self.Add(mInternalActor);
605 mInternalActor.ApplyConstraint( Constraint::New<Vector3>( Actor::SIZE, ParentSource( Actor::SIZE ), EqualToConstraint() ) );
606 mInternalActor.SetParentOrigin(ParentOrigin::CENTER);
607 mInternalActor.SetAnchorPoint(AnchorPoint::CENTER);
611 // Register Scroll Properties.
612 RegisterProperties();
614 mScrollPostPosition = mScrollPrePosition = Vector3::ZERO;
616 mMouseWheelScrollDistanceStep = Stage::GetCurrent().GetSize() * DEFAULT_MOUSE_WHEEL_SCROLL_DISTANCE_STEP_PROPORTION;
620 mGestureStackDepth = 0;
622 EnableGestureDetection( Gesture::Type( Gesture::Pan ) );
624 // For pan, default to only 1 touch required, ignoring touches outside this range.
625 SetTouchesRequiredForPanning(1, 1, false);
627 // By default we'll allow the user to freely drag the scroll view,
628 // while disabling the other rulers.
629 RulerPtr ruler = new DefaultRuler();
633 EnableScrollComponent(Toolkit::Scrollable::OvershootIndicator);
635 Vector3 size = GetControlSize();
636 UpdatePropertyDomain(size);
637 SetInternalConstraints();
640 void ScrollView::OnControlStageConnection()
642 DALI_LOG_SCROLL_STATE("[0x%X]", this);
646 SetScrollSensitive( false );
647 SetScrollSensitive( true );
649 if(IsScrollComponentEnabled(Toolkit::Scrollable::OvershootIndicator))
651 // try and make sure property notifications are set
652 EnableScrollComponent(Toolkit::Scrollable::OvershootIndicator);
656 void ScrollView::OnControlStageDisconnection()
658 DALI_LOG_SCROLL_STATE("[0x%X]", this);
663 ScrollView::~ScrollView()
665 DALI_LOG_SCROLL_STATE("[0x%X]", this);
668 AlphaFunction ScrollView::GetScrollSnapAlphaFunction() const
670 return mSnapAlphaFunction;
673 void ScrollView::SetScrollSnapAlphaFunction(AlphaFunction alpha)
675 mSnapAlphaFunction = alpha;
678 AlphaFunction ScrollView::GetScrollFlickAlphaFunction() const
680 return mFlickAlphaFunction;
683 void ScrollView::SetScrollFlickAlphaFunction(AlphaFunction alpha)
685 mFlickAlphaFunction = alpha;
688 float ScrollView::GetScrollSnapDuration() const
690 return mSnapDuration;
693 void ScrollView::SetScrollSnapDuration(float time)
695 mSnapDuration = time;
698 float ScrollView::GetScrollFlickDuration() const
700 return mFlickDuration;
703 void ScrollView::SetScrollFlickDuration(float time)
705 mFlickDuration = time;
708 void ScrollView::ApplyEffect(Toolkit::ScrollViewEffect effect)
710 Dali::Toolkit::ScrollView self = Dali::Toolkit::ScrollView::DownCast(Self());
712 // Assertion check to ensure effect doesn't already exist in this scrollview
713 bool effectAlreadyExistsInScrollView(false);
714 for (ScrollViewEffectIter iter = mEffects.begin(); iter != mEffects.end(); ++iter)
718 effectAlreadyExistsInScrollView = true;
723 DALI_ASSERT_ALWAYS(!effectAlreadyExistsInScrollView);
725 // add effect to effects list
726 mEffects.push_back(effect);
728 // invoke Attachment request to ScrollView first
729 GetImpl(effect).Attach(self);
732 void ScrollView::RemoveEffect(Toolkit::ScrollViewEffect effect)
734 Dali::Toolkit::ScrollView self = Dali::Toolkit::ScrollView::DownCast(Self());
736 // remove effect from effects list
737 bool effectExistedInScrollView(false);
738 for (ScrollViewEffectIter iter = mEffects.begin(); iter != mEffects.end(); ++iter)
742 mEffects.erase(iter);
743 effectExistedInScrollView = true;
748 // Assertion check to ensure effect existed.
749 DALI_ASSERT_ALWAYS(effectExistedInScrollView);
751 // invoke Detachment request to ScrollView last
752 GetImpl(effect).Detach(self);
755 void ScrollView::RemoveAllEffects()
757 Dali::Toolkit::ScrollView self = Dali::Toolkit::ScrollView::DownCast(Self());
759 for (ScrollViewEffectIter effectIter = mEffects.begin(); effectIter != mEffects.end(); ++effectIter)
761 Toolkit::ScrollViewEffect effect = *effectIter;
763 // invoke Detachment request to ScrollView last
764 GetImpl(effect).Detach(self);
770 void ScrollView::ApplyConstraintToChildren(Constraint constraint)
772 ApplyConstraintToBoundActors(constraint);
775 void ScrollView::RemoveConstraintsFromChildren()
777 RemoveConstraintsFromBoundActors();
780 const RulerPtr ScrollView::GetRulerX() const
785 const RulerPtr ScrollView::GetRulerY() const
790 void ScrollView::SetRulerX(RulerPtr ruler)
794 Vector3 size = GetControlSize();
795 UpdatePropertyDomain(size);
796 UpdateMainInternalConstraint();
799 void ScrollView::SetRulerY(RulerPtr ruler)
803 Vector3 size = GetControlSize();
804 UpdatePropertyDomain(size);
805 UpdateMainInternalConstraint();
808 void ScrollView::UpdatePropertyDomain(const Vector3& size)
811 Vector3 min = mMinScroll;
812 Vector3 max = mMaxScroll;
813 bool scrollPositionChanged = false;
814 bool domainChanged = false;
816 bool canScrollVertical = false;
817 bool canScrollHorizontal = false;
818 UpdateLocalScrollProperties();
819 if(mRulerX->IsEnabled())
821 const Toolkit::RulerDomain& rulerDomain = mRulerX->GetDomain();
822 if( fabsf(min.x - rulerDomain.min) > Math::MACHINE_EPSILON_100
823 || fabsf(max.x - rulerDomain.max) > Math::MACHINE_EPSILON_100 )
825 domainChanged = true;
826 min.x = rulerDomain.min;
827 max.x = rulerDomain.max;
829 // make sure new scroll value is within new domain
830 if( mScrollPrePosition.x < min.x
831 || mScrollPrePosition.x > max.x )
833 scrollPositionChanged = true;
834 mScrollPrePosition.x = Clamp(mScrollPrePosition.x, -(max.x - size.x), -min.x);
837 if( (fabsf(rulerDomain.max - rulerDomain.min) - size.x) > Math::MACHINE_EPSILON_100 )
839 canScrollHorizontal = true;
842 else if( fabs(min.x) > Math::MACHINE_EPSILON_100
843 || fabs(max.x) > Math::MACHINE_EPSILON_100 )
845 // need to reset to 0
846 domainChanged = true;
849 canScrollHorizontal = false;
852 if(mRulerY->IsEnabled())
854 const Toolkit::RulerDomain& rulerDomain = mRulerY->GetDomain();
855 if( fabsf(min.y - rulerDomain.min) > Math::MACHINE_EPSILON_100
856 || fabsf(max.y - rulerDomain.max) > Math::MACHINE_EPSILON_100 )
858 domainChanged = true;
859 min.y = rulerDomain.min;
860 max.y = rulerDomain.max;
862 // make sure new scroll value is within new domain
863 if( mScrollPrePosition.y < min.y
864 || mScrollPrePosition.y > max.y )
866 scrollPositionChanged = true;
867 mScrollPrePosition.y = Clamp(mScrollPrePosition.y, -(max.y - size.y), -min.y);
870 if( (fabsf(rulerDomain.max - rulerDomain.min) - size.y) > Math::MACHINE_EPSILON_100 )
872 canScrollVertical = true;
875 else if( fabs(min.y) > Math::MACHINE_EPSILON_100
876 || fabs(max.y) > Math::MACHINE_EPSILON_100 )
878 // need to reset to 0
879 domainChanged = true;
882 canScrollVertical = false;
885 // avoid setting properties if possible, otherwise this will cause an entire update as well as triggering constraints using each property we update
886 if( mCanScrollVertical != canScrollVertical )
888 mCanScrollVertical = canScrollVertical;
889 self.SetProperty(mPropertyCanScrollVertical, canScrollVertical);
891 if( mCanScrollHorizontal != canScrollHorizontal )
893 mCanScrollHorizontal = canScrollHorizontal;
894 self.SetProperty(mPropertyCanScrollHorizontal, canScrollHorizontal);
896 if( scrollPositionChanged )
898 DALI_LOG_SCROLL_STATE("[0x%X] Domain Changed, setting mPropertyPrePosition To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y );
899 self.SetProperty(mPropertyPrePosition, mScrollPrePosition);
905 self.SetProperty(mPropertyPositionMin, mMinScroll );
906 self.SetProperty(mPropertyPositionMax, mMaxScroll );
910 void ScrollView::SetScrollSensitive(bool sensitive)
913 PanGestureDetector panGesture( GetPanGestureDetector() );
915 DALI_LOG_SCROLL_STATE("[0x%X] sensitive: before:[%d] setting[%d]", this, int(mSensitive), int(sensitive));
917 if((!mSensitive) && (sensitive))
919 mSensitive = sensitive;
920 panGesture.Attach(self);
922 else if((mSensitive) && (!sensitive))
924 DALI_LOG_SCROLL_STATE("[0x%X] BEFORE: panning:[%d]", this, int(mPanning));
926 // while the scroll view is panning, the state needs to be reset.
929 PanGesture cancelGesture( Gesture::Cancelled );
930 OnPan( cancelGesture );
933 panGesture.Detach(self);
934 mSensitive = sensitive;
936 mGestureStackDepth = 0;
937 DALI_LOG_SCROLL_STATE("[0x%X] AFTER: panning:[%d]", this, int(mPanning));
941 void ScrollView::SetMaxOvershoot(float overshootX, float overshootY)
943 mMaxOvershoot.x = overshootX;
944 mMaxOvershoot.y = overshootY;
945 mUserMaxOvershoot = mMaxOvershoot;
946 mDefaultMaxOvershoot = false;
947 UpdateMainInternalConstraint();
950 void ScrollView::SetSnapOvershootAlphaFunction(AlphaFunction alpha)
952 mSnapOvershootAlphaFunction = alpha;
955 void ScrollView::SetSnapOvershootDuration(float duration)
957 mSnapOvershootDuration = duration;
960 void ScrollView::SetTouchesRequiredForPanning(unsigned int minTouches, unsigned int maxTouches, bool endOutside)
962 PanGestureDetector panGesture( GetPanGestureDetector() );
964 mMinTouchesForPanning = minTouches;
965 mMaxTouchesForPanning = maxTouches;
969 panGesture.SetMinimumTouchesRequired(minTouches);
970 panGesture.SetMaximumTouchesRequired(maxTouches);
974 panGesture.SetMinimumTouchesRequired(1);
975 panGesture.SetMaximumTouchesRequired(UINT_MAX);
979 void ScrollView::SetActorAutoSnap(bool enable)
981 mActorAutoSnapEnabled = enable;
984 void ScrollView::SetAutoResize(bool enable)
986 mAutoResizeContainerEnabled = enable;
987 // TODO: This needs a lot of issues to be addressed before working.
990 bool ScrollView::GetWrapMode() const
995 void ScrollView::SetWrapMode(bool enable)
998 Self().SetProperty(mPropertyWrap, enable);
1001 int ScrollView::GetScrollUpdateDistance() const
1003 return mScrollUpdateDistance;
1006 void ScrollView::SetScrollUpdateDistance(int distance)
1008 mScrollUpdateDistance = distance;
1011 bool ScrollView::GetAxisAutoLock() const
1013 return mAxisAutoLock;
1016 void ScrollView::SetAxisAutoLock(bool enable)
1018 mAxisAutoLock = enable;
1019 UpdateMainInternalConstraint();
1022 float ScrollView::GetAxisAutoLockGradient() const
1024 return mAxisAutoLockGradient;
1027 void ScrollView::SetAxisAutoLockGradient(float gradient)
1029 DALI_ASSERT_DEBUG( gradient >= 0.0f && gradient <= 1.0f );
1030 mAxisAutoLockGradient = gradient;
1031 UpdateMainInternalConstraint();
1034 float ScrollView::GetFrictionCoefficient() const
1036 return mFrictionCoefficient;
1039 void ScrollView::SetFrictionCoefficient(float friction)
1041 DALI_ASSERT_DEBUG( friction > 0.0f );
1042 mFrictionCoefficient = friction;
1045 float ScrollView::GetFlickSpeedCoefficient() const
1047 return mFlickSpeedCoefficient;
1050 void ScrollView::SetFlickSpeedCoefficient(float speed)
1052 mFlickSpeedCoefficient = speed;
1055 Vector2 ScrollView::GetMinimumDistanceForFlick() const
1057 return mMinFlickDistance;
1060 void ScrollView::SetMinimumDistanceForFlick( const Vector2& distance )
1062 mMinFlickDistance = distance;
1065 float ScrollView::GetMinimumSpeedForFlick() const
1067 return mFlickSpeedThreshold;
1070 void ScrollView::SetMinimumSpeedForFlick( float speed )
1072 mFlickSpeedThreshold = speed;
1075 float ScrollView::GetMaxFlickSpeed() const
1077 return mMaxFlickSpeed;
1080 void ScrollView::SetMaxFlickSpeed(float speed)
1082 mMaxFlickSpeed = speed;
1085 void ScrollView::SetMouseWheelScrollDistanceStep(Vector2 step)
1087 mMouseWheelScrollDistanceStep = step;
1090 Vector2 ScrollView::GetMouseWheelScrollDistanceStep() const
1092 return mMouseWheelScrollDistanceStep;
1095 unsigned int ScrollView::GetCurrentPage() const
1097 // in case animation is currently taking place.
1098 Vector3 position = GetPropertyPosition();
1100 Actor self = Self();
1101 unsigned int page = 0;
1102 unsigned int pagesPerVolume = 1;
1103 unsigned int volume = 0;
1105 // if rulerX is enabled, then get page count (columns)
1106 page = mRulerX->GetPageFromPosition(-position.x, mWrapMode);
1107 volume = mRulerY->GetPageFromPosition(-position.y, mWrapMode);
1108 pagesPerVolume = mRulerX->GetTotalPages();
1110 return volume * pagesPerVolume + page;
1113 Vector3 ScrollView::GetCurrentScrollPosition() const
1115 return -GetPropertyPosition();
1118 void ScrollView::SetScrollPosition(const Vector3& position)
1120 mScrollPrePosition = position;
1123 Vector3 ScrollView::GetDomainSize() const
1125 Vector3 size = Self().GetCurrentSize();
1127 const RulerDomain& xDomain = GetRulerX()->GetDomain();
1128 const RulerDomain& yDomain = GetRulerY()->GetDomain();
1130 Vector3 domainSize = Vector3( xDomain.max - xDomain.min, yDomain.max - yDomain.min, 0.0f ) - size;
1134 void ScrollView::TransformTo(const Vector3& position,
1135 DirectionBias horizontalBias, DirectionBias verticalBias)
1137 TransformTo(position, mSnapDuration, mSnapAlphaFunction, horizontalBias, verticalBias);
1140 void ScrollView::TransformTo(const Vector3& position, float duration, AlphaFunction alpha,
1141 DirectionBias horizontalBias, DirectionBias verticalBias)
1143 Actor self( Self() );
1145 // Guard against destruction during signal emission
1146 // Note that Emit() methods are called indirectly e.g. from within ScrollView::AnimateTo()
1147 Toolkit::ScrollView handle( GetOwner() );
1149 DALI_LOG_SCROLL_STATE("[0x%X] pos[%.2f,%.2f], duration[%.2f] bias[%d, %d]",
1150 this, position.x, position.y, duration, int(horizontalBias), int(verticalBias));
1152 Vector3 currentScrollPosition = GetCurrentScrollPosition();
1153 self.SetProperty( mPropertyScrollStartPagePosition, currentScrollPosition );
1155 if( mScrolling ) // are we interrupting a current scroll?
1157 // set mScrolling to false, in case user has code that interrogates mScrolling Getter() in complete.
1159 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignalV2 1 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
1160 mScrollCompletedSignalV2.Emit( currentScrollPosition );
1163 if( mPanning ) // are we interrupting a current pan?
1165 DALI_LOG_SCROLL_STATE("[0x%X] Interrupting Pan, set to false", this );
1167 mGestureStackDepth = 0;
1168 self.SetProperty( mPropertyPanning, false );
1170 if( mScrollMainInternalPrePositionConstraint )
1172 self.RemoveConstraint(mScrollMainInternalPrePositionConstraint);
1176 self.SetProperty(mPropertyScrolling, true);
1179 DALI_LOG_SCROLL_STATE("[0x%X] mScrollStartedSignalV2 1 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
1180 mScrollStartedSignalV2.Emit( currentScrollPosition );
1181 bool animating = AnimateTo(-position,
1182 Vector3::ONE * duration,
1191 // if not animating, then this pan has completed right now.
1192 self.SetProperty(mPropertyScrolling, false);
1195 // If we have no duration, then in the next update frame, we will be at the position specified as we just set.
1196 // In this scenario, we cannot return the currentScrollPosition as this is out-of-date and should instead return the requested final position
1197 Vector3 completedPosition( currentScrollPosition );
1198 if( duration <= Math::MACHINE_EPSILON_10 )
1200 completedPosition = position;
1203 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignalV2 2 [%.2f, %.2f]", this, completedPosition.x, completedPosition.y);
1204 SetScrollUpdateNotification(false);
1205 mScrollCompletedSignalV2.Emit( completedPosition );
1209 void ScrollView::ScrollTo(const Vector3& position)
1211 ScrollTo(position, mSnapDuration );
1214 void ScrollView::ScrollTo(const Vector3& position, float duration)
1216 ScrollTo(position, duration, DirectionBiasNone, DirectionBiasNone);
1219 void ScrollView::ScrollTo(const Vector3& position, float duration, AlphaFunction alpha)
1221 ScrollTo(position, duration, alpha, DirectionBiasNone, DirectionBiasNone);
1224 void ScrollView::ScrollTo(const Vector3& position, float duration,
1225 DirectionBias horizontalBias, DirectionBias verticalBias)
1227 ScrollTo(position, duration, mSnapAlphaFunction, horizontalBias, verticalBias);
1230 void ScrollView::ScrollTo(const Vector3& position, float duration, AlphaFunction alpha,
1231 DirectionBias horizontalBias, DirectionBias verticalBias)
1233 DALI_LOG_SCROLL_STATE("[0x%X] position[%.2f, %.2f] duration[%.2f]", this, position.x, position.y, duration, int(horizontalBias), int(verticalBias));
1234 TransformTo(position, duration, alpha, horizontalBias, verticalBias);
1237 void ScrollView::ScrollTo(unsigned int page)
1239 ScrollTo(page, mSnapDuration);
1242 void ScrollView::ScrollTo(unsigned int page, float duration, DirectionBias bias)
1245 unsigned int volume;
1246 unsigned int libraries;
1248 // The position to scroll to is continuous and linear
1249 // unless a domain has been enabled on the X axis.
1250 // or if WrapMode has been enabled.
1251 bool carryX = mRulerX->GetDomain().enabled | mWrapMode;
1252 bool carryY = mRulerY->GetDomain().enabled | mWrapMode;
1254 position.x = mRulerX->GetPositionFromPage(page, volume, carryX);
1255 position.y = mRulerY->GetPositionFromPage(volume, libraries, carryY);
1257 ScrollTo(position, duration, bias, bias);
1260 void ScrollView::ScrollTo(Actor &actor)
1262 ScrollTo(actor, mSnapDuration);
1265 void ScrollView::ScrollTo(Actor &actor, float duration)
1267 DALI_ASSERT_ALWAYS(actor.GetParent() == Self());
1269 Actor self = Self();
1270 Vector3 size = self.GetCurrentSize();
1271 Vector3 position = actor.GetCurrentPosition();
1272 position -= GetPropertyPrePosition();
1274 ScrollTo(Vector3(position.x - size.width * 0.5f, position.y - size.height * 0.5f, 0.0f), duration);
1277 Actor ScrollView::FindClosestActor()
1279 Actor self = Self();
1280 Vector3 size = self.GetCurrentSize();
1282 return FindClosestActorToPosition(Vector3(size.width * 0.5f,size.height * 0.5f,0.0f));
1285 Actor ScrollView::FindClosestActorToPosition(const Vector3& position, FindDirection dirX, FindDirection dirY, FindDirection dirZ)
1288 float closestDistance2 = 0.0f;
1289 Vector3 actualPosition = position;
1291 unsigned int numChildren = Self().GetChildCount();
1293 for(unsigned int i = 0; i < numChildren; ++i)
1295 Actor child = Self().GetChildAt(i);
1297 if(mInternalActor == child) // ignore internal actor.
1302 Vector3 childPosition = GetPositionOfAnchor(child, AnchorPoint::CENTER);
1304 Vector3 delta = childPosition - actualPosition;
1306 // X-axis checking (only find Actors to the [dirX] of actualPosition)
1307 if(dirX > All) // != All,None
1309 FindDirection deltaH = delta.x > 0 ? Right : Left;
1316 // Y-axis checking (only find Actors to the [dirY] of actualPosition)
1317 if(dirY > All) // != All,None
1319 FindDirection deltaV = delta.y > 0 ? Down : Up;
1326 // Z-axis checking (only find Actors to the [dirZ] of actualPosition)
1327 if(dirZ > All) // != All,None
1329 FindDirection deltaV = delta.y > 0 ? In : Out;
1336 // compare child to closest child in terms of distance.
1337 float distance2 = 0.0f;
1339 // distance2 = the Square of the relevant dimensions of delta
1342 distance2 += delta.x * delta.x;
1347 distance2 += delta.y * delta.y;
1352 distance2 += delta.z * delta.z;
1355 if(closestChild) // Next time.
1357 if(distance2 < closestDistance2)
1359 closestChild = child;
1360 closestDistance2 = distance2;
1365 closestChild = child;
1366 closestDistance2 = distance2;
1370 return closestChild;
1373 bool ScrollView::ScrollToSnapPoint()
1375 DALI_LOG_SCROLL_STATE("[0x%X]", this );
1376 Vector2 stationaryVelocity = Vector2(0.0f, 0.0f);
1377 return SnapWithVelocity( stationaryVelocity );
1380 // TODO: In situations where axes are different (X snap, Y free)
1381 // Each axis should really have their own independent animation (time and equation)
1382 // Consider, X axis snapping to nearest grid point (EaseOut over fixed time)
1383 // Consider, Y axis simulating physics to arrive at a point (Physics equation over variable time)
1384 // Currently, the axes have been split however, they both use the same EaseOut equation.
1385 bool ScrollView::SnapWithVelocity(Vector2 velocity)
1387 // Animator takes over now, touches are assumed not to interfere.
1388 // And if touches do interfere, then we'll stop animation, update PrePosition
1389 // to current mScroll's properties, and then resume.
1390 // Note: For Flicking this may work a bit different...
1392 float angle = atan2(velocity.y, velocity.x);
1393 float speed2 = velocity.LengthSquared();
1394 AlphaFunction alphaFunction = mSnapAlphaFunction;
1395 Vector3 positionDuration = Vector3::ONE * mSnapDuration;
1398 FindDirection horizontal = None;
1399 FindDirection vertical = None;
1401 // orthoAngleRange = Angle tolerance within the Exact N,E,S,W direction
1402 // that will be accepted as a general N,E,S,W flick direction.
1404 const float orthoAngleRange = FLICK_ORTHO_ANGLE_RANGE * M_PI / 180.0f;
1405 const float flickSpeedThreshold2 = mFlickSpeedThreshold * mFlickSpeedThreshold;
1407 Vector3 positionSnap = mScrollPrePosition;
1409 // Flick logic X Axis
1411 if(mRulerX->IsEnabled() && mLockAxis != LockHorizontal)
1415 if( speed2 > flickSpeedThreshold2 || // exceeds flick threshold
1416 mInAccessibilityPan ) // With AccessibilityPan its easier to move between snap positions
1418 if((angle >= -orthoAngleRange) && (angle < orthoAngleRange)) // Swiping East
1420 biasX = 0.0f, horizontal = Left;
1422 // This guards against an error where no movement occurs, due to the flick finishing
1423 // before the update-thread has advanced mScrollPostPosition past the the previous snap point.
1424 positionSnap.x += 1.0f;
1426 else if((angle >= M_PI-orthoAngleRange) || (angle < -M_PI+orthoAngleRange)) // Swiping West
1428 biasX = 1.0f, horizontal = Right;
1430 // This guards against an error where no movement occurs, due to the flick finishing
1431 // before the update-thread has advanced mScrollPostPosition past the the previous snap point.
1432 positionSnap.x -= 1.0f;
1437 // Flick logic Y Axis
1439 if(mRulerY->IsEnabled() && mLockAxis != LockVertical)
1443 if( speed2 > flickSpeedThreshold2 || // exceeds flick threshold
1444 mInAccessibilityPan ) // With AccessibilityPan its easier to move between snap positions
1446 if((angle >= M_PI_2-orthoAngleRange) && (angle < M_PI_2+orthoAngleRange)) // Swiping South
1448 biasY = 0.0f, vertical = Up;
1450 else if((angle >= -M_PI_2-orthoAngleRange) && (angle < -M_PI_2+orthoAngleRange)) // Swiping North
1452 biasY = 1.0f, vertical = Down;
1457 // isFlick: Whether this gesture is a flick or not.
1458 bool isFlick = (horizontal != All || vertical != All);
1459 // isFreeFlick: Whether this gesture is a flick under free panning criteria.
1460 bool isFreeFlick = velocity.LengthSquared() > (FREE_FLICK_SPEED_THRESHOLD*FREE_FLICK_SPEED_THRESHOLD);
1462 if(isFlick || isFreeFlick)
1464 positionDuration = Vector3::ONE * mFlickDuration;
1465 alphaFunction = mFlickAlphaFunction;
1468 // Calculate next positionSnap ////////////////////////////////////////////////////////////
1470 if(mActorAutoSnapEnabled)
1472 Vector3 size = Self().GetCurrentSize();
1474 Actor child = FindClosestActorToPosition( Vector3(size.width * 0.5f,size.height * 0.5f,0.0f), horizontal, vertical );
1476 if(!child && isFlick )
1478 // If we conducted a direction limited search and found no actor, then just snap to the closest actor.
1479 child = FindClosestActorToPosition( Vector3(size.width * 0.5f,size.height * 0.5f,0.0f) );
1484 Vector3 position = Self().GetProperty<Vector3>(mPropertyPosition);
1486 // Get center-point of the Actor.
1487 Vector3 childPosition = GetPositionOfAnchor(child, AnchorPoint::CENTER);
1489 if(mRulerX->IsEnabled())
1491 positionSnap.x = position.x - childPosition.x + size.width * 0.5f;
1493 if(mRulerY->IsEnabled())
1495 positionSnap.y = position.y - childPosition.y + size.height * 0.5f;
1500 Vector3 startPosition = positionSnap;
1501 positionSnap.x = -mRulerX->Snap(-positionSnap.x, biasX); // NOTE: X & Y rulers think in -ve coordinate system.
1502 positionSnap.y = -mRulerY->Snap(-positionSnap.y, biasY); // That is scrolling RIGHT (e.g. 100.0, 0.0) means moving LEFT.
1504 Vector3 clampDelta(Vector3::ZERO);
1505 ClampPosition(positionSnap);
1507 if( (mRulerX->GetType() == Ruler::Free || mRulerY->GetType() == Ruler::Free)
1508 && isFreeFlick && !mActorAutoSnapEnabled)
1510 // Calculate target position based on velocity of flick.
1512 // a = Deceleration (Set to diagonal stage length * friction coefficient)
1513 // u = Initial Velocity (Flick velocity)
1514 // v = 0 (Final Velocity)
1515 // t = Time (Velocity / Deceleration)
1516 Vector2 stageSize = Stage::GetCurrent().GetSize();
1517 float stageLength = Vector3(stageSize.x, stageSize.y, 0.0f).Length();
1518 float a = (stageLength * mFrictionCoefficient);
1519 Vector3 u = Vector3(velocity.x, velocity.y, 0.0f) * mFlickSpeedCoefficient;
1520 float speed = u.Length();
1523 // TODO: Change this to a decay function. (faster you flick, the slower it should be)
1524 speed = std::min(speed, stageLength * mMaxFlickSpeed );
1526 alphaFunction = ConstantDecelerationAlphaFunction;
1528 float t = speed / a;
1530 if(mRulerX->IsEnabled() && mRulerX->GetType() == Ruler::Free)
1532 positionSnap.x += t*u.x*0.5f;
1535 if(mRulerY->IsEnabled() && mRulerY->GetType() == Ruler::Free)
1537 positionSnap.y += t*u.y*0.5f;
1540 clampDelta = positionSnap;
1541 ClampPosition(positionSnap);
1542 if((positionSnap - startPosition).LengthSquared() > Math::MACHINE_EPSILON_0)
1544 clampDelta -= positionSnap;
1545 clampDelta.x = clampDelta.x > 0.0f ? std::min(clampDelta.x, mMaxOvershoot.x) : std::max(clampDelta.x, -mMaxOvershoot.x);
1546 clampDelta.y = clampDelta.y > 0.0f ? std::min(clampDelta.y, mMaxOvershoot.y) : std::max(clampDelta.y, -mMaxOvershoot.y);
1550 clampDelta = Vector3::ZERO;
1553 // If Axis is Free and has velocity, then calculate time taken
1554 // to reach target based on velocity in axis.
1555 if(mRulerX->IsEnabled() && mRulerX->GetType() == Ruler::Free)
1557 float deltaX = fabsf(startPosition.x - positionSnap.x);
1559 if(fabsf(u.x) > Math::MACHINE_EPSILON_1)
1561 positionDuration.x = fabsf(deltaX / u.x);
1565 positionDuration.x = 0;
1569 if(mRulerY->IsEnabled() && mRulerY->GetType() == Ruler::Free)
1571 float deltaY = fabsf(startPosition.y - positionSnap.y);
1573 if(fabsf(u.y) > Math::MACHINE_EPSILON_1)
1575 positionDuration.y = fabsf(deltaY / u.y);
1579 positionDuration.y = 0;
1583 positionSnap += clampDelta;
1585 bool animating = AnimateTo(positionSnap, positionDuration,
1586 alphaFunction, false,
1587 DirectionBiasNone, DirectionBiasNone,
1588 isFlick || isFreeFlick ? Flick : Snap);
1593 void ScrollView::StopAnimation(void)
1595 // Clear Snap animation if exists.
1596 StopAnimation(mInternalXAnimation);
1597 StopAnimation(mInternalYAnimation);
1598 mScrollStateFlags = 0;
1599 // remove scroll animation flags
1600 HandleStoppedAnimation();
1603 void ScrollView::StopAnimation(Animation& animation)
1612 bool ScrollView::AnimateTo(const Vector3& position, const Vector3& positionDuration,
1613 AlphaFunction alpha, bool findShortcuts,
1614 DirectionBias horizontalBias, DirectionBias verticalBias,
1617 // Here we perform an animation on a number of properties (depending on which have changed)
1618 // The animation is applied to all ScrollBases
1619 Actor self = Self();
1620 mScrollTargetPosition = position;
1621 float totalDuration = 0.0f;
1623 bool positionChanged = (mScrollTargetPosition != mScrollPostPosition);
1627 totalDuration = std::max(totalDuration, positionDuration.x);
1628 totalDuration = std::max(totalDuration, positionDuration.y);
1632 // try to animate for a frame, on some occasions update will be changing scroll value while event side thinks it hasnt changed
1633 totalDuration = 0.01f;
1634 positionChanged = true;
1639 // Position Delta ///////////////////////////////////////////////////////
1642 if(mWrapMode && findShortcuts)
1644 // In Wrap Mode, the shortest distance is a little less intuitive...
1645 const RulerDomain rulerDomainX = mRulerX->GetDomain();
1646 const RulerDomain rulerDomainY = mRulerY->GetDomain();
1648 if(mRulerX->IsEnabled())
1650 float dir = VectorInDomain(-mScrollPrePosition.x, -mScrollTargetPosition.x, rulerDomainX.min, rulerDomainX.max, horizontalBias);
1651 mScrollTargetPosition.x = mScrollPrePosition.x + -dir;
1654 if(mRulerY->IsEnabled())
1656 float dir = VectorInDomain(-mScrollPrePosition.y, -mScrollTargetPosition.y, rulerDomainY.min, rulerDomainY.max, verticalBias);
1657 mScrollTargetPosition.y = mScrollPrePosition.y + -dir;
1661 // note we have two separate animations for X & Y, this deals with sliding diagonally and hitting
1662 // a horizonal/vertical wall.delay
1663 AnimateInternalXTo(mScrollTargetPosition.x, positionDuration.x, alpha);
1664 AnimateInternalYTo(mScrollTargetPosition.y, positionDuration.y, alpha);
1666 if( !(mScrollStateFlags & SCROLL_ANIMATION_FLAGS) )
1668 DALI_LOG_SCROLL_STATE("[0x%X] Setting mPropertyPrePosition To[%.2f, %.2f]", this, mScrollTargetPosition.x, mScrollTargetPosition.y );
1669 self.SetProperty(mPropertyPrePosition, mScrollTargetPosition);
1670 mScrollPrePosition = mScrollTargetPosition;
1671 mScrollPostPosition = mScrollTargetPosition;
1672 WrapPosition(mScrollPostPosition);
1675 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 );
1676 DALI_LOG_SCROLL_STATE("[0x%X] mPropertyPrePosition[%.2f, %.2f], mPropertyPosition[%.2f, %.2f]", this, self.GetProperty( mPropertyPrePosition ).Get<Vector3>().x, self.GetProperty( mPropertyPrePosition ).Get<Vector3>().y, self.GetProperty( mPropertyPosition ).Get<Vector3>().x, self.GetProperty( mPropertyPosition ).Get<Vector3>().y );
1679 SetScrollUpdateNotification(true);
1681 // Always send a snap event when AnimateTo is called.
1682 Toolkit::ScrollView::SnapEvent snapEvent;
1683 snapEvent.type = snapType;
1684 snapEvent.position = -mScrollTargetPosition;
1685 snapEvent.duration = totalDuration;
1687 DALI_LOG_SCROLL_STATE("[0x%X] mSnapStartedSignalV2 [%.2f, %.2f]", this, snapEvent.position.x, snapEvent.position.y);
1688 mSnapStartedSignalV2.Emit( snapEvent );
1690 return (mScrollStateFlags & SCROLL_ANIMATION_FLAGS) != 0;
1693 void ScrollView::SetOvershootEnabled(bool enabled)
1695 if(enabled && !mOvershootIndicator)
1697 mOvershootIndicator = ScrollOvershootIndicator::New();
1701 mMaxOvershoot = OVERSCROLL_CLAMP;
1702 mOvershootIndicator->AttachToScrollable(*this);
1706 mMaxOvershoot = mUserMaxOvershoot;
1707 mOvershootIndicator->DetachFromScrollable(*this);
1709 UpdateMainInternalConstraint();
1712 void ScrollView::AddOverlay(Actor actor)
1714 mInternalActor.Add( actor );
1717 void ScrollView::RemoveOverlay(Actor actor)
1719 mInternalActor.Remove( actor );
1722 void ScrollView::SetOvershootEffectColor( const Vector4& color )
1724 mOvershootEffectColor = color;
1725 if( mOvershootIndicator )
1727 mOvershootIndicator->SetOvershootEffectColor( color );
1731 void ScrollView::SetScrollingDirection( Radian direction, Radian threshold )
1733 PanGestureDetector panGesture( GetPanGestureDetector() );
1735 // First remove just in case we have some set, then add.
1736 panGesture.RemoveDirection( direction );
1737 panGesture.AddDirection( direction, threshold );
1740 void ScrollView::RemoveScrollingDirection( Radian direction )
1742 PanGestureDetector panGesture( GetPanGestureDetector() );
1743 panGesture.RemoveDirection( direction );
1746 Toolkit::ScrollView::SnapStartedSignalV2& ScrollView::SnapStartedSignal()
1748 return mSnapStartedSignalV2;
1751 void ScrollView::FindAndUnbindActor(Actor child)
1756 Vector3 ScrollView::GetPropertyPrePosition() const
1758 Vector3 position = Self().GetProperty<Vector3>(mPropertyPrePosition);
1759 WrapPosition(position);
1763 Vector3 ScrollView::GetPropertyPosition() const
1765 Vector3 position = Self().GetProperty<Vector3>(mPropertyPosition);
1766 WrapPosition(position);
1771 void ScrollView::HandleStoppedAnimation()
1773 SetScrollUpdateNotification(false);
1776 void ScrollView::HandleSnapAnimationFinished()
1778 // Emit Signal that scrolling has completed.
1780 Actor self = Self();
1781 self.SetProperty(mPropertyScrolling, false);
1783 Vector3 deltaPosition(mScrollPrePosition);
1785 UpdateLocalScrollProperties();
1786 WrapPosition(mScrollPrePosition);
1787 DALI_LOG_SCROLL_STATE("[0x%X] Setting mPropertyPrePosition To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y );
1788 self.SetProperty(mPropertyPrePosition, mScrollPrePosition);
1790 Vector3 currentScrollPosition = GetCurrentScrollPosition();
1791 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignalV2 3 current[%.2f, %.2f], mScrollTargetPosition[%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y, -mScrollTargetPosition.x, -mScrollTargetPosition.y );
1792 mScrollCompletedSignalV2.Emit( currentScrollPosition );
1794 mDomainOffset += deltaPosition - mScrollPostPosition;
1795 self.SetProperty(mPropertyDomainOffset, mDomainOffset);
1796 HandleStoppedAnimation();
1799 void ScrollView::SetScrollUpdateNotification( bool enabled )
1801 Actor self = Self();
1802 if( mScrollXUpdateNotification )
1804 // disconnect now to avoid a notification before removed from update thread
1805 mScrollXUpdateNotification.NotifySignal().Disconnect(this, &ScrollView::OnScrollUpdateNotification);
1806 self.RemovePropertyNotification(mScrollXUpdateNotification);
1807 mScrollXUpdateNotification.Reset();
1811 mScrollXUpdateNotification = self.AddPropertyNotification(mPropertyPosition, 0, StepCondition(mScrollUpdateDistance, 0.0f));
1812 mScrollXUpdateNotification.NotifySignal().Connect( this, &ScrollView::OnScrollUpdateNotification );
1814 if( mScrollYUpdateNotification )
1816 // disconnect now to avoid a notification before removed from update thread
1817 mScrollYUpdateNotification.NotifySignal().Disconnect(this, &ScrollView::OnScrollUpdateNotification);
1818 self.RemovePropertyNotification(mScrollYUpdateNotification);
1819 mScrollYUpdateNotification.Reset();
1823 mScrollYUpdateNotification = self.AddPropertyNotification(mPropertyPosition, 1, StepCondition(mScrollUpdateDistance, 0.0f));
1824 mScrollYUpdateNotification.NotifySignal().Connect( this, &ScrollView::OnScrollUpdateNotification );
1828 void ScrollView::OnScrollUpdateNotification(Dali::PropertyNotification& source)
1830 // Guard against destruction during signal emission
1831 Toolkit::ScrollView handle( GetOwner() );
1833 Vector3 currentScrollPosition = GetCurrentScrollPosition();
1834 mScrollUpdatedSignalV2.Emit( currentScrollPosition );
1837 bool ScrollView::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
1839 Dali::BaseHandle handle( object );
1841 bool connected( true );
1842 Toolkit::ScrollView view = Toolkit::ScrollView::DownCast( handle );
1844 if( Toolkit::ScrollView::SIGNAL_SNAP_STARTED == signalName )
1846 view.SnapStartedSignal().Connect( tracker, functor );
1850 // signalName does not match any signal
1857 void ScrollView::OnSizeAnimation(Animation& animation, const Vector3& targetSize)
1859 // need to update domain properties for new size
1860 UpdatePropertyDomain(targetSize);
1863 void ScrollView::OnControlSizeSet( const Vector3& size )
1865 // need to update domain properties for new size
1866 if( mDefaultMaxOvershoot )
1868 mUserMaxOvershoot.x = size.x * 0.5f;
1869 mUserMaxOvershoot.y = size.y * 0.5f;
1870 if( !IsScrollComponentEnabled(Toolkit::Scrollable::OvershootIndicator) )
1872 mMaxOvershoot = mUserMaxOvershoot;
1875 UpdatePropertyDomain(size);
1876 UpdateMainInternalConstraint();
1877 if( IsScrollComponentEnabled(Toolkit::Scrollable::OvershootIndicator) )
1879 mOvershootIndicator->Reset();
1883 void ScrollView::OnChildAdd(Actor& child)
1891 void ScrollView::OnChildRemove(Actor& child)
1893 // TODO: Actor needs a RemoveConstraint method to take out an individual constraint.
1897 void ScrollView::OnPropertySet( Property::Index index, Property::Value propertyValue )
1899 Actor self = Self();
1900 if( index == mPropertyPrePosition )
1902 DALI_LOG_SCROLL_STATE("[0x%X]: mPropertyPrePosition[%.2f, %.2f]", this, propertyValue.Get<Vector3>().x, propertyValue.Get<Vector3>().y);
1903 propertyValue.Get(mScrollPrePosition);
1907 void ScrollView::StartTouchDownTimer()
1909 if ( !mTouchDownTimer )
1911 mTouchDownTimer = Timer::New( TOUCH_DOWN_TIMER_INTERVAL );
1912 mTouchDownTimer.TickSignal().Connect( this, &ScrollView::OnTouchDownTimeout );
1915 mTouchDownTimer.Start();
1918 void ScrollView::StopTouchDownTimer()
1920 if ( mTouchDownTimer )
1922 mTouchDownTimer.Stop();
1926 bool ScrollView::OnTouchDownTimeout()
1928 DALI_LOG_SCROLL_STATE("[0x%X]", this);
1930 mTouchDownTimeoutReached = true;
1932 unsigned int currentScrollStateFlags( mScrollStateFlags ); // Cleared in StopAnimation so keep local copy for comparison
1933 if( currentScrollStateFlags & (SCROLL_ANIMATION_FLAGS | SNAP_ANIMATION_FLAGS) )
1935 DALI_LOG_SCROLL_STATE("[0x%X] Scrolling Or snapping flags set, stopping animation", this);
1938 if( currentScrollStateFlags & SCROLL_ANIMATION_FLAGS )
1940 DALI_LOG_SCROLL_STATE("[0x%X] Scrolling flags set, emitting signal", this);
1942 mScrollInterrupted = true;
1943 // reset domain offset as scrolling from original plane.
1944 mDomainOffset = Vector3::ZERO;
1945 Self().SetProperty(mPropertyDomainOffset, Vector3::ZERO);
1947 UpdateLocalScrollProperties();
1948 Vector3 currentScrollPosition = GetCurrentScrollPosition();
1949 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignalV2 4 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
1950 mScrollCompletedSignalV2.Emit( currentScrollPosition );
1957 bool ScrollView::OnTouchEvent(const TouchEvent& event)
1961 DALI_LOG_SCROLL_STATE("[0x%X], Not Sensitive, ignoring", this);
1963 // Ignore this touch event, if scrollview is insensitive.
1967 // Ignore events with multiple-touch points
1968 if (event.GetPointCount() != 1)
1970 DALI_LOG_SCROLL_STATE("[0x%X], multiple touch, ignoring", this);
1975 const TouchPoint::State pointState = event.GetPoint(0).state;
1976 if( pointState == TouchPoint::Down )
1978 DALI_LOG_SCROLL_STATE("[0x%X] Down", this);
1980 if(mGestureStackDepth==0)
1982 mTouchDownTime = event.time;
1984 // This allows time for a pan-gesture to start, to avoid breaking snap-animation behavior with fast flicks.
1985 // If touch-down does not become a pan (after timeout interval), then snap-animation can be interrupted.
1986 mTouchDownTimeoutReached = false;
1987 mScrollInterrupted = false;
1988 StartTouchDownTimer();
1991 else if( ( pointState == TouchPoint::Up ) ||
1992 ( ( pointState == TouchPoint::Interrupted ) && ( event.GetPoint(0).hitActor == Self() ) ) )
1994 DALI_LOG_SCROLL_STATE("[0x%X] %s", this, ( ( pointState == TouchPoint::Up ) ? "Up" : "Interrupted" ) );
1996 StopTouchDownTimer();
1998 // if the user touches and releases without enough movement to go
1999 // into a gesture state, then we should snap to nearest point.
2000 // otherwise our scroll could be stopped (interrupted) half way through an animation.
2001 if(mGestureStackDepth==0 && mTouchDownTimeoutReached)
2003 if( ( event.GetPoint(0).state == TouchPoint::Interrupted ) ||
2004 ( ( event.time - mTouchDownTime ) >= MINIMUM_TIME_BETWEEN_DOWN_AND_UP_FOR_RESET ) )
2006 // Reset the velocity only if down was received a while ago
2007 mLastVelocity = Vector2( 0.0f, 0.0f );
2010 UpdateLocalScrollProperties();
2011 // Only finish the transform if scrolling was interrupted on down or if we are scrolling
2012 if ( mScrollInterrupted || mScrolling )
2014 DALI_LOG_SCROLL_STATE("[0x%X] Calling FinishTransform", this);
2019 mTouchDownTimeoutReached = false;
2020 mScrollInterrupted = false;
2026 bool ScrollView::OnMouseWheelEvent(const MouseWheelEvent& event)
2030 // Ignore this mouse wheel event, if scrollview is insensitive.
2034 Vector3 targetScrollPosition = GetPropertyPosition();
2036 if(mRulerX->IsEnabled() && !mRulerY->IsEnabled())
2038 // If only the ruler in the X axis is enabled, scroll in the X axis.
2039 if(mRulerX->GetType() == Ruler::Free)
2041 // Free panning mode
2042 targetScrollPosition.x += event.z * mMouseWheelScrollDistanceStep.x;
2043 ClampPosition(targetScrollPosition);
2044 ScrollTo(-targetScrollPosition);
2046 else if(!mScrolling)
2048 // Snap mode, only respond to the event when the previous snap animation is finished.
2049 ScrollTo(GetCurrentPage() - event.z);
2054 // If the ruler in the Y axis is enabled, scroll in the Y axis.
2055 if(mRulerY->GetType() == Ruler::Free)
2057 // Free panning mode
2058 targetScrollPosition.y += event.z * mMouseWheelScrollDistanceStep.y;
2059 ClampPosition(targetScrollPosition);
2060 ScrollTo(-targetScrollPosition);
2062 else if(!mScrolling)
2064 // Snap mode, only respond to the event when the previous snap animation is finished.
2065 ScrollTo(GetCurrentPage() - event.z * mRulerX->GetTotalPages());
2072 void ScrollView::ResetScrolling()
2074 Actor self = Self();
2075 self.GetProperty(mPropertyPosition).Get(mScrollPostPosition);
2076 mScrollPrePosition = mScrollPostPosition;
2077 DALI_LOG_SCROLL_STATE("[0x%X] Setting mPropertyPrePosition To[%.2f, %.2f]", this, mScrollPostPosition.x, mScrollPostPosition.y );
2078 self.SetProperty(mPropertyPrePosition, mScrollPostPosition);
2081 void ScrollView::UpdateLocalScrollProperties()
2083 Actor self = Self();
2084 self.GetProperty(mPropertyPrePosition).Get(mScrollPrePosition);
2085 self.GetProperty(mPropertyPosition).Get(mScrollPostPosition);
2088 // private functions
2090 void ScrollView::PreAnimatedScrollSetup()
2092 // mPropertyPrePosition is our unclamped property with wrapping
2093 // mPropertyPosition is our final scroll position after clamping
2095 Actor self = Self();
2097 Vector3 deltaPosition(mScrollPostPosition);
2098 WrapPosition(mScrollPostPosition);
2099 mDomainOffset += deltaPosition - mScrollPostPosition;
2100 Self().SetProperty(mPropertyDomainOffset, mDomainOffset);
2102 if( mScrollStateFlags & SCROLL_X_STATE_MASK )
2104 // already performing animation on internal x position
2105 StopAnimation(mInternalXAnimation);
2108 if( mScrollStateFlags & SCROLL_Y_STATE_MASK )
2110 // already performing animation on internal y position
2111 StopAnimation(mInternalYAnimation);
2114 mScrollStateFlags = 0;
2116 // Update Actor position with this wrapped value.
2119 void ScrollView::FinaliseAnimatedScroll()
2121 // TODO - common animation finishing code in here
2124 void ScrollView::AnimateInternalXTo( float position, float duration, AlphaFunction alpha )
2126 StopAnimation(mInternalXAnimation);
2128 if( duration > Math::MACHINE_EPSILON_10 )
2130 Actor self = Self();
2131 DALI_LOG_SCROLL_STATE("[0x%X], Animating from[%.2f] to[%.2f]", this, self.GetProperty(mPropertyPrePosition).Get<Vector3>().x, position );
2132 mInternalXAnimation = Animation::New(duration);
2133 DALI_LOG_SCROLL_STATE("[0x%X], mInternalXAnimation[0x%X]", this, mInternalXAnimation.GetObjectPtr() );
2134 mInternalXAnimation.FinishedSignal().Connect(this, &ScrollView::OnScrollAnimationFinished);
2135 mInternalXAnimation.AnimateTo( Property(self, mPropertyPrePosition, 0), position, alpha, duration);
2136 mInternalXAnimation.Play();
2138 // erase current state flags
2139 mScrollStateFlags &= ~SCROLL_X_STATE_MASK;
2140 // add internal animation state flag
2141 mScrollStateFlags |= AnimatingInternalX;
2145 void ScrollView::AnimateInternalYTo( float position, float duration, AlphaFunction alpha )
2147 StopAnimation(mInternalYAnimation);
2149 if( duration > Math::MACHINE_EPSILON_10 )
2151 Actor self = Self();
2152 DALI_LOG_SCROLL_STATE("[0x%X], Animating from[%.2f] to[%.2f]", this, self.GetProperty(mPropertyPrePosition).Get<Vector3>().y, position );
2153 mInternalYAnimation = Animation::New(duration);
2154 DALI_LOG_SCROLL_STATE("[0x%X], mInternalYAnimation[0x%X]", this, mInternalYAnimation.GetObjectPtr() );
2155 mInternalYAnimation.FinishedSignal().Connect(this, &ScrollView::OnScrollAnimationFinished);
2156 mInternalYAnimation.AnimateTo( Property(self, mPropertyPrePosition, 1), position, alpha, TimePeriod(duration));
2157 mInternalYAnimation.Play();
2159 // erase current state flags
2160 mScrollStateFlags &= ~SCROLL_Y_STATE_MASK;
2161 // add internal animation state flag
2162 mScrollStateFlags |= AnimatingInternalY;
2166 void ScrollView::OnScrollAnimationFinished( Animation& source )
2168 // Guard against destruction during signal emission
2169 // Note that ScrollCompletedSignal is emitted from HandleSnapAnimationFinished()
2170 Toolkit::ScrollView handle( GetOwner() );
2172 bool scrollingFinished = false;
2174 // update our local scroll positions
2175 UpdateLocalScrollProperties();
2177 if( source == mInternalXAnimation )
2179 DALI_LOG_SCROLL_STATE("[0x%X] mInternalXAnimation[0x%X], expected[%.2f], actual[%.2f], post[%.2f]", this, mInternalXAnimation.GetObjectPtr(), mScrollTargetPosition.x, Self().GetProperty(mPropertyPrePosition).Get<Vector3>().x, mScrollPostPosition.x );
2181 if( !(mScrollStateFlags & AnimatingInternalY) )
2183 scrollingFinished = true;
2185 mInternalXAnimation.Reset();
2186 // wrap pre scroll x position and set it
2189 const RulerDomain rulerDomain = mRulerX->GetDomain();
2190 mScrollPrePosition.x = -WrapInDomain(-mScrollPrePosition.x, rulerDomain.min, rulerDomain.max);
2191 DALI_LOG_SCROLL_STATE("[0x%X] Setting mPropertyPrePosition To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y );
2192 handle.SetProperty(mPropertyPrePosition, mScrollPrePosition);
2194 SnapInternalXTo(mScrollPostPosition.x);
2197 if( source == mInternalYAnimation )
2199 DALI_LOG_SCROLL_STATE("[0x%X] mInternalYAnimation[0x%X], expected[%.2f], actual[%.2f], post[%.2f]", this, mInternalYAnimation.GetObjectPtr(), mScrollTargetPosition.y, Self().GetProperty(mPropertyPrePosition).Get<Vector3>().y, mScrollPostPosition.y );
2201 if( !(mScrollStateFlags & AnimatingInternalX) )
2203 scrollingFinished = true;
2205 mInternalYAnimation.Reset();
2208 // wrap pre scroll y position and set it
2209 const RulerDomain rulerDomain = mRulerY->GetDomain();
2210 mScrollPrePosition.y = -WrapInDomain(-mScrollPrePosition.y, rulerDomain.min, rulerDomain.max);
2211 DALI_LOG_SCROLL_STATE("[0x%X] Setting mPropertyPrePosition To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y );
2212 handle.SetProperty(mPropertyPrePosition, mScrollPrePosition);
2214 SnapInternalYTo(mScrollPostPosition.y);
2217 DALI_LOG_SCROLL_STATE("[0x%X] scrollingFinished[%d] Animation[0x%X]", this, scrollingFinished, source.GetObjectPtr());
2219 if(scrollingFinished)
2221 HandleSnapAnimationFinished();
2225 void ScrollView::OnSnapInternalPositionFinished( Animation& source )
2227 Actor self = Self();
2228 UpdateLocalScrollProperties();
2229 if( source == mInternalXAnimation )
2231 DALI_LOG_SCROLL_STATE("[0x%X] Finished X PostPosition Animation", this );
2233 // clear internal x animation flags
2234 mScrollStateFlags &= ~SCROLL_X_STATE_MASK;
2235 mInternalXAnimation.Reset();
2236 WrapPosition(mScrollPrePosition);
2238 if( source == mInternalYAnimation )
2240 DALI_LOG_SCROLL_STATE("[0x%X] Finished Y PostPosition Animation", this );
2242 mScrollStateFlags &= ~SCROLL_Y_STATE_MASK;
2243 mInternalYAnimation.Reset();
2244 WrapPosition(mScrollPrePosition);
2248 void ScrollView::SnapInternalXTo(float position)
2250 Actor self = Self();
2252 StopAnimation(mInternalXAnimation);
2254 // erase current state flags
2255 mScrollStateFlags &= ~SCROLL_X_STATE_MASK;
2257 // if internal x not equal to inputed parameter, animate it
2258 float duration = std::min(fabsf((position - mScrollPrePosition.x) / mMaxOvershoot.x) * mSnapOvershootDuration, mSnapOvershootDuration);
2259 DALI_LOG_SCROLL_STATE("[0x%X] duration[%.2f]", this, duration );
2260 if( duration > Math::MACHINE_EPSILON_1 )
2262 DALI_LOG_SCROLL_STATE("[0x%X] Starting X Snap Animation to[%.2f]", this, position );
2264 mInternalXAnimation = Animation::New(duration);
2265 mInternalXAnimation.FinishedSignal().Connect(this, &ScrollView::OnSnapInternalPositionFinished);
2266 mInternalXAnimation.AnimateTo(Property(self, mPropertyPrePosition, 0), position);
2267 mInternalXAnimation.Play();
2269 // add internal animation state flag
2270 mScrollStateFlags |= SnappingInternalX;
2274 void ScrollView::SnapInternalYTo(float position)
2276 Actor self = Self();
2278 StopAnimation(mInternalYAnimation);
2280 // erase current state flags
2281 mScrollStateFlags &= ~SCROLL_Y_STATE_MASK;
2283 // if internal y not equal to inputed parameter, animate it
2284 float duration = std::min(fabsf((position - mScrollPrePosition.y) / mMaxOvershoot.y) * mSnapOvershootDuration, mSnapOvershootDuration);
2285 DALI_LOG_SCROLL_STATE("[0x%X] duration[%.2f]", this, duration );
2286 if( duration > Math::MACHINE_EPSILON_1 )
2288 DALI_LOG_SCROLL_STATE("[0x%X] Starting Y Snap Animation to[%.2f]", this, position );
2290 mInternalYAnimation = Animation::New(duration);
2291 mInternalYAnimation.FinishedSignal().Connect(this, &ScrollView::OnSnapInternalPositionFinished);
2292 mInternalYAnimation.AnimateTo(Property(self, mPropertyPrePosition, 1), position);
2293 mInternalYAnimation.Play();
2295 // add internal animation state flag
2296 mScrollStateFlags |= SnappingInternalY;
2300 void ScrollView::GestureStarted()
2302 // we handle the first gesture.
2303 // if we're currently doing a gesture and receive another
2304 // we continue and combine the effects of the gesture instead of reseting.
2305 if(mGestureStackDepth++==0)
2307 Actor self = Self();
2308 StopTouchDownTimer();
2310 mPanDelta = Vector3::ZERO;
2311 mLastVelocity = Vector2(0.0f, 0.0f);
2314 mLockAxis = LockPossible;
2317 if( mScrollStateFlags & SCROLL_X_STATE_MASK )
2319 StopAnimation(mInternalXAnimation);
2321 if( mScrollStateFlags & SCROLL_Y_STATE_MASK )
2323 StopAnimation(mInternalYAnimation);
2325 mScrollStateFlags = 0;
2327 if(mScrolling) // are we interrupting a current scroll?
2329 // set mScrolling to false, in case user has code that interrogates mScrolling Getter() in complete.
2331 // send negative scroll position since scroll internal scroll position works as an offset for actors,
2332 // give applications the position within the domain from the scroll view's anchor position
2333 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignalV2 5 [%.2f, %.2f]", this, -mScrollPostPosition.x, -mScrollPostPosition.y);
2334 mScrollCompletedSignalV2.Emit( -mScrollPostPosition );
2339 void ScrollView::GestureContinuing(const Vector2& panDelta)
2341 mPanDelta.x+= panDelta.x;
2342 mPanDelta.y+= panDelta.y;
2344 // Save the velocity, there is a bug in PanGesture
2345 // Whereby the Gesture::Finished's velocity is either:
2346 // NaN (due to time delta of zero between the last two events)
2347 // or 0 (due to position being the same between the last two events)
2349 // Axis Auto Lock - locks the panning to the horizontal or vertical axis if the pan
2350 // appears mostly horizontal or mostly vertical respectively.
2353 mLockAxis = GetLockAxis(mPanDelta.GetVectorXY(), mLockAxis, mAxisAutoLockGradient);
2354 } // end if mAxisAutoLock
2357 // TODO: Upgrade to use a more powerful gesture detector (one that supports multiple touches on pan - so works as pan and flick gesture)
2358 // BUG: Gesture::Finished doesn't always return velocity on release (due to
2359 // timeDelta between last two events being 0 sometimes, or posiiton being the same)
2360 void ScrollView::OnPan( const PanGesture& gesture )
2362 // Guard against destruction during signal emission
2363 // Note that Emit() methods are called indirectly e.g. from within ScrollView::OnGestureEx()
2364 Actor self( Self() );
2368 DALI_LOG_SCROLL_STATE("[0x%X] Pan Ignored, Insensitive", this);
2370 // If another callback on the same original signal disables sensitivity,
2371 // this callback will still be called, so we must suppress it.
2375 // translate Gesture input to get useful data...
2376 switch(gesture.state)
2378 case Gesture::Started:
2380 DALI_LOG_SCROLL_STATE("[0x%X] Pan Started", this);
2381 mPanStartPosition = gesture.position - gesture.displacement;
2382 UpdateLocalScrollProperties();
2385 self.SetProperty( mPropertyPanning, true );
2386 self.SetProperty( mPropertyScrollStartPagePosition, Vector3(gesture.position.x, gesture.position.y, 0.0f) );
2388 UpdateMainInternalConstraint();
2392 case Gesture::Continuing:
2396 DALI_LOG_SCROLL_STATE("[0x%X] Pan Continuing", this);
2397 GestureContinuing(gesture.screenDisplacement);
2401 // If we do not think we are panning, then we should not do anything here
2407 case Gesture::Finished:
2408 case Gesture::Cancelled:
2412 DALI_LOG_SCROLL_STATE("[0x%X] Pan %s", this, ( ( gesture.state == Gesture::Finished ) ? "Finished" : "Cancelled" ) );
2414 UpdateLocalScrollProperties();
2415 mLastVelocity = gesture.velocity;
2417 self.SetProperty( mPropertyPanning, false );
2419 if( mScrollMainInternalPrePositionConstraint )
2421 self.RemoveConstraint(mScrollMainInternalPrePositionConstraint);
2424 if( mOvershootIndicator )
2426 mOvershootIndicator->ClearOvershoot();
2431 // If we do not think we are panning, then we should not do anything here
2437 case Gesture::Possible:
2438 case Gesture::Clear:
2440 // Nothing to do, not needed.
2444 } // end switch(gesture.state)
2446 OnGestureEx(gesture.state);
2449 void ScrollView::OnGestureEx(Gesture::State state)
2451 // call necessary signals for application developer
2453 if(state == Gesture::Started)
2455 Vector3 currentScrollPosition = GetCurrentScrollPosition();
2456 Self().SetProperty(mPropertyScrolling, true);
2458 DALI_LOG_SCROLL_STATE("[0x%X] mScrollStartedSignalV2 2 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
2459 mScrollStartedSignalV2.Emit( currentScrollPosition );
2461 else if( (state == Gesture::Finished) ||
2462 (state == Gesture::Cancelled) ) // Finished/default
2464 // when all the gestures have finished, we finish the transform.
2465 // so if a user decides to pan (1 gesture), and then pan+zoom (2 gestures)
2466 // then stop panning (back to 1 gesture), and then stop zooming (0 gestures).
2467 // this is the point we end, and perform necessary snapping.
2468 mGestureStackDepth--;
2469 if(mGestureStackDepth==0)
2471 // no flick if we have not exceeded min flick distance
2472 if( (fabsf(mPanDelta.x) < mMinFlickDistance.x)
2473 && (fabsf(mPanDelta.y) < mMinFlickDistance.y) )
2475 // reset flick velocity
2476 mLastVelocity = Vector2::ZERO;
2482 DALI_LOG_SCROLL_STATE("[0x%X] mGestureStackDepth[%d]", this, mGestureStackDepth);
2487 void ScrollView::FinishTransform()
2489 // at this stage internal x and x scroll position should have followed prescroll position exactly
2490 Actor self = Self();
2492 PreAnimatedScrollSetup();
2494 // convert pixels/millisecond to pixels per second
2495 bool animating = SnapWithVelocity(mLastVelocity * 1000.0f);
2499 // if not animating, then this pan has completed right now.
2500 SetScrollUpdateNotification(false);
2502 Self().SetProperty(mPropertyScrolling, false);
2504 if( fabs(mScrollPrePosition.x - mScrollTargetPosition.x) > Math::MACHINE_EPSILON_10 )
2506 SnapInternalXTo(mScrollTargetPosition.x);
2508 if( fabs(mScrollPrePosition.y - mScrollTargetPosition.y) > Math::MACHINE_EPSILON_10 )
2510 SnapInternalYTo(mScrollTargetPosition.y);
2512 Vector3 currentScrollPosition = GetCurrentScrollPosition();
2513 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignalV2 6 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
2514 mScrollCompletedSignalV2.Emit( currentScrollPosition );
2518 Vector3 ScrollView::GetOvershoot(Vector3& position) const
2520 Vector3 size = Self().GetCurrentSize();
2523 const RulerDomain rulerDomainX = mRulerX->GetDomain();
2524 const RulerDomain rulerDomainY = mRulerY->GetDomain();
2526 if(mRulerX->IsEnabled() && rulerDomainX.enabled)
2528 const float left = rulerDomainX.min - position.x;
2529 const float right = size.width - rulerDomainX.max - position.x;
2536 overshoot.x = right;
2540 if(mRulerY->IsEnabled() && rulerDomainY.enabled)
2542 const float top = rulerDomainY.min - position.y;
2543 const float bottom = size.height - rulerDomainY.max - position.y;
2550 overshoot.y = bottom;
2557 bool ScrollView::OnAccessibilityPan(PanGesture gesture)
2559 // Keep track of whether this is an AccessibilityPan
2560 mInAccessibilityPan = true;
2562 mInAccessibilityPan = false;
2567 void ScrollView::ClampPosition(Vector3& position) const
2569 ClampState3 clamped;
2570 ClampPosition(position, clamped);
2573 void ScrollView::ClampPosition(Vector3& position, ClampState3 &clamped) const
2575 Vector3 size = Self().GetCurrentSize();
2577 position.x = -mRulerX->Clamp(-position.x, size.width, 1.0f, clamped.x); // NOTE: X & Y rulers think in -ve coordinate system.
2578 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.
2580 clamped.z = NotClamped;
2583 void ScrollView::WrapPosition(Vector3& position) const
2587 const RulerDomain rulerDomainX = mRulerX->GetDomain();
2588 const RulerDomain rulerDomainY = mRulerY->GetDomain();
2590 if(mRulerX->IsEnabled())
2592 position.x = -WrapInDomain(-position.x, rulerDomainX.min, rulerDomainX.max);
2595 if(mRulerY->IsEnabled())
2597 position.y = -WrapInDomain(-position.y, rulerDomainY.min, rulerDomainY.max);
2602 void ScrollView::UpdateMainInternalConstraint()
2604 // TODO: Only update the constraints which have changed, rather than remove all and add all again.
2605 // Requires a dali-core ApplyConstraintAt, or a ReplaceConstraint. The former is probably more flexible.
2606 Actor self = Self();
2607 PanGestureDetector detector( GetPanGestureDetector() );
2609 if(mScrollMainInternalPositionConstraint)
2611 self.RemoveConstraint(mScrollMainInternalPositionConstraint);
2612 self.RemoveConstraint(mScrollMainInternalDeltaConstraint);
2613 self.RemoveConstraint(mScrollMainInternalFinalConstraint);
2614 self.RemoveConstraint(mScrollMainInternalRelativeConstraint);
2616 if( mScrollMainInternalPrePositionConstraint )
2618 self.RemoveConstraint(mScrollMainInternalPrePositionConstraint);
2621 // TODO: It's probably better to use a local displacement value as this will give a displacement when scrolling just commences
2622 // but we need to make sure than the gesture system gives displacement since last frame (60Hz), not displacement since last touch event (90Hz).
2624 // 1. First calculate the pre-position (this is the scroll position if no clamping has taken place)
2625 Vector2 initialPanMask = Vector2(mRulerX->IsEnabled() ? 1.0f : 0.0f, mRulerY->IsEnabled() ? 1.0f : 0.0f);
2627 if( mLockAxis == LockVertical )
2629 initialPanMask.y = 0.0f;
2631 else if( mLockAxis == LockHorizontal )
2633 initialPanMask.x = 0.0f;
2635 Constraint constraint;
2639 constraint = Constraint::New<Vector3>( mPropertyPrePosition,
2640 Source( detector, PanGestureDetector::LOCAL_POSITION ),
2641 Source( self, Actor::SIZE ),
2642 InternalPrePositionConstraint( mPanStartPosition, initialPanMask, mAxisAutoLock, mAxisAutoLockGradient, mLockAxis, mMaxOvershoot, mRulerX->GetDomain(), mRulerY->GetDomain() ) );
2643 mScrollMainInternalPrePositionConstraint = self.ApplyConstraint( constraint );
2646 // 2. Second calculate the clamped position (actual position)
2647 constraint = Constraint::New<Vector3>( mPropertyPosition,
2648 LocalSource( mPropertyPrePosition ),
2649 LocalSource( mPropertyPositionMin ),
2650 LocalSource( mPropertyPositionMax ),
2651 Source( self, Actor::SIZE ),
2652 InternalPositionConstraint( mRulerX->GetDomain(),
2653 mRulerY->GetDomain(), mWrapMode ) );
2654 mScrollMainInternalPositionConstraint = self.ApplyConstraint( constraint );
2656 constraint = Constraint::New<Vector3>( mPropertyPositionDelta,
2657 LocalSource( mPropertyPosition ),
2658 LocalSource( mPropertyDomainOffset ),
2659 InternalPositionDeltaConstraint );
2660 mScrollMainInternalDeltaConstraint = self.ApplyConstraint( constraint );
2662 constraint = Constraint::New<Vector3>( mPropertyFinal,
2663 LocalSource( mPropertyPosition ),
2664 LocalSource( mPropertyOvershootX ),
2665 LocalSource( mPropertyOvershootY ),
2666 InternalFinalConstraint( FinalDefaultAlphaFunction,
2667 FinalDefaultAlphaFunction ) );
2668 mScrollMainInternalFinalConstraint = self.ApplyConstraint( constraint );
2670 constraint = Constraint::New<Vector3>( mPropertyRelativePosition,
2671 LocalSource( mPropertyPosition ),
2672 LocalSource( mPropertyPositionMin ),
2673 LocalSource( mPropertyPositionMax ),
2674 LocalSource( Actor::SIZE ),
2675 InternalRelativePositionConstraint );
2676 mScrollMainInternalRelativeConstraint = self.ApplyConstraint( constraint );
2678 // When panning we want to make sure overshoot values are affected by pre position and post position
2679 SetOvershootConstraintsEnabled(!mWrapMode);
2682 void ScrollView::SetOvershootConstraintsEnabled(bool enabled)
2684 Actor self( Self() );
2685 // remove and reset, it may now be in wrong order with the main internal constraints
2686 if( mScrollMainInternalOvershootXConstraint )
2688 self.RemoveConstraint(mScrollMainInternalOvershootXConstraint);
2689 mScrollMainInternalOvershootXConstraint.Reset();
2690 self.RemoveConstraint(mScrollMainInternalOvershootYConstraint);
2691 mScrollMainInternalOvershootYConstraint.Reset();
2695 Constraint constraint = Constraint::New<float>( mPropertyOvershootX,
2696 LocalSource( mPropertyPrePosition ),
2697 LocalSource( mPropertyPosition ),
2698 LocalSource( mPropertyCanScrollHorizontal ),
2699 OvershootXConstraint(mMaxOvershoot.x) );
2700 mScrollMainInternalOvershootXConstraint = self.ApplyConstraint( constraint );
2702 constraint = Constraint::New<float>( mPropertyOvershootY,
2703 LocalSource( mPropertyPrePosition ),
2704 LocalSource( mPropertyPosition ),
2705 LocalSource( mPropertyCanScrollVertical ),
2706 OvershootYConstraint(mMaxOvershoot.y) );
2707 mScrollMainInternalOvershootYConstraint = self.ApplyConstraint( constraint );
2711 self.SetProperty(mPropertyOvershootX, 0.0f);
2712 self.SetProperty(mPropertyOvershootY, 0.0f);
2716 void ScrollView::SetInternalConstraints()
2718 // Internal constraints (applied to target ScrollBase Actor itself) /////////
2719 UpdateMainInternalConstraint();
2721 // User definable constraints to apply to all child actors //////////////////
2722 Actor self = Self();
2724 // Apply some default constraints to ScrollView & its bound actors
2725 // Movement + Wrap function
2727 Constraint constraint;
2729 // MoveActor (scrolling)
2730 constraint = Constraint::New<Vector3>( Actor::POSITION,
2731 Source( self, mPropertyPosition ),
2732 MoveActorConstraint );
2733 constraint.SetRemoveAction(Constraint::Discard);
2734 ApplyConstraintToBoundActors(constraint);
2736 // WrapActor (wrap functionality)
2737 constraint = Constraint::New<Vector3>( Actor::POSITION,
2738 LocalSource( Actor::SCALE ),
2739 LocalSource( Actor::ANCHOR_POINT ),
2740 LocalSource( Actor::SIZE ),
2741 Source( self, mPropertyPositionMin ),
2742 Source( self, mPropertyPositionMax ),
2743 Source( self, mPropertyWrap ),
2744 WrapActorConstraint );
2745 constraint.SetRemoveAction(Constraint::Discard);
2746 ApplyConstraintToBoundActors(constraint);
2749 } // namespace Internal
2751 } // namespace Toolkit