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/public-api/events/mouse-wheel-event.h>
21 #include <dali-toolkit/public-api/controls/scrollable/scroll-view/scroll-view-constraints.h>
22 #include <dali-toolkit/public-api/controls/scrollable/scroll-component-impl.h>
23 #include <dali-toolkit/internal/controls/scrollable/scroll-view/scroll-view-impl.h>
24 #include <dali-toolkit/internal/controls/scrollable/scroll-view/scroll-view-effect-impl.h>
25 #include <dali-toolkit/internal/controls/scrollable/scroll-view/scroll-overshoot-indicator-impl.h>
26 #include <dali/integration-api/debug.h>
28 #define ENABLED_SCROLL_STATE_LOGGING
30 #ifdef ENABLED_SCROLL_STATE_LOGGING
31 #define DALI_LOG_SCROLL_STATE(format, args...) Dali::Integration::Log::LogMessage(Dali::Integration::Log::DebugInfo, "%s:%d " format, __PRETTY_FUNCTION__, __LINE__, ## args)
33 #define DALI_LOG_SCROLL_STATE(format, args...)
36 // TODO: Change to two class system:
37 // 1. DraggableActor (is an actor which can be dragged anywhere/scaled/rotated, can be set to range using the ruler)
38 // 2. ScrollView (contains a draggable actor that can a) be dragged in the negative X, and Y domain, b) has a hitArea for touches)
40 // TODO: Asymetrical scaling
41 // TODO: external components (page and status overlays).
43 // TODO: upgrade Vector2/3 to support returning Unit vectors, normals, & cross product (dot product is already provided)
50 const int DEFAULT_REFRESH_INTERVAL_MILLISECONDS = 50; ///< Refresh rate TODO: Animation should have an update signal (and see item-view-impl)
51 const float FLICK_SPEED_THRESHOLD = 500.0f; ///< Flick threshold in pixels/ms
52 const float FREE_FLICK_SPEED_THRESHOLD = 200.0f; ///< Free-Flick threshold in pixels/ms
53 const float AUTOLOCK_AXIS_MINIMUM_DISTANCE2 = 100.0f; ///< Auto-lock axis after minimum distance squared.
54 const float FLICK_ORTHO_ANGLE_RANGE = 60.0f; ///< degrees. (if >45, then supports diagonal flicking)
55 const unsigned int MAXIMUM_NUMBER_OF_VALUES = 5; ///< Number of values to use for weighted pan calculation.
56 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.
57 const unsigned long MINIMUM_TIME_BETWEEN_DOWN_AND_UP_FOR_RESET( 150u );
58 const float DEFAULT_OVERSHOOT_ANIMATION_DURATION = 0.35f; // time in seconds
59 const Vector2 OVERSCROLL_CLAMP(1.0f, 1.0f); // maximum overscroll allowed in pixels when overshoot indicator is being used
60 const float TOUCH_DOWN_TIMER_INTERVAL = 100.0f;
61 const float DEFAULT_SCROLL_UPDATE_DISTANCE( 30.0f ); ///< Default distance to travel in pixels for scroll update signal
63 // predefined effect values
64 const Vector3 ANGLE_CAROUSEL_ROTATE(Math::PI * 0.5f, Math::PI * 0.5f, 0.0f);
65 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
66 const Vector2 ANGLE_CUSTOM_CUBE_SWING(-Math::PI * 0.45f, -Math::PI * 0.45f); ///< outer cube pages swing 90 degrees as they pan offscreen
67 const Vector2 ANGLE_SPIRAL_SWING_IN(Math::PI * 0.5f, Math::PI * 0.5f);
68 const Vector2 ANGLE_SPIRAL_SWING_OUT(Math::PI * 0.35f, Math::PI * 0.35f);
69 const Vector2 ANGLE_OUTER_CUBE_SWING(Math::PI * 0.5f, Math::PI * 0.5f); ///< outer cube pages swing 90 degrees as they pan offscreen
71 // Helpers ////////////////////////////////////////////////////////////////////////////////////////
73 // TODO: GetAngle for Vector2 can be moved.
74 // GetAngle for Vector3 needs to be measured against a normal/plane.
77 * @param[in] vector The 3D vector to be measured
78 * @return angle in radians from 0 to 2PI
80 float GetAngle(const Vector3& vector)
82 return atan2(vector.y, vector.x) + Math::PI;
86 * @param[in] vector The 2D vector to be measured
87 * @return angle in radians from 0 to 2PI
89 float GetAngle(const Vector2& vector)
91 return atan2(vector.y, vector.x) + Math::PI;
95 * Find the vector (distance) from (a) to (b)
96 * in domain (start) to (end)
97 * (\ / start) (\ / end)
100 * @note assumes both (a) and (b) are already with the domain
103 * @param[in] a the current point
104 * @param[in] b the target point
105 * @param[in] start the start of the domain
106 * @param[in] end the end of the domain
107 * @param[in] bias whether to only take the right direction or the left direction,
108 * or the shortest direction.
109 * @return the shortest direction and distance
111 float VectorInDomain(float a, float b, float start, float end, Dali::Toolkit::DirectionBias bias)
113 if(bias == Dali::Toolkit::DirectionBiasNone)
115 return ShortestDistanceInDomain( a, b, start, end );
118 float size = end-start;
124 if(bias == Dali::Toolkit::DirectionBiasRight) // going right, take the vector.
130 float aRight = a+size;
137 if(bias == Dali::Toolkit::DirectionBiasLeft) // going left, take the vector.
143 float aLeft = a-size;
150 * Returns the position of the anchor within actor
152 * @param actor The Actor
153 * @param anchor The Anchor point of interest.
154 * @return The position of the Anchor
156 Vector3 GetPositionOfAnchor(Actor &actor, const Vector3 &anchor)
158 Vector3 childPosition = actor.GetCurrentPosition();
159 Vector3 childAnchor = - actor.GetCurrentAnchorPoint() + anchor;
160 Vector3 childSize = actor.GetCurrentSize();
162 return childPosition + childAnchor * childSize;
165 // AlphaFunctions /////////////////////////////////////////////////////////////////////////////////
167 float FinalDefaultAlphaFunction(float offset)
169 return offset * 0.5f;
173 * ConstantDecelerationAlphaFunction
174 * Newtoninan distance for constant deceleration
175 * v = 1 - t, s = t - 1/2 t^2
176 * when t = 0, s = 0.0 (min distance)
177 * when t = 1, s = 0.5 (max distance)
178 * progress = s / (max-min) = 2t - t^2
180 * @param[in] offset The input progress
181 * @return The output progress
183 float ConstantDecelerationAlphaFunction(float progress)
185 return progress * 2.0f - progress * progress;
188 // Internal Constraints ///////////////////////////////////////////////////////////////////////////
191 * Internal Relative position Constraint
192 * Generates the relative position value of the scroll view
193 * based on the absolute position, and it's relation to the
194 * scroll domain. This is a value from 0.0f to 1.0f in each
195 * scroll position axis.
197 Vector3 InternalRelativePositionConstraint(const Vector3& current,
198 const PropertyInput& scrollPositionProperty,
199 const PropertyInput& scrollMinProperty,
200 const PropertyInput& scrollMaxProperty,
201 const PropertyInput& scrollSizeProperty)
203 Vector3 position = -scrollPositionProperty.GetVector3();
204 const Vector3& min = scrollMinProperty.GetVector3();
205 const Vector3& max = scrollMaxProperty.GetVector3();
206 const Vector3& size = scrollSizeProperty.GetVector3();
208 position.x = WrapInDomain(position.x, min.x, max.x);
209 position.y = WrapInDomain(position.y, min.y, max.y);
211 Vector3 relativePosition;
212 Vector3 domainSize = (max - min) - size;
214 relativePosition.x = domainSize.x > Math::MACHINE_EPSILON_1 ? fabsf((position.x - min.x) / domainSize.x) : 0.0f;
215 relativePosition.y = domainSize.y > Math::MACHINE_EPSILON_1 ? fabsf((position.y - min.y) / domainSize.y) : 0.0f;
217 return relativePosition;
220 } // unnamed namespace
235 * Returns whether to lock scrolling to a particular axis
237 * @param[in] panDelta Distance panned since gesture started
238 * @param[in] currentLockAxis The current lock axis value
239 * @param[in] lockGradient How quickly to lock to a particular axis
241 * @return The new axis lock state
243 ScrollView::LockAxis GetLockAxis(const Vector2& panDelta, ScrollView::LockAxis currentLockAxis, float lockGradient)
245 if(panDelta.LengthSquared() > AUTOLOCK_AXIS_MINIMUM_DISTANCE2 &&
246 currentLockAxis == ScrollView::LockPossible)
248 float dx = fabsf(panDelta.x);
249 float dy = fabsf(panDelta.y);
250 if(dx * lockGradient >= dy)
252 // 0.36:1 gradient to the horizontal (deviate < 20 degrees)
253 currentLockAxis = ScrollView::LockVertical;
255 else if(dy * lockGradient > dx)
257 // 0.36:1 gradient to the vertical (deviate < 20 degrees)
258 currentLockAxis = ScrollView::LockHorizontal;
262 currentLockAxis = ScrollView::LockNone;
265 return currentLockAxis;
269 * Internal Pre-Position Property Constraint.
271 * Generates position property based on current position + gesture displacement.
272 * Or generates position property based on positionX/Y.
273 * Note: This is the position prior to any clamping at scroll boundaries.
274 * TODO: Scale & Rotation Transforms.
276 struct InternalPrePositionConstraint
278 InternalPrePositionConstraint(const Vector2& initialPanMask,
280 float axisAutoLockGradient,
281 ScrollView::LockAxis initialLockAxis,
282 const Vector2& maxOvershoot,
283 const RulerDomain& domainX, const RulerDomain& domainY)
284 : mInitialPanMask(initialPanMask),
285 mDomainMin( -domainX.min, -domainY.min ),
286 mDomainMax( -domainX.max, -domainY.max ),
287 mMaxOvershoot(maxOvershoot),
288 mAxisAutoLockGradient(axisAutoLockGradient),
289 mLockAxis(initialLockAxis),
290 mAxisAutoLock(axisAutoLock),
292 mClampX( domainX.enabled ),
293 mClampY( domainY.enabled )
297 Vector3 operator()(const Vector3& current,
298 const PropertyInput& gesturePositionProperty,
299 const PropertyInput& gestureDisplacementProperty,
300 const PropertyInput& sizeProperty)
302 Vector3 scrollPostPosition = current;
303 Vector2 panPosition = gesturePositionProperty.GetVector2();
307 mLocalStart = gesturePositionProperty.GetVector2() - gestureDisplacementProperty.GetVector2();
308 mPrePosition = current;
309 mCurrentPanMask = mInitialPanMask;
313 // Calculate Deltas...
314 Vector2 currentPosition = gesturePositionProperty.GetVector2();
315 Vector2 panDelta( currentPosition - mLocalStart );
317 // Axis Auto Lock - locks the panning to the horizontal or vertical axis if the pan
318 // appears mostly horizontal or mostly vertical respectively...
321 mLockAxis = GetLockAxis(panDelta, mLockAxis, mAxisAutoLockGradient);
322 if( mLockAxis == ScrollView::LockVertical )
324 mCurrentPanMask.y = 0.0f;
326 else if( mLockAxis == ScrollView::LockHorizontal )
328 mCurrentPanMask.x = 0.0f;
332 // Restrict deltas based on ruler enable/disable and axis-lock state...
333 panDelta *= mCurrentPanMask;
335 // Perform Position transform based on input deltas...
336 scrollPostPosition = mPrePosition;
337 scrollPostPosition.GetVectorXY() += panDelta;
339 // if no wrapping then clamp preposition to maximum overshoot amount
340 const Vector3& size = sizeProperty.GetVector3();
343 float newXPosition = Clamp(scrollPostPosition.x, (mDomainMax.x + size.x) - mMaxOvershoot.x, mDomainMin.x + mMaxOvershoot.x );
344 if( (newXPosition < scrollPostPosition.x - Math::MACHINE_EPSILON_1)
345 || (newXPosition > scrollPostPosition.x + Math::MACHINE_EPSILON_1) )
347 mPrePosition.x = newXPosition;
348 mLocalStart.x = panPosition.x;
350 scrollPostPosition.x = newXPosition;
354 float newYPosition = Clamp(scrollPostPosition.y, (mDomainMax.y + size.y) - mMaxOvershoot.y, mDomainMin.y + mMaxOvershoot.y );
355 if( (newYPosition < scrollPostPosition.y - Math::MACHINE_EPSILON_1)
356 || (newYPosition > scrollPostPosition.y + Math::MACHINE_EPSILON_1) )
358 mPrePosition.y = newYPosition;
359 mLocalStart.y = panPosition.y;
361 scrollPostPosition.y = newYPosition;
364 return scrollPostPosition;
367 Vector3 mPrePosition;
369 Vector2 mInitialPanMask; ///< Initial pan mask (based on ruler settings)
370 Vector2 mCurrentPanMask; ///< Current pan mask that can be altered by axis lock mode.
373 Vector2 mMaxOvershoot;
375 float mAxisAutoLockGradient; ///< Set by ScrollView
376 ScrollView::LockAxis mLockAxis;
378 bool mAxisAutoLock:1; ///< Set by ScrollView
385 * Internal Position Property Constraint.
387 * Generates position property based on pre-position
388 * Note: This is the position after clamping.
389 * (uses result of InternalPrePositionConstraint)
391 struct InternalPositionConstraint
393 InternalPositionConstraint(const RulerDomain& domainX, const RulerDomain& domainY, bool wrap)
394 : mDomainMin( -domainX.min, -domainY.min ),
395 mDomainMax( -domainX.max, -domainY.max ),
396 mClampX( domainX.enabled ),
397 mClampY( domainY.enabled ),
402 Vector3 operator()(const Vector3& current,
403 const PropertyInput& scrollPositionProperty,
404 const PropertyInput& scrollMinProperty,
405 const PropertyInput& scrollMaxProperty,
406 const PropertyInput& scrollSizeProperty)
408 Vector3 position = scrollPositionProperty.GetVector3();
409 const Vector2& size = scrollSizeProperty.GetVector3().GetVectorXY();
410 const Vector3& min = scrollMinProperty.GetVector3();
411 const Vector3& max = scrollMaxProperty.GetVector3();
415 position.x = -WrapInDomain(-position.x, min.x, max.x);
416 position.y = -WrapInDomain(-position.y, min.y, max.y);
420 // clamp post position to domain
421 position.x = mClampX ? Clamp(position.x, mDomainMax.x + size.x, mDomainMin.x ) : position.x;
422 position.y = mClampY ? Clamp(position.y, mDomainMax.y + size.y, mDomainMin.y ) : position.y;
437 * This constraint updates the X overshoot property using the difference
438 * mPropertyPrePosition.x and mPropertyPosition.x, returning a relative value between 0.0f and 1.0f
440 struct OvershootXConstraint
442 OvershootXConstraint(float maxOvershoot) : mMaxOvershoot(maxOvershoot) {}
444 float operator()(const float& current,
445 const PropertyInput& scrollPrePositionProperty,
446 const PropertyInput& scrollPostPositionProperty,
447 const PropertyInput& canScrollProperty)
449 if( canScrollProperty.GetBoolean() )
451 const Vector3& scrollPrePosition = scrollPrePositionProperty.GetVector3();
452 const Vector3& scrollPostPosition = scrollPostPositionProperty.GetVector3();
453 float newOvershoot = scrollPrePosition.x - scrollPostPosition.x;
454 return (newOvershoot > 0.0f ? std::min(newOvershoot, mMaxOvershoot) : std::max(newOvershoot, -mMaxOvershoot)) / mMaxOvershoot;
463 * This constraint updates the Y overshoot property using the difference
464 * mPropertyPrePosition.y and mPropertyPosition.y, returning a relative value between 0.0f and 1.0f
466 struct OvershootYConstraint
468 OvershootYConstraint(float maxOvershoot) : mMaxOvershoot(maxOvershoot) {}
470 float operator()(const float& current,
471 const PropertyInput& scrollPrePositionProperty,
472 const PropertyInput& scrollPostPositionProperty,
473 const PropertyInput& canScrollProperty)
475 if( canScrollProperty.GetBoolean() )
477 const Vector3& scrollPrePosition = scrollPrePositionProperty.GetVector3();
478 const Vector3& scrollPostPosition = scrollPostPositionProperty.GetVector3();
479 float newOvershoot = scrollPrePosition.y - scrollPostPosition.y;
480 return (newOvershoot > 0.0f ? std::min(newOvershoot, mMaxOvershoot) : std::max(newOvershoot, -mMaxOvershoot)) / mMaxOvershoot;
489 * When panning, this constraint updates the X property, otherwise
490 * it has no effect on the X property.
492 float InternalXConstraint(const float& current,
493 const PropertyInput& scrollPosition)
495 return scrollPosition.GetVector3().x;
499 * When panning, this constraint updates the Y property, otherwise
500 * it has no effect on the Y property.
502 float InternalYConstraint(const float& current,
503 const PropertyInput& scrollPosition)
505 return scrollPosition.GetVector3().y;
509 * Internal Position-Delta Property Constraint.
511 * Generates position-delta property based on scroll-position + scroll-offset properties.
513 Vector3 InternalPositionDeltaConstraint(const Vector3& current,
514 const PropertyInput& scrollPositionProperty,
515 const PropertyInput& scrollOffsetProperty)
517 const Vector3& scrollPosition = scrollPositionProperty.GetVector3();
518 const Vector3& scrollOffset = scrollOffsetProperty.GetVector3();
520 return scrollPosition + scrollOffset;
524 * Internal Final Position Constraint
525 * The position of content is:
526 * of scroll-position + f(scroll-overshoot)
527 * where f(...) function defines how overshoot
528 * should affect final-position.
530 struct InternalFinalConstraint
532 InternalFinalConstraint(AlphaFunction functionX,
533 AlphaFunction functionY)
534 : mFunctionX(functionX),
535 mFunctionY(functionY)
539 Vector3 operator()(const Vector3& current,
540 const PropertyInput& scrollPositionProperty,
541 const PropertyInput& scrollOvershootXProperty,
542 const PropertyInput& scrollOvershootYProperty)
544 const float& overshootx = scrollOvershootXProperty.GetFloat();
545 const float& overshooty = scrollOvershootYProperty.GetFloat();
546 Vector3 offset( mFunctionX(overshootx),
547 mFunctionY(overshooty),
550 return scrollPositionProperty.GetVector3() - offset;
553 AlphaFunction mFunctionX;
554 AlphaFunction mFunctionY;
560 return Toolkit::ScrollView::New();
563 TypeRegistration typeRegistration( typeid(Toolkit::ScrollView), typeid(Toolkit::Scrollable), Create );
565 SignalConnectorType signalConnector1( typeRegistration, Toolkit::ScrollView::SIGNAL_SNAP_STARTED, &ScrollView::DoConnectSignal );
570 ///////////////////////////////////////////////////////////////////////////////////////////////////
572 ///////////////////////////////////////////////////////////////////////////////////////////////////
574 Dali::Toolkit::ScrollView ScrollView::New()
576 // Create the implementation
577 ScrollViewPtr scrollView(new ScrollView());
579 // Pass ownership to CustomActor via derived handle
580 Dali::Toolkit::ScrollView handle(*scrollView);
582 // Second-phase init of the implementation
583 // This can only be done after the CustomActor connection has been made...
584 scrollView->Initialize();
589 ScrollView::ScrollView()
592 mGestureStackDepth(0),
593 mRotationDelta(0.0f),
594 mScrollStateFlags(0),
595 mScrollPreRotation(0.0f),
596 mScrollPostRotation(0.0f),
597 mMinTouchesForPanning(1),
598 mMaxTouchesForPanning(1),
599 mLockAxis(LockPossible),
600 mScrollUpdateDistance(DEFAULT_SCROLL_UPDATE_DISTANCE),
601 mOvershootDelay(1.0f),
602 mMaxOvershoot(Toolkit::ScrollView::DEFAULT_MAX_OVERSHOOT, Toolkit::ScrollView::DEFAULT_MAX_OVERSHOOT),
603 mUserMaxOvershoot(Toolkit::ScrollView::DEFAULT_MAX_OVERSHOOT, Toolkit::ScrollView::DEFAULT_MAX_OVERSHOOT),
604 mSnapOvershootDuration(Toolkit::ScrollView::DEFAULT_SNAP_OVERSHOOT_DURATION),
605 mSnapOvershootAlphaFunction(AlphaFunctions::EaseOut),
606 mSnapDuration(Toolkit::ScrollView::DEFAULT_SLOW_SNAP_ANIMATION_DURATION),
607 mSnapAlphaFunction(AlphaFunctions::EaseOut),
608 mFlickDuration(Toolkit::ScrollView::DEFAULT_FAST_SNAP_ANIMATION_DURATION),
609 mFlickAlphaFunction(AlphaFunctions::EaseOut),
610 mAxisAutoLockGradient(Toolkit::ScrollView::DEFAULT_AXIS_AUTO_LOCK_GRADIENT),
611 mFrictionCoefficient(Toolkit::ScrollView::DEFAULT_FRICTION_COEFFICIENT),
612 mFlickSpeedCoefficient(Toolkit::ScrollView::DEFAULT_FLICK_SPEED_COEFFICIENT),
613 mMaxFlickSpeed(Toolkit::ScrollView::DEFAULT_MAX_FLICK_SPEED),
614 mInAccessibilityPan(false),
617 mScrollInterrupted(false),
620 mTouchDownTimeoutReached(false),
621 mActorAutoSnapEnabled(false),
622 mAutoResizeContainerEnabled(false),
624 mAxisAutoLock(false),
626 mDefaultMaxOvershoot(true)
628 SetRequiresMouseWheelEvents(true);
631 void ScrollView::OnInitialize()
635 // Internal Actor, used to hide actors from enumerations.
636 // Also actors added to Internal actor appear as overlays e.g. ScrollBar components.
637 mInternalActor = Actor::New();
638 mInternalActor.SetDrawMode(DrawMode::OVERLAY);
639 self.Add(mInternalActor);
640 mInternalActor.ApplyConstraint( Constraint::New<Vector3>( Actor::SIZE, ParentSource( Actor::SIZE ), EqualToConstraint() ) );
641 mInternalActor.SetParentOrigin(ParentOrigin::CENTER);
642 mInternalActor.SetAnchorPoint(AnchorPoint::CENTER);
646 // Register Scroll Properties.
647 RegisterProperties();
649 mScrollPostPosition = mScrollPrePosition = Vector3::ZERO;
650 mScrollPostScale = mScrollPreScale = Vector3::ONE;
651 mScrollPostRotation = mScrollPreRotation = 0.0f;
653 mMouseWheelScrollDistanceStep = Stage::GetCurrent().GetSize() * DEFAULT_MOUSE_WHEEL_SCROLL_DISTANCE_STEP_PROPORTION;
657 mGestureStackDepth = 0;
659 EnableGestureDetection( Gesture::Type( Gesture::Pan ) );
661 // For pan, default to only 1 touch required, ignoring touches outside this range.
662 SetTouchesRequiredForPanning(1, 1, false);
664 // By default we'll allow the user to freely drag the scroll view,
665 // while disabling the other rulers.
666 RulerPtr ruler = new DefaultRuler();
667 RulerPtr rulerDisabled = new DefaultRuler();
668 rulerDisabled->Disable();
671 mRulerScaleX = rulerDisabled;
672 mRulerScaleY = rulerDisabled;
673 mRulerRotation = rulerDisabled;
675 EnableScrollComponent(Toolkit::Scrollable::OvershootIndicator);
677 Vector3 size = GetControlSize();
678 UpdatePropertyDomain(size);
679 SetInternalConstraints();
682 void ScrollView::OnControlStageConnection()
684 DALI_LOG_SCROLL_STATE("[0x%X]", this);
688 SetScrollSensitive( false );
689 SetScrollSensitive( true );
691 if(IsScrollComponentEnabled(Toolkit::Scrollable::OvershootIndicator))
693 // try and make sure property notifications are set
694 EnableScrollComponent(Toolkit::Scrollable::OvershootIndicator);
698 void ScrollView::OnControlStageDisconnection()
700 DALI_LOG_SCROLL_STATE("[0x%X]", this);
705 ScrollView::~ScrollView()
707 DALI_LOG_SCROLL_STATE("[0x%X]", this);
710 AlphaFunction ScrollView::GetScrollSnapAlphaFunction() const
712 return mSnapAlphaFunction;
715 void ScrollView::SetScrollSnapAlphaFunction(AlphaFunction alpha)
717 mSnapAlphaFunction = alpha;
720 AlphaFunction ScrollView::GetScrollFlickAlphaFunction() const
722 return mFlickAlphaFunction;
725 void ScrollView::SetScrollFlickAlphaFunction(AlphaFunction alpha)
727 mFlickAlphaFunction = alpha;
730 float ScrollView::GetScrollSnapDuration() const
732 return mSnapDuration;
735 void ScrollView::SetScrollSnapDuration(float time)
737 mSnapDuration = time;
740 float ScrollView::GetScrollFlickDuration() const
742 return mFlickDuration;
745 void ScrollView::SetScrollFlickDuration(float time)
747 mFlickDuration = time;
750 void ScrollView::ApplyEffect(Toolkit::ScrollViewEffect effect)
752 Dali::Toolkit::ScrollView self = Dali::Toolkit::ScrollView::DownCast(Self());
754 // Assertion check to ensure effect doesn't already exist in this scrollview
755 bool effectAlreadyExistsInScrollView(false);
756 for (ScrollViewEffectIter iter = mEffects.begin(); iter != mEffects.end(); ++iter)
760 effectAlreadyExistsInScrollView = true;
765 DALI_ASSERT_ALWAYS(!effectAlreadyExistsInScrollView);
767 // add effect to effects list
768 mEffects.push_back(effect);
770 // invoke Attachment request to ScrollView first
771 GetImpl(effect).Attach(self);
774 Toolkit::ScrollViewEffect ScrollView::ApplyEffect(Toolkit::ScrollView::PageEffect effect)
776 Toolkit::ScrollViewEffect scrollEffect;
779 case Toolkit::ScrollView::PageEffectNone:
783 case Toolkit::ScrollView::PageEffectOuterCube:
785 Toolkit::ScrollViewCustomEffect customEffect;
786 scrollEffect = customEffect = Toolkit::ScrollViewCustomEffect::New();
787 Vector2 pageSize = Stage::GetCurrent().GetSize();
788 // set the page translation to the slide off distance, also add an extra value to space the pages, having a smaller spacing on translationOut will allow the spacing to reduce over time
789 // the page moving onto screen will start 50.0f further out (1.0f * 50.0f) and the spacing will reduce as its position reaches the centre (0.0f * 50.0f)
790 // the page moving off screen will slowly build a spacing from 0.0f to 20.0f
791 // the spacing from each page is added together for the final spacing between the two pages.
792 customEffect.SetPageTranslation(Vector3(pageSize.x, pageSize.y, 0) + Vector3(50.0f, 50.0f, 0.0f), Vector3(pageSize.x, pageSize.y, 0) + Vector3(20.0f, 20.0f, 0.0f));
793 customEffect.SetSwingAngleOut(ANGLE_CUSTOM_CUBE_SWING.x, Vector3(0.0f, -1.0f, 0.0f));
794 customEffect.SetSwingAnchor(AnchorPoint::CENTER, AnchorPoint::CENTER_LEFT);
795 customEffect.SetOpacityThreshold(0.7f);
798 case Toolkit::ScrollView::PageEffectDepth:
800 Toolkit::ScrollViewCustomEffect customEffect;
801 scrollEffect = customEffect = Toolkit::ScrollViewCustomEffect::New();
804 case Toolkit::ScrollView::PageEffectInnerCube:
806 Toolkit::ScrollViewCustomEffect customEffect;
807 scrollEffect = customEffect = Toolkit::ScrollViewCustomEffect::New();
808 customEffect.SetPageSpacing(Vector2(30.0f, 30.0f));
809 customEffect.SetAngledOriginPageRotation(ANGLE_CUBE_PAGE_ROTATE);
810 customEffect.SetSwingAngle(ANGLE_CUBE_PAGE_ROTATE.x, Vector3(0,-1,0));
811 customEffect.SetOpacityThreshold(0.5f);
814 case Toolkit::ScrollView::PageEffectCarousel:
816 Toolkit::ScrollViewCustomEffect customEffect;
817 scrollEffect = customEffect = Toolkit::ScrollViewCustomEffect::New();
818 customEffect.SetPageTranslation(Vector3(0,0,0), Vector3(-30, 0, 0));
819 customEffect.SetPageSpacing(Vector2(60.0f, 60.0f));
820 customEffect.SetAngledOriginPageRotation(-ANGLE_CUBE_PAGE_ROTATE);
821 customEffect.SetOpacityThreshold(0.2f, 0.6f);
824 case Toolkit::ScrollView::PageEffectSpiral:
826 Toolkit::ScrollViewCustomEffect customEffect;
827 scrollEffect = customEffect = Toolkit::ScrollViewCustomEffect::New();
829 Vector2 pageSize = Stage::GetCurrent().GetSize();
830 customEffect.SetSwingAngle(-ANGLE_SPIRAL_SWING_IN.x, Vector3(0.0f, -1.0f, 0.0f), ANGLE_SPIRAL_SWING_OUT.x, Vector3(0.0f, -1.0f, 0.0f));
831 //customEffect.SetSwingAngleAlphaFunctionOut(AlphaFunctions::EaseOut);
832 customEffect.SetSwingAnchor(AnchorPoint::CENTER_RIGHT);
833 customEffect.SetPageTranslation(Vector3(pageSize.x, pageSize.y, 0) + Vector3(100.0f, 100.0f, 0.0f), Vector3(pageSize.x, pageSize.y, -pageSize.y * 2.0f) * 0.33f);
834 //customEffect.SetPageTranslateAlphaFunctionOut(AlphaFunctions::EaseOut);
835 customEffect.SetOpacityThreshold(0.75f, 0.6f);
836 customEffect.SetOpacityAlphaFunctionIn(AlphaFunctions::EaseInOut);
841 DALI_ASSERT_DEBUG(0 && "unknown scroll view effect");
844 RemoveConstraintsFromChildren();
847 ApplyEffect(scrollEffect);
852 void ScrollView::RemoveEffect(Toolkit::ScrollViewEffect effect)
854 Dali::Toolkit::ScrollView self = Dali::Toolkit::ScrollView::DownCast(Self());
856 // remove effect from effects list
857 bool effectExistedInScrollView(false);
858 for (ScrollViewEffectIter iter = mEffects.begin(); iter != mEffects.end(); ++iter)
862 mEffects.erase(iter);
863 effectExistedInScrollView = true;
868 // Assertion check to ensure effect existed.
869 DALI_ASSERT_ALWAYS(effectExistedInScrollView);
871 // invoke Detachment request to ScrollView last
872 GetImpl(effect).Detach(self);
875 void ScrollView::RemoveAllEffects()
877 Dali::Toolkit::ScrollView self = Dali::Toolkit::ScrollView::DownCast(Self());
879 for (ScrollViewEffectIter effectIter = mEffects.begin(); effectIter != mEffects.end(); ++effectIter)
881 Toolkit::ScrollViewEffect effect = *effectIter;
883 // invoke Detachment request to ScrollView last
884 GetImpl(effect).Detach(self);
890 void ScrollView::ApplyConstraintToChildren(Constraint constraint)
892 ApplyConstraintToBoundActors(constraint);
895 void ScrollView::RemoveConstraintsFromChildren()
897 RemoveConstraintsFromBoundActors();
900 const RulerPtr ScrollView::GetRulerX() const
905 const RulerPtr ScrollView::GetRulerY() const
910 void ScrollView::SetRulerX(RulerPtr ruler)
914 Vector3 size = GetControlSize();
915 UpdatePropertyDomain(size);
916 UpdateMainInternalConstraint();
919 void ScrollView::SetRulerY(RulerPtr ruler)
923 Vector3 size = GetControlSize();
924 UpdatePropertyDomain(size);
925 UpdateMainInternalConstraint();
928 void ScrollView::UpdatePropertyDomain(const Vector3& size)
931 Vector3 min = mMinScroll;
932 Vector3 max = mMaxScroll;
933 bool scrollPositionChanged = false;
934 bool domainChanged = false;
936 bool canScrollVertical = false;
937 bool canScrollHorizontal = false;
938 UpdateLocalScrollProperties();
939 if(mRulerX->IsEnabled())
941 const Toolkit::RulerDomain& rulerDomain = mRulerX->GetDomain();
942 if( fabsf(min.x - rulerDomain.min) > Math::MACHINE_EPSILON_10000
943 || fabsf(max.x - rulerDomain.max) > Math::MACHINE_EPSILON_10000 )
945 domainChanged = true;
946 min.x = rulerDomain.min;
947 max.x = rulerDomain.max;
949 // make sure new scroll value is within new domain
950 if( mScrollPrePosition.x < min.x
951 || mScrollPrePosition.x > max.x )
953 scrollPositionChanged = true;
954 mScrollPrePosition.x = Clamp(mScrollPrePosition.x, -(max.x - size.x), -min.x);
957 if( (fabsf(rulerDomain.max - rulerDomain.min) - size.x) > Math::MACHINE_EPSILON_10000 )
959 canScrollHorizontal = true;
963 if(mRulerY->IsEnabled())
965 const Toolkit::RulerDomain& rulerDomain = mRulerY->GetDomain();
966 if( fabsf(min.y - rulerDomain.min) > Math::MACHINE_EPSILON_10000
967 || fabsf(max.y - rulerDomain.max) > Math::MACHINE_EPSILON_10000 )
969 domainChanged = true;
970 min.y = rulerDomain.min;
971 max.y = rulerDomain.max;
973 // make sure new scroll value is within new domain
974 if( mScrollPrePosition.y < min.y
975 || mScrollPrePosition.y > max.y )
977 scrollPositionChanged = true;
978 mScrollPrePosition.y = Clamp(mScrollPrePosition.y, -(max.y - size.y), -min.y);
981 if( (fabsf(rulerDomain.max - rulerDomain.min) - size.y) > Math::MACHINE_EPSILON_10000 )
983 canScrollVertical = true;
986 // avoid setting properties if possible, otherwise this will cause an entire update as well as triggering constraints using each property we update
987 if( self.GetProperty<bool>(mPropertyCanScrollVertical) != canScrollVertical )
989 self.SetProperty(mPropertyCanScrollVertical, canScrollVertical);
991 if( self.GetProperty<bool>(mPropertyCanScrollHorizontal) != canScrollHorizontal )
993 self.SetProperty(mPropertyCanScrollHorizontal, canScrollHorizontal);
995 if( scrollPositionChanged )
997 self.SetProperty(mPropertyPrePosition, mScrollPrePosition);
1003 self.SetProperty(mPropertyPositionMin, min );
1004 self.SetProperty(mPropertyPositionMax, max );
1008 void ScrollView::SetRulerScaleX(RulerPtr ruler)
1010 mRulerScaleX = ruler;
1011 UpdateMainInternalConstraint();
1014 void ScrollView::SetRulerScaleY(RulerPtr ruler)
1016 mRulerScaleY = ruler;
1017 UpdateMainInternalConstraint();
1020 void ScrollView::SetRulerRotation(RulerPtr ruler)
1022 mRulerRotation = ruler;
1023 UpdateMainInternalConstraint();
1026 void ScrollView::SetScrollSensitive(bool sensitive)
1028 Actor self = Self();
1029 PanGestureDetector panGesture( GetPanGestureDetector() );
1031 DALI_LOG_SCROLL_STATE("[0x%X] sensitive[%d]", this, int(sensitive));
1033 if((!mSensitive) && (sensitive))
1035 mSensitive = sensitive;
1036 panGesture.Attach(self);
1038 else if((mSensitive) && (!sensitive))
1040 // while the scroll view is panning, the state needs to be reset.
1041 bool isPanning = self.GetProperty<bool>( mPropertyPanning );
1044 PanGesture cancelGesture( Gesture::Cancelled );
1045 OnPan( cancelGesture );
1048 panGesture.Detach(self);
1049 mSensitive = sensitive;
1051 mGestureStackDepth = 0;
1055 void ScrollView::SetMaxOvershoot(float overshootX, float overshootY)
1057 mMaxOvershoot.x = overshootX;
1058 mMaxOvershoot.y = overshootY;
1059 mUserMaxOvershoot = mMaxOvershoot;
1060 mDefaultMaxOvershoot = false;
1061 UpdateMainInternalConstraint();
1064 void ScrollView::SetSnapOvershootAlphaFunction(AlphaFunction alpha)
1066 mSnapOvershootAlphaFunction = alpha;
1069 void ScrollView::SetSnapOvershootDuration(float duration)
1071 mSnapOvershootDuration = duration;
1074 void ScrollView::SetTouchesRequiredForPanning(unsigned int minTouches, unsigned int maxTouches, bool endOutside)
1076 PanGestureDetector panGesture( GetPanGestureDetector() );
1078 mMinTouchesForPanning = minTouches;
1079 mMaxTouchesForPanning = maxTouches;
1083 panGesture.SetMinimumTouchesRequired(minTouches);
1084 panGesture.SetMaximumTouchesRequired(maxTouches);
1088 panGesture.SetMinimumTouchesRequired(1);
1089 panGesture.SetMaximumTouchesRequired(UINT_MAX);
1093 void ScrollView::SetActorAutoSnap(bool enable)
1095 mActorAutoSnapEnabled = enable;
1098 void ScrollView::SetAutoResize(bool enable)
1100 mAutoResizeContainerEnabled = enable;
1101 // TODO: This needs a lot of issues to be addressed before working.
1104 bool ScrollView::GetWrapMode() const
1109 void ScrollView::SetWrapMode(bool enable)
1112 Self().SetProperty(mPropertyWrap, enable);
1115 int ScrollView::GetRefreshInterval() const
1117 return mScrollUpdateDistance;
1120 void ScrollView::SetRefreshInterval(int milliseconds)
1122 mScrollUpdateDistance = milliseconds;
1125 int ScrollView::GetScrollUpdateDistance() const
1127 return mScrollUpdateDistance;
1130 void ScrollView::SetScrollUpdateDistance(int distance)
1132 mScrollUpdateDistance = distance;
1135 bool ScrollView::GetAxisAutoLock() const
1137 return mAxisAutoLock;
1140 void ScrollView::SetAxisAutoLock(bool enable)
1142 mAxisAutoLock = enable;
1143 UpdateMainInternalConstraint();
1146 float ScrollView::GetAxisAutoLockGradient() const
1148 return mAxisAutoLockGradient;
1151 void ScrollView::SetAxisAutoLockGradient(float gradient)
1153 DALI_ASSERT_DEBUG( gradient >= 0.0f && gradient <= 1.0f );
1154 mAxisAutoLockGradient = gradient;
1155 UpdateMainInternalConstraint();
1158 float ScrollView::GetFrictionCoefficient() const
1160 return mFrictionCoefficient;
1163 void ScrollView::SetFrictionCoefficient(float friction)
1165 DALI_ASSERT_DEBUG( friction > 0.0f );
1166 mFrictionCoefficient = friction;
1169 float ScrollView::GetFlickSpeedCoefficient() const
1171 return mFlickSpeedCoefficient;
1174 void ScrollView::SetFlickSpeedCoefficient(float speed)
1176 mFlickSpeedCoefficient = speed;
1179 float ScrollView::GetMaxFlickSpeed() const
1181 return mMaxFlickSpeed;
1184 void ScrollView::SetMaxFlickSpeed(float speed)
1186 mMaxFlickSpeed = speed;
1189 void ScrollView::SetMouseWheelScrollDistanceStep(Vector2 step)
1191 mMouseWheelScrollDistanceStep = step;
1194 Vector2 ScrollView::GetMouseWheelScrollDistanceStep() const
1196 return mMouseWheelScrollDistanceStep;
1199 unsigned int ScrollView::GetCurrentPage() const
1201 // in case animation is currently taking place.
1202 Vector3 position = GetPropertyPosition();
1204 Actor self = Self();
1205 unsigned int page = 0;
1206 unsigned int pagesPerVolume = 1;
1207 unsigned int volume = 0;
1209 // if rulerX is enabled, then get page count (columns)
1210 page = mRulerX->GetPageFromPosition(-position.x, mWrapMode);
1211 volume = mRulerY->GetPageFromPosition(-position.y, mWrapMode);
1212 pagesPerVolume = mRulerX->GetTotalPages();
1214 return volume * pagesPerVolume + page;
1217 Vector3 ScrollView::GetCurrentScrollPosition() const
1219 return -GetPropertyPosition();
1222 void ScrollView::SetScrollPosition(const Vector3& position)
1224 mScrollPrePosition = position;
1227 Vector3 ScrollView::GetCurrentScrollScale() const
1229 // in case animation is currently taking place.
1230 return GetPropertyScale();
1233 Vector3 ScrollView::GetDomainSize() const
1235 Vector3 size = Self().GetCurrentSize();
1237 const RulerDomain& xDomain = GetRulerX()->GetDomain();
1238 const RulerDomain& yDomain = GetRulerY()->GetDomain();
1240 Vector3 domainSize = Vector3( xDomain.max - xDomain.min, yDomain.max - yDomain.min, 0.0f ) - size;
1244 void ScrollView::TransformTo(const Vector3& position, const Vector3& scale, float rotation,
1245 DirectionBias horizontalBias, DirectionBias verticalBias)
1247 TransformTo(position, scale, rotation, mSnapDuration, horizontalBias, verticalBias);
1250 void ScrollView::TransformTo(const Vector3& position, const Vector3& scale, float rotation, float duration,
1251 DirectionBias horizontalBias, DirectionBias verticalBias)
1253 // Guard against destruction during signal emission
1254 // Note that Emit() methods are called indirectly e.g. from within ScrollView::AnimateTo()
1255 Toolkit::ScrollView handle( GetOwner() );
1257 Vector3 currentScrollPosition = GetCurrentScrollPosition();
1258 Self().SetProperty( mPropertyScrollStartPagePosition, currentScrollPosition );
1260 if(mScrolling) // are we interrupting a current scroll?
1262 // set mScrolling to false, in case user has code that interrogates mScrolling Getter() in complete.
1264 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignalV2 1 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
1265 mScrollCompletedSignalV2.Emit( currentScrollPosition );
1268 Self().SetProperty(mPropertyScrolling, true);
1270 mScrollStartedSignalV2.Emit( currentScrollPosition );
1271 bool animating = AnimateTo(-position,
1272 Vector3::ONE * duration,
1274 Vector3::ONE * duration,
1285 // if not animating, then this pan has completed right now.
1286 Self().SetProperty(mPropertyScrolling, false);
1288 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignalV2 2 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
1289 SetScrollUpdateNotification(false);
1290 mScrollCompletedSignalV2.Emit( currentScrollPosition );
1294 void ScrollView::ScrollTo(const Vector3& position)
1296 ScrollTo(position, mSnapDuration );
1299 void ScrollView::ScrollTo(const Vector3& position, float duration)
1301 ScrollTo(position, duration, DirectionBiasNone, DirectionBiasNone);
1304 void ScrollView::ScrollTo(const Vector3& position, float duration,
1305 DirectionBias horizontalBias, DirectionBias verticalBias)
1307 TransformTo(position, mScrollPostScale, mScrollPostRotation, duration, horizontalBias, verticalBias);
1310 void ScrollView::ScrollTo(unsigned int page)
1312 ScrollTo(page, mSnapDuration);
1315 void ScrollView::ScrollTo(unsigned int page, float duration, DirectionBias bias)
1318 unsigned int volume;
1319 unsigned int libraries;
1321 // The position to scroll to is continuous and linear
1322 // unless a domain has been enabled on the X axis.
1323 // or if WrapMode has been enabled.
1324 bool carryX = mRulerX->GetDomain().enabled | mWrapMode;
1325 bool carryY = mRulerY->GetDomain().enabled | mWrapMode;
1327 position.x = mRulerX->GetPositionFromPage(page, volume, carryX);
1328 position.y = mRulerY->GetPositionFromPage(volume, libraries, carryY);
1330 ScrollTo(position, duration, bias, bias);
1333 void ScrollView::ScrollTo(Actor &actor)
1335 ScrollTo(actor, mSnapDuration);
1338 void ScrollView::ScrollTo(Actor &actor, float duration)
1340 DALI_ASSERT_ALWAYS(actor.GetParent() == Self());
1342 Actor self = Self();
1343 Vector3 size = self.GetCurrentSize();
1344 Vector3 position = actor.GetCurrentPosition();
1345 position -= GetPropertyPrePosition();
1347 ScrollTo(Vector3(position.x - size.width * 0.5f, position.y - size.height * 0.5f, 0.0f), duration);
1350 Actor ScrollView::FindClosestActor()
1352 Actor self = Self();
1353 Vector3 size = self.GetCurrentSize();
1355 return FindClosestActorToPosition(Vector3(size.width * 0.5f,size.height * 0.5f,0.0f));
1358 Actor ScrollView::FindClosestActorToPosition(const Vector3& position, FindDirection dirX, FindDirection dirY, FindDirection dirZ)
1361 float closestDistance2 = 0.0f;
1362 Vector3 actualPosition = position;
1364 unsigned int numChildren = Self().GetChildCount();
1366 for(unsigned int i = 0; i < numChildren; ++i)
1368 Actor child = Self().GetChildAt(i);
1370 if(mInternalActor == child) // ignore internal actor.
1375 Vector3 childPosition = GetPositionOfAnchor(child, AnchorPoint::CENTER);
1377 Vector3 delta = childPosition - actualPosition;
1379 // X-axis checking (only find Actors to the [dirX] of actualPosition)
1380 if(dirX > All) // != All,None
1382 FindDirection deltaH = delta.x > 0 ? Right : Left;
1389 // Y-axis checking (only find Actors to the [dirY] of actualPosition)
1390 if(dirY > All) // != All,None
1392 FindDirection deltaV = delta.y > 0 ? Down : Up;
1399 // Z-axis checking (only find Actors to the [dirZ] of actualPosition)
1400 if(dirZ > All) // != All,None
1402 FindDirection deltaV = delta.y > 0 ? In : Out;
1409 // compare child to closest child in terms of distance.
1410 float distance2 = 0.0f;
1412 // distance2 = the Square of the relevant dimensions of delta
1415 distance2 += delta.x * delta.x;
1420 distance2 += delta.y * delta.y;
1425 distance2 += delta.z * delta.z;
1428 if(closestChild) // Next time.
1430 if(distance2 < closestDistance2)
1432 closestChild = child;
1433 closestDistance2 = distance2;
1438 closestChild = child;
1439 closestDistance2 = distance2;
1443 return closestChild;
1446 bool ScrollView::ScrollToSnapPoint()
1448 Vector2 stationaryVelocity = Vector2(0.0f, 0.0f);
1449 return SnapWithVelocity( stationaryVelocity );
1452 void ScrollView::ScaleTo(const Vector3& scale)
1454 ScaleTo(scale, mSnapDuration);
1457 void ScrollView::ScaleTo(const Vector3& scale, float duration)
1459 TransformTo(mScrollPostPosition, scale, mScrollPostRotation, duration);
1463 // TODO: In situations where axes are different (X snap, Y free)
1464 // Each axis should really have their own independent animation (time and equation)
1465 // Consider, X axis snapping to nearest grid point (EaseOut over fixed time)
1466 // Consider, Y axis simulating physics to arrive at a point (Physics equation over variable time)
1467 // Currently, the axes have been split however, they both use the same EaseOut equation.
1468 bool ScrollView::SnapWithVelocity(Vector2 velocity)
1470 // Animator takes over now, touches are assumed not to interfere.
1471 // And if touches do interfere, then we'll stop animation, update PrePosition
1472 // to current mScroll's properties, and then resume.
1473 // Note: For Flicking this may work a bit different...
1475 float angle = atan2(velocity.y, velocity.x);
1476 float speed2 = velocity.LengthSquared();
1477 AlphaFunction alphaFunction = mSnapAlphaFunction;
1478 Vector3 positionDuration = Vector3::ONE * mSnapDuration;
1479 Vector3 scaleDuration = Vector3::ONE * mSnapDuration;
1480 float rotationDuration = mSnapDuration;
1483 FindDirection horizontal = None;
1484 FindDirection vertical = None;
1486 // orthoAngleRange = Angle tolerance within the Exact N,E,S,W direction
1487 // that will be accepted as a general N,E,S,W flick direction.
1489 const float orthoAngleRange = FLICK_ORTHO_ANGLE_RANGE * M_PI / 180.0f;
1490 const float flickSpeedThreshold2 = FLICK_SPEED_THRESHOLD*FLICK_SPEED_THRESHOLD;
1492 Vector3 positionSnap = mScrollPrePosition;
1494 // Flick logic X Axis
1496 if(mRulerX->IsEnabled() && mLockAxis != LockHorizontal)
1500 if( speed2 > flickSpeedThreshold2 || // exceeds flick threshold
1501 mInAccessibilityPan ) // With AccessibilityPan its easier to move between snap positions
1503 if((angle >= -orthoAngleRange) && (angle < orthoAngleRange)) // Swiping East
1505 biasX = 0.0f, horizontal = Left;
1507 // This guards against an error where no movement occurs, due to the flick finishing
1508 // before the update-thread has advanced mScrollPostPosition past the the previous snap point.
1509 positionSnap.x += 1.0f;
1511 else if((angle >= M_PI-orthoAngleRange) || (angle < -M_PI+orthoAngleRange)) // Swiping West
1513 biasX = 1.0f, horizontal = Right;
1515 // This guards against an error where no movement occurs, due to the flick finishing
1516 // before the update-thread has advanced mScrollPostPosition past the the previous snap point.
1517 positionSnap.x -= 1.0f;
1522 // Flick logic Y Axis
1524 if(mRulerY->IsEnabled() && mLockAxis != LockVertical)
1528 if( speed2 > flickSpeedThreshold2 || // exceeds flick threshold
1529 mInAccessibilityPan ) // With AccessibilityPan its easier to move between snap positions
1531 if((angle >= M_PI_2-orthoAngleRange) && (angle < M_PI_2+orthoAngleRange)) // Swiping South
1533 biasY = 0.0f, vertical = Up;
1535 else if((angle >= -M_PI_2-orthoAngleRange) && (angle < -M_PI_2+orthoAngleRange)) // Swiping North
1537 biasY = 1.0f, vertical = Down;
1542 // isFlick: Whether this gesture is a flick or not.
1543 bool isFlick = (horizontal != All || vertical != All);
1544 // isFreeFlick: Whether this gesture is a flick under free panning criteria.
1545 bool isFreeFlick = velocity.LengthSquared() > (FREE_FLICK_SPEED_THRESHOLD*FREE_FLICK_SPEED_THRESHOLD);
1547 if(isFlick || isFreeFlick)
1549 positionDuration = Vector3::ONE * mFlickDuration;
1550 alphaFunction = mFlickAlphaFunction;
1553 // Calculate next positionSnap ////////////////////////////////////////////////////////////
1555 if(mActorAutoSnapEnabled)
1557 Vector3 size = Self().GetCurrentSize();
1559 Actor child = FindClosestActorToPosition( Vector3(size.width * 0.5f,size.height * 0.5f,0.0f), horizontal, vertical );
1561 if(!child && isFlick )
1563 // If we conducted a direction limited search and found no actor, then just snap to the closest actor.
1564 child = FindClosestActorToPosition( Vector3(size.width * 0.5f,size.height * 0.5f,0.0f) );
1569 Vector3 position = Self().GetProperty<Vector3>(mPropertyPosition);
1571 // Get center-point of the Actor.
1572 Vector3 childPosition = GetPositionOfAnchor(child, AnchorPoint::CENTER);
1574 if(mRulerX->IsEnabled())
1576 positionSnap.x = position.x - childPosition.x + size.width * 0.5f;
1578 if(mRulerY->IsEnabled())
1580 positionSnap.y = position.y - childPosition.y + size.height * 0.5f;
1585 Vector3 startPosition = positionSnap;
1586 positionSnap.x = -mRulerX->Snap(-positionSnap.x, biasX); // NOTE: X & Y rulers think in -ve coordinate system.
1587 positionSnap.y = -mRulerY->Snap(-positionSnap.y, biasY); // That is scrolling RIGHT (e.g. 100.0, 0.0) means moving LEFT.
1589 Vector3 clampDelta(Vector3::ZERO);
1590 ClampPosition(positionSnap);
1592 if( (mRulerX->GetType() == Ruler::Free || mRulerY->GetType() == Ruler::Free)
1593 && isFreeFlick && !mActorAutoSnapEnabled)
1595 // Calculate target position based on velocity of flick.
1597 // a = Deceleration (Set to diagonal stage length * friction coefficient)
1598 // u = Initial Velocity (Flick velocity)
1599 // v = 0 (Final Velocity)
1600 // t = Time (Velocity / Deceleration)
1601 Vector2 stageSize = Stage::GetCurrent().GetSize();
1602 float stageLength = Vector3(stageSize.x, stageSize.y, 0.0f).Length();
1603 float a = (stageLength * mFrictionCoefficient);
1604 Vector3 u = Vector3(velocity.x, velocity.y, 0.0f) * mFlickSpeedCoefficient;
1605 float speed = u.Length();
1608 // TODO: Change this to a decay function. (faster you flick, the slower it should be)
1609 speed = std::min(speed, stageLength * mMaxFlickSpeed );
1611 alphaFunction = ConstantDecelerationAlphaFunction;
1613 float t = speed / a;
1615 if(mRulerX->IsEnabled() && mRulerX->GetType() == Ruler::Free)
1617 positionSnap.x += t*u.x*0.5f;
1620 if(mRulerY->IsEnabled() && mRulerY->GetType() == Ruler::Free)
1622 positionSnap.y += t*u.y*0.5f;
1625 clampDelta = positionSnap;
1626 ClampPosition(positionSnap);
1627 if((positionSnap - startPosition).LengthSquared() > Math::MACHINE_EPSILON_0)
1629 clampDelta -= positionSnap;
1630 clampDelta.x = clampDelta.x > 0.0f ? std::min(clampDelta.x, mMaxOvershoot.x) : std::max(clampDelta.x, -mMaxOvershoot.x);
1631 clampDelta.y = clampDelta.y > 0.0f ? std::min(clampDelta.y, mMaxOvershoot.y) : std::max(clampDelta.y, -mMaxOvershoot.y);
1635 clampDelta = Vector3::ZERO;
1638 // If Axis is Free and has velocity, then calculate time taken
1639 // to reach target based on velocity in axis.
1640 if(mRulerX->IsEnabled() && mRulerX->GetType() == Ruler::Free)
1642 float deltaX = fabsf(startPosition.x - positionSnap.x);
1644 if(fabsf(u.x) > Math::MACHINE_EPSILON_1)
1646 positionDuration.x = fabsf(deltaX / u.x);
1650 positionDuration.x = 0;
1654 if(mRulerY->IsEnabled() && mRulerY->GetType() == Ruler::Free)
1656 float deltaY = fabsf(startPosition.y - positionSnap.y);
1658 if(fabsf(u.y) > Math::MACHINE_EPSILON_1)
1660 positionDuration.y = fabsf(deltaY / u.y);
1664 positionDuration.y = 0;
1668 positionSnap += clampDelta;
1670 // Scale Snap ///////////////////////////////////////////////////////////////
1671 Vector3 scaleSnap = mScrollPostScale;
1673 scaleSnap.x = mRulerScaleX->Snap(scaleSnap.x);
1674 scaleSnap.y = mRulerScaleY->Snap(scaleSnap.y);
1676 ClampScale(scaleSnap);
1678 // Rotation Snap ////////////////////////////////////////////////////////////
1679 float rotationSnap = mScrollPostRotation;
1680 // TODO: implement rotation snap
1682 bool animating = AnimateTo(positionSnap, positionDuration,
1683 scaleSnap, scaleDuration,
1684 rotationSnap, rotationDuration,
1685 alphaFunction, false,
1686 DirectionBiasNone, DirectionBiasNone,
1687 isFlick || isFreeFlick ? Flick : Snap);
1692 void ScrollView::StopAnimation(void)
1694 // Clear Snap animation if exists.
1695 StopAnimation(mSnapAnimation);
1696 StopAnimation(mInternalXAnimation);
1697 StopAnimation(mInternalYAnimation);
1698 mScrollStateFlags = 0;
1699 // remove scroll animation flags
1700 HandleStoppedAnimation();
1703 void ScrollView::StopAnimation(Animation& animation)
1712 bool ScrollView::AnimateTo(const Vector3& position, const Vector3& positionDuration,
1713 const Vector3& scale, const Vector3& scaleDuration,
1714 float rotation, float rotationDuration,
1715 AlphaFunction alpha, bool findShortcuts,
1716 DirectionBias horizontalBias, DirectionBias verticalBias,
1719 // Here we perform an animation on a number of properties (depending on which have changed)
1720 // The animation is applied to all ScrollBases
1721 Actor self = Self();
1722 mScrollTargetPosition = position;
1723 float totalDuration = 0.0f;
1725 bool positionChanged = (mScrollTargetPosition != mScrollPostPosition);
1726 bool scaleChanged = (scale != mScrollPostScale);
1727 bool rotationChanged = fabsf(rotation - mScrollPostRotation) > Math::MACHINE_EPSILON_0;
1731 totalDuration = std::max(totalDuration, positionDuration.x);
1732 totalDuration = std::max(totalDuration, positionDuration.y);
1736 // try to animate for a frame, on some occasions update will be changing scroll value while event side thinks it hasnt changed
1737 totalDuration = 0.01f;
1738 positionChanged = true;
1743 totalDuration = std::max(totalDuration, scaleDuration.x);
1744 totalDuration = std::max(totalDuration, scaleDuration.y);
1749 totalDuration = std::max(totalDuration, rotationDuration);
1753 // Position Delta ///////////////////////////////////////////////////////
1756 if(mWrapMode && findShortcuts)
1758 // In Wrap Mode, the shortest distance is a little less intuitive...
1759 const RulerDomain rulerDomainX = mRulerX->GetDomain();
1760 const RulerDomain rulerDomainY = mRulerY->GetDomain();
1762 if(mRulerX->IsEnabled())
1764 float dir = VectorInDomain(-mScrollPostPosition.x, -mScrollTargetPosition.x, rulerDomainX.min, rulerDomainX.max, horizontalBias);
1765 mScrollTargetPosition.x = mScrollPostPosition.x + -dir;
1768 if(mRulerY->IsEnabled())
1770 float dir = VectorInDomain(-mScrollPostPosition.y, -mScrollTargetPosition.y, rulerDomainY.min, rulerDomainY.max, verticalBias);
1771 mScrollTargetPosition.y = mScrollPostPosition.y + -dir;
1775 // note we have two separate animations for X & Y, this deals with sliding diagonally and hitting
1776 // a horizonal/vertical wall.delay
1777 AnimateInternalXTo(mScrollTargetPosition.x, positionDuration.x, alpha);
1778 AnimateInternalYTo(mScrollTargetPosition.y, positionDuration.y, alpha);
1780 if( !(mScrollStateFlags & SCROLL_ANIMATION_FLAGS) )
1782 self.SetProperty(mPropertyPrePosition, mScrollTargetPosition);
1783 mScrollPrePosition = mScrollTargetPosition;
1787 // Scale Delta ///////////////////////////////////////////////////////
1790 if(totalDuration > Math::MACHINE_EPSILON_1)
1792 mSnapAnimation = Animation::New(totalDuration);
1793 mSnapAnimation.FinishedSignal().Connect(this, &ScrollView::OnScrollAnimationFinished);
1794 // TODO: for non-uniform scaling to different bounds e.g. scaling a square to a 4:3 aspect ratio screen with a velocity
1795 // the height will hit first, and then the width, so that would require two different animation times just like position.
1796 mSnapAnimation.AnimateTo( Property(self, mPropertyScale), scale, alpha, TimePeriod(0.0f, scaleDuration.x));
1798 mSnapAnimation.AnimateTo( Property(self, mPropertyTime), totalDuration, AlphaFunctions::Linear );
1799 mSnapAnimation.Play();
1803 self.SetProperty(mPropertyScale, scale);
1805 mScrollPreScale = mScrollPostScale = scale;
1808 SetScrollUpdateNotification(true);
1810 // Always send a snap event when AnimateTo is called.
1811 Toolkit::ScrollView::SnapEvent snapEvent;
1812 snapEvent.type = snapType;
1813 snapEvent.position = -mScrollTargetPosition;
1814 snapEvent.scale = scale;
1815 snapEvent.rotation = rotation;
1816 snapEvent.duration = totalDuration;
1818 mSnapStartedSignalV2.Emit( snapEvent );
1820 return (mScrollStateFlags & SCROLL_ANIMATION_FLAGS) != 0;
1823 void ScrollView::SetOvershootEnabled(bool enabled)
1825 if(enabled && !mOvershootIndicator)
1827 mOvershootIndicator = ScrollOvershootIndicator::New();
1831 mMaxOvershoot = OVERSCROLL_CLAMP;
1832 mOvershootIndicator->AttachToScrollable(*this);
1836 mMaxOvershoot = mUserMaxOvershoot;
1837 mOvershootIndicator->DetachFromScrollable(*this);
1839 UpdateMainInternalConstraint();
1842 void ScrollView::AddOverlay(Actor actor)
1844 mInternalActor.Add( actor );
1847 void ScrollView::RemoveOverlay(Actor actor)
1849 mInternalActor.Remove( actor );
1852 void ScrollView::SetScrollingDirection( Radian direction, Radian threshold )
1854 PanGestureDetector panGesture( GetPanGestureDetector() );
1856 // First remove just in case we have some set, then add.
1857 panGesture.RemoveDirection( direction );
1858 panGesture.AddDirection( direction, threshold );
1861 void ScrollView::RemoveScrollingDirection( Radian direction )
1863 PanGestureDetector panGesture( GetPanGestureDetector() );
1864 panGesture.RemoveDirection( direction );
1867 Toolkit::ScrollView::SnapStartedSignalV2& ScrollView::SnapStartedSignal()
1869 return mSnapStartedSignalV2;
1872 void ScrollView::FindAndUnbindActor(Actor child)
1877 Vector3 ScrollView::GetPropertyPrePosition() const
1879 Vector3 position = Self().GetProperty<Vector3>(mPropertyPrePosition);
1880 WrapPosition(position);
1884 Vector3 ScrollView::GetPropertyPosition() const
1886 Vector3 position = Self().GetProperty<Vector3>(mPropertyPosition);
1887 WrapPosition(position);
1892 Vector3 ScrollView::GetPropertyScale() const
1894 return Self().GetProperty<Vector3>(mPropertyScale);
1897 void ScrollView::HandleStoppedAnimation()
1899 SetScrollUpdateNotification(false);
1902 void ScrollView::HandleSnapAnimationFinished()
1904 // Emit Signal that scrolling has completed.
1906 Actor self = Self();
1907 self.SetProperty(mPropertyScrolling, false);
1909 Vector3 deltaPosition(mScrollPrePosition);
1911 UpdateLocalScrollProperties();
1912 WrapPosition(mScrollPrePosition);
1913 self.SetProperty(mPropertyPrePosition, mScrollPrePosition);
1915 Vector3 currentScrollPosition = GetCurrentScrollPosition();
1916 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignalV2 3 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
1917 mScrollCompletedSignalV2.Emit( currentScrollPosition );
1919 mDomainOffset += deltaPosition - mScrollPostPosition;
1920 self.SetProperty(mPropertyDomainOffset, mDomainOffset);
1921 HandleStoppedAnimation();
1924 void ScrollView::SetScrollUpdateNotification( bool enabled )
1926 Actor self = Self();
1927 if( mScrollXUpdateNotification )
1929 // disconnect now to avoid a notification before removed from update thread
1930 mScrollXUpdateNotification.NotifySignal().Disconnect(this, &ScrollView::OnScrollUpdateNotification);
1931 self.RemovePropertyNotification(mScrollXUpdateNotification);
1932 mScrollXUpdateNotification.Reset();
1936 mScrollXUpdateNotification = self.AddPropertyNotification(mPropertyPosition, 0, StepCondition(mScrollUpdateDistance, 0.0f));
1937 mScrollXUpdateNotification.NotifySignal().Connect( this, &ScrollView::OnScrollUpdateNotification );
1939 if( mScrollYUpdateNotification )
1941 // disconnect now to avoid a notification before removed from update thread
1942 mScrollYUpdateNotification.NotifySignal().Disconnect(this, &ScrollView::OnScrollUpdateNotification);
1943 self.RemovePropertyNotification(mScrollYUpdateNotification);
1944 mScrollYUpdateNotification.Reset();
1948 mScrollYUpdateNotification = self.AddPropertyNotification(mPropertyPosition, 1, StepCondition(mScrollUpdateDistance, 0.0f));
1949 mScrollYUpdateNotification.NotifySignal().Connect( this, &ScrollView::OnScrollUpdateNotification );
1953 void ScrollView::OnScrollUpdateNotification(Dali::PropertyNotification& source)
1955 // Guard against destruction during signal emission
1956 Toolkit::ScrollView handle( GetOwner() );
1958 Vector3 currentScrollPosition = GetCurrentScrollPosition();
1959 mScrollUpdatedSignalV2.Emit( currentScrollPosition );
1962 bool ScrollView::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
1964 Dali::BaseHandle handle( object );
1966 bool connected( true );
1967 Toolkit::ScrollView view = Toolkit::ScrollView::DownCast( handle );
1969 if( Toolkit::ScrollView::SIGNAL_SNAP_STARTED == signalName )
1971 view.SnapStartedSignal().Connect( tracker, functor );
1975 // signalName does not match any signal
1982 void ScrollView::OnSizeAnimation(Animation& animation, const Vector3& targetSize)
1984 // need to update domain properties for new size
1985 UpdatePropertyDomain(targetSize);
1988 void ScrollView::OnControlSizeSet( const Vector3& size )
1990 // need to update domain properties for new size
1991 if( mDefaultMaxOvershoot )
1993 mUserMaxOvershoot.x = size.x * 0.5f;
1994 mUserMaxOvershoot.y = size.y * 0.5f;
1995 if( !IsScrollComponentEnabled(Toolkit::Scrollable::OvershootIndicator) )
1997 mMaxOvershoot = mUserMaxOvershoot;
2000 UpdatePropertyDomain(size);
2001 UpdateMainInternalConstraint();
2002 if( IsScrollComponentEnabled(Toolkit::Scrollable::OvershootIndicator) )
2004 mOvershootIndicator->Reset();
2008 void ScrollView::OnChildAdd(Actor& child)
2016 void ScrollView::OnChildRemove(Actor& child)
2018 // TODO: Actor needs a RemoveConstraint method to take out an individual constraint.
2022 void ScrollView::OnPropertySet( Property::Index index, Property::Value propertyValue )
2024 Actor self = Self();
2025 if( index == mPropertyX )
2027 self.GetProperty(mPropertyPrePosition).Get(mScrollPrePosition);
2028 propertyValue.Get(mScrollPrePosition.x);
2029 self.SetProperty(mPropertyPrePosition, mScrollPrePosition);
2031 else if( index == mPropertyY )
2033 self.GetProperty(mPropertyPrePosition).Get(mScrollPrePosition);
2034 propertyValue.Get(mScrollPrePosition.y);
2035 self.SetProperty(mPropertyPrePosition, mScrollPrePosition);
2037 else if( index == mPropertyPrePosition )
2039 DALI_LOG_SCROLL_STATE("[0x%X]", this);
2040 propertyValue.Get(mScrollPrePosition);
2044 void ScrollView::StartTouchDownTimer()
2046 if ( !mTouchDownTimer )
2048 mTouchDownTimer = Timer::New( TOUCH_DOWN_TIMER_INTERVAL );
2049 mTouchDownTimer.TickSignal().Connect( this, &ScrollView::OnTouchDownTimeout );
2052 mTouchDownTimer.Start();
2055 void ScrollView::StopTouchDownTimer()
2057 if ( mTouchDownTimer )
2059 mTouchDownTimer.Stop();
2063 bool ScrollView::OnTouchDownTimeout()
2065 mTouchDownTimeoutReached = true;
2067 if( mScrollStateFlags & (SCROLL_ANIMATION_FLAGS | SNAP_ANIMATION_FLAGS) )
2070 if( mScrollStateFlags & SCROLL_ANIMATION_FLAGS )
2072 mScrollInterrupted = true;
2073 // reset domain offset as scrolling from original plane.
2074 mDomainOffset = Vector3::ZERO;
2075 Self().SetProperty(mPropertyDomainOffset, Vector3::ZERO);
2077 UpdateLocalScrollProperties();
2078 Vector3 currentScrollPosition = GetCurrentScrollPosition();
2079 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignalV2 4 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
2080 mScrollCompletedSignalV2.Emit( currentScrollPosition );
2087 bool ScrollView::OnTouchEvent(const TouchEvent& event)
2091 // Ignore this touch event, if scrollview is insensitive.
2095 // Ignore events with multiple-touch points
2096 if (event.GetPointCount() != 1)
2101 if( event.GetPoint(0).state == TouchPoint::Down )
2103 if(mGestureStackDepth==0)
2105 mTouchDownTime = event.time;
2107 // This allows time for a pan-gesture to start, to avoid breaking snap-animation behavior with fast flicks.
2108 // If touch-down does not become a pan (after timeout interval), then snap-animation can be interrupted.
2109 StartTouchDownTimer();
2112 else if( event.GetPoint(0).state == TouchPoint::Up )
2114 StopTouchDownTimer();
2116 // if the user touches and releases without enough movement to go
2117 // into a gesture state, then we should snap to nearest point.
2118 // otherwise our scroll could be stopped (interrupted) half way through an animation.
2119 if(mGestureStackDepth==0 && mTouchDownTimeoutReached)
2121 unsigned timeDelta( event.time - mTouchDownTime );
2122 if ( timeDelta >= MINIMUM_TIME_BETWEEN_DOWN_AND_UP_FOR_RESET )
2124 // Reset the velocity only if down was received a while ago
2125 mLastVelocity = Vector2( 0.0f, 0.0f );
2128 UpdateLocalScrollProperties();
2129 // Only finish the transform if scrolling was interrupted on down or if we are scrolling
2130 if ( mScrollInterrupted || mScrolling )
2135 mTouchDownTimeoutReached = false;
2136 mScrollInterrupted = false;
2142 bool ScrollView::OnMouseWheelEvent(const MouseWheelEvent& event)
2146 // Ignore this mouse wheel event, if scrollview is insensitive.
2150 Vector3 targetScrollPosition = GetPropertyPosition();
2152 if(mRulerX->IsEnabled() && !mRulerY->IsEnabled())
2154 // If only the ruler in the X axis is enabled, scroll in the X axis.
2155 if(mRulerX->GetType() == Ruler::Free)
2157 // Free panning mode
2158 targetScrollPosition.x += event.z * mMouseWheelScrollDistanceStep.x;
2159 ClampPosition(targetScrollPosition);
2160 ScrollTo(-targetScrollPosition);
2162 else if(!mScrolling)
2164 // Snap mode, only respond to the event when the previous snap animation is finished.
2165 ScrollTo(GetCurrentPage() - event.z);
2170 // If the ruler in the Y axis is enabled, scroll in the Y axis.
2171 if(mRulerY->GetType() == Ruler::Free)
2173 // Free panning mode
2174 targetScrollPosition.y += event.z * mMouseWheelScrollDistanceStep.y;
2175 ClampPosition(targetScrollPosition);
2176 ScrollTo(-targetScrollPosition);
2178 else if(!mScrolling)
2180 // Snap mode, only respond to the event when the previous snap animation is finished.
2181 ScrollTo(GetCurrentPage() - event.z * mRulerX->GetTotalPages());
2188 void ScrollView::ResetScrolling()
2190 Actor self = Self();
2191 self.GetProperty(mPropertyPosition).Get(mScrollPostPosition);
2192 mScrollPrePosition = mScrollPostPosition;
2193 self.SetProperty(mPropertyPrePosition, mScrollPostPosition);
2196 void ScrollView::UpdateLocalScrollProperties()
2198 Actor self = Self();
2199 self.GetProperty(mPropertyPrePosition).Get(mScrollPrePosition);
2200 self.GetProperty(mPropertyPosition).Get(mScrollPostPosition);
2203 // private functions
2205 void ScrollView::PreAnimatedScrollSetup()
2207 // mPropertyPrePosition is our unclamped property with wrapping
2208 // mPropertyPosition is our final scroll position after clamping
2210 Actor self = Self();
2212 Vector3 deltaPosition(mScrollPostPosition);
2213 WrapPosition(mScrollPostPosition);
2214 mDomainOffset += deltaPosition - mScrollPostPosition;
2215 Self().SetProperty(mPropertyDomainOffset, mDomainOffset);
2217 if( mScrollStateFlags & SCROLL_X_STATE_MASK )
2219 // already performing animation on internal x position
2220 StopAnimation(mInternalXAnimation);
2223 if( mScrollStateFlags & SCROLL_Y_STATE_MASK )
2225 // already performing animation on internal y position
2226 StopAnimation(mInternalYAnimation);
2229 mScrollStateFlags = 0;
2231 mScrollPostScale = GetPropertyScale();
2233 // Update Actor position with this wrapped value.
2236 mScrollPreScale = mScrollPostScale;
2237 mScrollPreRotation = mScrollPostRotation;
2240 void ScrollView::FinaliseAnimatedScroll()
2242 // TODO - common animation finishing code in here
2245 void ScrollView::AnimateInternalXTo( float position, float duration, AlphaFunction alpha )
2247 StopAnimation(mInternalXAnimation);
2249 if( duration > Math::MACHINE_EPSILON_10 )
2251 Actor self = Self();
2252 mInternalXAnimation = Animation::New(duration);
2253 mInternalXAnimation.FinishedSignal().Connect(this, &ScrollView::OnScrollAnimationFinished);
2254 mInternalXAnimation.AnimateTo( Property(self, mPropertyPrePosition, 0), position, alpha, duration);
2255 mInternalXAnimation.Play();
2257 // erase current state flags
2258 mScrollStateFlags &= ~SCROLL_X_STATE_MASK;
2259 // add internal animation state flag
2260 mScrollStateFlags |= AnimatingInternalX;
2264 void ScrollView::AnimateInternalYTo( float position, float duration, AlphaFunction alpha )
2266 StopAnimation(mInternalYAnimation);
2268 if( duration > Math::MACHINE_EPSILON_10 )
2270 Actor self = Self();
2271 mInternalYAnimation = Animation::New(duration);
2272 mInternalYAnimation.FinishedSignal().Connect(this, &ScrollView::OnScrollAnimationFinished);
2273 mInternalYAnimation.AnimateTo( Property(self, mPropertyPrePosition, 1), position, alpha, TimePeriod(duration));
2274 mInternalYAnimation.Play();
2276 // erase current state flags
2277 mScrollStateFlags &= ~SCROLL_Y_STATE_MASK;
2278 // add internal animation state flag
2279 mScrollStateFlags |= AnimatingInternalY;
2283 void ScrollView::OnScrollAnimationFinished( Animation& source )
2285 // Guard against destruction during signal emission
2286 // Note that ScrollCompletedSignal is emitted from HandleSnapAnimationFinished()
2287 Toolkit::ScrollView handle( GetOwner() );
2289 bool scrollingFinished = false;
2291 // update our local scroll positions
2292 UpdateLocalScrollProperties();
2294 if( source == mSnapAnimation )
2296 // generic snap animation used for scaling and rotation
2297 mSnapAnimation.Reset();
2300 if( source == mInternalXAnimation )
2302 if( !(mScrollStateFlags & AnimatingInternalY) )
2304 scrollingFinished = true;
2306 mInternalXAnimation.Reset();
2307 SnapInternalXTo(mScrollPostPosition.x);
2310 if( source == mInternalYAnimation )
2312 if( !(mScrollStateFlags & AnimatingInternalX) )
2314 scrollingFinished = true;
2316 mInternalYAnimation.Reset();
2317 SnapInternalYTo(mScrollPostPosition.y);
2320 if(scrollingFinished)
2322 HandleSnapAnimationFinished();
2326 void ScrollView::OnSnapInternalPositionFinished( Animation& source )
2328 Actor self = Self();
2329 UpdateLocalScrollProperties();
2330 if( source == mInternalXAnimation )
2332 // clear internal x animation flags
2333 mScrollStateFlags &= ~SCROLL_X_STATE_MASK;
2334 mInternalXAnimation.Reset();
2335 WrapPosition(mScrollPrePosition);
2337 if( source == mInternalYAnimation )
2339 mScrollStateFlags &= ~SCROLL_Y_STATE_MASK;
2340 mInternalYAnimation.Reset();
2341 WrapPosition(mScrollPrePosition);
2345 void ScrollView::SnapInternalXTo(float position)
2347 Actor self = Self();
2349 StopAnimation(mInternalXAnimation);
2351 // erase current state flags
2352 mScrollStateFlags &= ~SCROLL_X_STATE_MASK;
2354 // if internal x not equal to inputed parameter, animate it
2355 float duration = std::min(fabsf((position - mScrollPrePosition.x) / mMaxOvershoot.x) * mSnapOvershootDuration, mSnapOvershootDuration);
2356 if( duration > Math::MACHINE_EPSILON_1 )
2358 mInternalXAnimation = Animation::New(duration);
2359 mInternalXAnimation.FinishedSignal().Connect(this, &ScrollView::OnSnapInternalPositionFinished);
2360 mInternalXAnimation.AnimateTo(Property(self, mPropertyPrePosition, 0), position);
2361 mInternalXAnimation.Play();
2363 // add internal animation state flag
2364 mScrollStateFlags |= SnappingInternalX;
2368 void ScrollView::SnapInternalYTo(float position)
2370 Actor self = Self();
2372 StopAnimation(mInternalYAnimation);
2374 // erase current state flags
2375 mScrollStateFlags &= ~SCROLL_Y_STATE_MASK;
2377 // if internal y not equal to inputed parameter, animate it
2378 float duration = std::min(fabsf((position - mScrollPrePosition.y) / mMaxOvershoot.y) * mSnapOvershootDuration, mSnapOvershootDuration);
2379 if( duration > Math::MACHINE_EPSILON_1 )
2381 mInternalYAnimation = Animation::New(duration);
2382 mInternalYAnimation.FinishedSignal().Connect(this, &ScrollView::OnSnapInternalPositionFinished);
2383 mInternalYAnimation.AnimateTo(Property(self, mPropertyPrePosition, 1), position);
2384 mInternalYAnimation.Play();
2386 // add internal animation state flag
2387 mScrollStateFlags |= SnappingInternalY;
2391 void ScrollView::GestureStarted()
2393 // we handle the first gesture.
2394 // if we're currently doing a gesture and receive another
2395 // we continue and combine the effects of the gesture instead of reseting.
2396 if(mGestureStackDepth++==0)
2398 Actor self = Self();
2399 StopTouchDownTimer();
2401 mPanDelta = Vector3::ZERO;
2402 mScaleDelta = Vector3::ONE;
2403 mRotationDelta = 0.0f;
2404 mLastVelocity = Vector2(0.0f, 0.0f);
2407 mLockAxis = LockPossible;
2410 if( mScrollStateFlags & SCROLL_X_STATE_MASK )
2412 StopAnimation(mInternalXAnimation);
2414 if( mScrollStateFlags & SCROLL_Y_STATE_MASK )
2416 StopAnimation(mInternalYAnimation);
2418 mScrollStateFlags = 0;
2420 if(mScrolling) // are we interrupting a current scroll?
2422 // set mScrolling to false, in case user has code that interrogates mScrolling Getter() in complete.
2424 // send negative scroll position since scroll internal scroll position works as an offset for actors,
2425 // give applications the position within the domain from the scroll view's anchor position
2426 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignalV2 5 [%.2f, %.2f]", this, -mScrollPostPosition.x, -mScrollPostPosition.y);
2427 mScrollCompletedSignalV2.Emit( -mScrollPostPosition );
2432 void ScrollView::GestureContinuing(const Vector2& panDelta, const Vector2& scaleDelta, float rotationDelta)
2434 mPanDelta.x+= panDelta.x;
2435 mPanDelta.y+= panDelta.y;
2436 mScaleDelta.x*= scaleDelta.x;
2437 mScaleDelta.y*= scaleDelta.y;
2438 mRotationDelta+= rotationDelta;
2440 // Save the velocity, there is a bug in PanGesture
2441 // Whereby the Gesture::Finished's velocity is either:
2442 // NaN (due to time delta of zero between the last two events)
2443 // or 0 (due to position being the same between the last two events)
2445 // Axis Auto Lock - locks the panning to the horizontal or vertical axis if the pan
2446 // appears mostly horizontal or mostly vertical respectively.
2449 mLockAxis = GetLockAxis(mPanDelta.GetVectorXY(), mLockAxis, mAxisAutoLockGradient);
2450 } // end if mAxisAutoLock
2453 // TODO: Upgrade to use a more powerful gesture detector (one that supports multiple touches on pan - so works as pan and flick gesture)
2454 // TODO: Reimplement Scaling (pinching 2+ points)
2455 // TODO: Reimplment Rotation (pinching 2+ points)
2456 // BUG: Gesture::Finished doesn't always return velocity on release (due to
2457 // timeDelta between last two events being 0 sometimes, or posiiton being the same)
2458 void ScrollView::OnPan(PanGesture gesture)
2460 // Guard against destruction during signal emission
2461 // Note that Emit() methods are called indirectly e.g. from within ScrollView::OnGestureEx()
2462 Actor self( Self() );
2466 // If another callback on the same original signal disables sensitivity,
2467 // this callback will still be called, so we must suppress it.
2471 // translate Gesture input to get useful data...
2472 switch(gesture.state)
2474 case Gesture::Started:
2476 UpdateLocalScrollProperties();
2479 self.SetProperty( mPropertyPanning, true );
2480 self.SetProperty( mPropertyScrollStartPagePosition, Vector3(gesture.position.x, gesture.position.y, 0.0f) );
2482 UpdateMainInternalConstraint();
2486 case Gesture::Continuing:
2488 GestureContinuing(gesture.screenDisplacement, Vector2::ZERO, 0.0f);
2492 case Gesture::Finished:
2493 case Gesture::Cancelled:
2495 UpdateLocalScrollProperties();
2496 mLastVelocity = gesture.velocity;
2498 self.SetProperty( mPropertyPanning, false );
2500 if( mScrollMainInternalPrePositionConstraint )
2502 self.RemoveConstraint(mScrollMainInternalPrePositionConstraint);
2507 case Gesture::Possible:
2508 case Gesture::Clear:
2510 // Nothing to do, not needed.
2514 } // end switch(gesture.state)
2516 OnGestureEx(gesture.state);
2519 void ScrollView::OnGestureEx(Gesture::State state)
2521 // call necessary signals for application developer
2523 if(state == Gesture::Started)
2525 Vector3 currentScrollPosition = GetCurrentScrollPosition();
2526 Self().SetProperty(mPropertyScrolling, true);
2528 mScrollStartedSignalV2.Emit( currentScrollPosition );
2530 else if( (state == Gesture::Finished) ||
2531 (state == Gesture::Cancelled) ) // Finished/default
2533 // when all the gestures have finished, we finish the transform.
2534 // so if a user decides to pan (1 gesture), and then pan+zoom (2 gestures)
2535 // then stop panning (back to 1 gesture), and then stop zooming (0 gestures).
2536 // this is the point we end, and perform necessary snapping.
2537 mGestureStackDepth--;
2538 if(mGestureStackDepth==0)
2545 void ScrollView::UpdateTransform()
2547 // TODO: notify clamps using property notifications (or see if we need this, can deprecate it)
2550 void ScrollView::FinishTransform()
2552 // at this stage internal x and x scroll position should have followed prescroll position exactly
2553 Actor self = Self();
2555 PreAnimatedScrollSetup();
2557 bool animating = SnapWithVelocity(mLastVelocity * 1000.0f);
2561 // if not animating, then this pan has completed right now.
2562 SetScrollUpdateNotification(false);
2564 Self().SetProperty(mPropertyScrolling, false);
2565 Vector3 currentScrollPosition = GetCurrentScrollPosition();
2566 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignalV2 6 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
2567 mScrollCompletedSignalV2.Emit( currentScrollPosition );
2571 Vector3 ScrollView::GetOvershoot(Vector3& position) const
2573 Vector3 size = Self().GetCurrentSize();
2576 const RulerDomain rulerDomainX = mRulerX->GetDomain();
2577 const RulerDomain rulerDomainY = mRulerY->GetDomain();
2579 if(mRulerX->IsEnabled() && rulerDomainX.enabled)
2581 const float left = rulerDomainX.min - position.x;
2582 const float right = size.width - rulerDomainX.max - position.x;
2589 overshoot.x = right;
2593 if(mRulerY->IsEnabled() && rulerDomainY.enabled)
2595 const float top = rulerDomainY.min - position.y;
2596 const float bottom = size.height - rulerDomainY.max - position.y;
2603 overshoot.y = bottom;
2610 bool ScrollView::OnAccessibilityPan(PanGesture gesture)
2612 // Keep track of whether this is an AccessibilityPan
2613 mInAccessibilityPan = true;
2615 mInAccessibilityPan = false;
2620 void ScrollView::ClampPosition(Vector3& position) const
2622 ClampState3 clamped;
2623 ClampPosition(position, clamped);
2626 void ScrollView::ClampPosition(Vector3& position, ClampState3 &clamped) const
2628 Vector3 size = Self().GetCurrentSize();
2630 // determine size of viewport relative to current scaled size.
2631 // e.g. if you're zoomed in 200%, then each pixel on screen is only 0.5 pixels on subject.
2632 if(fabsf(mScrollPostScale.x) > Math::MACHINE_EPSILON_0)
2634 size.x /= mScrollPostScale.x;
2637 if(fabsf(mScrollPostScale.y) > Math::MACHINE_EPSILON_0)
2639 size.y /= mScrollPostScale.y;
2642 position.x = -mRulerX->Clamp(-position.x, size.width, 1.0f, clamped.x); // NOTE: X & Y rulers think in -ve coordinate system.
2643 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.
2645 clamped.z = NotClamped;
2648 void ScrollView::WrapPosition(Vector3& position) const
2652 const RulerDomain rulerDomainX = mRulerX->GetDomain();
2653 const RulerDomain rulerDomainY = mRulerY->GetDomain();
2655 if(mRulerX->IsEnabled())
2657 position.x = -WrapInDomain(-position.x, rulerDomainX.min, rulerDomainX.max);
2660 if(mRulerY->IsEnabled())
2662 position.y = -WrapInDomain(-position.y, rulerDomainY.min, rulerDomainY.max);
2667 void ScrollView::ClampScale(Vector3& scale) const
2669 ClampState3 clamped;
2670 ClampScale(scale, clamped);
2673 void ScrollView::ClampScale(Vector3& scale, ClampState3 &clamped) const
2675 scale.x = mRulerScaleX->Clamp(scale.x, 0.0f, 1.0f, clamped.x);
2676 scale.y = mRulerScaleY->Clamp(scale.y, 0.0f, 1.0f, clamped.y);
2677 clamped.z = NotClamped;
2680 void ScrollView::UpdateMainInternalConstraint()
2682 // TODO: Only update the constraints which have changed, rather than remove all and add all again.
2683 // Requires a dali-core ApplyConstraintAt, or a ReplaceConstraint. The former is probably more flexible.
2684 Actor self = Self();
2685 PanGestureDetector detector( GetPanGestureDetector() );
2687 if(mScrollMainInternalPositionConstraint)
2689 self.RemoveConstraint(mScrollMainInternalPositionConstraint);
2690 self.RemoveConstraint(mScrollMainInternalDeltaConstraint);
2691 self.RemoveConstraint(mScrollMainInternalFinalConstraint);
2692 self.RemoveConstraint(mScrollMainInternalRelativeConstraint);
2693 self.RemoveConstraint(mScrollMainInternalXConstraint);
2694 self.RemoveConstraint(mScrollMainInternalYConstraint);
2696 if( mScrollMainInternalPrePositionConstraint )
2698 self.RemoveConstraint(mScrollMainInternalPrePositionConstraint);
2701 // TODO: It's probably better to use a local displacement value as this will give a displacement when scrolling just commences
2702 // but we need to make sure than the gesture system gives displacement since last frame (60Hz), not displacement since last touch event (90Hz).
2704 // 1. First calculate the pre-position (this is the scroll position if no clamping has taken place)
2705 Vector2 initialPanMask = Vector2(mRulerX->IsEnabled() ? 1.0f : 0.0f, mRulerY->IsEnabled() ? 1.0f : 0.0f);
2707 if( mLockAxis == LockVertical )
2709 initialPanMask.y = 0.0f;
2711 else if( mLockAxis == LockHorizontal )
2713 initialPanMask.x = 0.0f;
2715 Constraint constraint;
2719 constraint = Constraint::New<Vector3>( mPropertyPrePosition,
2720 Source( detector, PanGestureDetector::LOCAL_POSITION ),
2721 Source( detector, PanGestureDetector::LOCAL_DISPLACEMENT ),
2722 Source( self, Actor::SIZE ),
2723 InternalPrePositionConstraint( initialPanMask, mAxisAutoLock, mAxisAutoLockGradient, mLockAxis, mMaxOvershoot, mRulerX->GetDomain(), mRulerY->GetDomain() ) );
2724 mScrollMainInternalPrePositionConstraint = self.ApplyConstraint( constraint );
2727 // 2. Second calculate the clamped position (actual position)
2728 constraint = Constraint::New<Vector3>( mPropertyPosition,
2729 LocalSource( mPropertyPrePosition ),
2730 LocalSource( mPropertyPositionMin ),
2731 LocalSource( mPropertyPositionMax ),
2732 Source( self, Actor::SIZE ),
2733 InternalPositionConstraint( mRulerX->GetDomain(),
2734 mRulerY->GetDomain(), mWrapMode ) );
2735 mScrollMainInternalPositionConstraint = self.ApplyConstraint( constraint );
2737 constraint = Constraint::New<Vector3>( mPropertyPositionDelta,
2738 LocalSource( mPropertyPosition ),
2739 LocalSource( mPropertyDomainOffset ),
2740 InternalPositionDeltaConstraint );
2741 mScrollMainInternalDeltaConstraint = self.ApplyConstraint( constraint );
2743 constraint = Constraint::New<Vector3>( mPropertyFinal,
2744 LocalSource( mPropertyPosition ),
2745 LocalSource( mPropertyOvershootX ),
2746 LocalSource( mPropertyOvershootY ),
2747 InternalFinalConstraint( FinalDefaultAlphaFunction,
2748 FinalDefaultAlphaFunction ) );
2749 mScrollMainInternalFinalConstraint = self.ApplyConstraint( constraint );
2751 constraint = Constraint::New<Vector3>( mPropertyRelativePosition,
2752 LocalSource( mPropertyPosition ),
2753 LocalSource( mPropertyPositionMin ),
2754 LocalSource( mPropertyPositionMax ),
2755 LocalSource( Actor::SIZE ),
2756 InternalRelativePositionConstraint );
2757 mScrollMainInternalRelativeConstraint = self.ApplyConstraint( constraint );
2759 constraint = Constraint::New<float>( mPropertyX,
2760 LocalSource( mPropertyPrePosition ),
2761 InternalXConstraint );
2762 mScrollMainInternalXConstraint = self.ApplyConstraint( constraint );
2764 constraint = Constraint::New<float>( mPropertyY,
2765 LocalSource( mPropertyPrePosition ),
2766 InternalYConstraint );
2767 mScrollMainInternalYConstraint = self.ApplyConstraint( constraint );
2769 // When panning we want to make sure overshoot values are affected by pre position and post position
2770 SetOvershootConstraintsEnabled(!mWrapMode);
2773 void ScrollView::SetOvershootConstraintsEnabled(bool enabled)
2775 Actor self( Self() );
2776 // remove and reset, it may now be in wrong order with the main internal constraints
2777 if( mScrollMainInternalOvershootXConstraint )
2779 self.RemoveConstraint(mScrollMainInternalOvershootXConstraint);
2780 mScrollMainInternalOvershootXConstraint.Reset();
2781 self.RemoveConstraint(mScrollMainInternalOvershootYConstraint);
2782 mScrollMainInternalOvershootYConstraint.Reset();
2786 Constraint constraint = Constraint::New<float>( mPropertyOvershootX,
2787 LocalSource( mPropertyPrePosition ),
2788 LocalSource( mPropertyPosition ),
2789 LocalSource( mPropertyCanScrollHorizontal ),
2790 OvershootXConstraint(mMaxOvershoot.x) );
2791 mScrollMainInternalOvershootXConstraint = self.ApplyConstraint( constraint );
2793 constraint = Constraint::New<float>( mPropertyOvershootY,
2794 LocalSource( mPropertyPrePosition ),
2795 LocalSource( mPropertyPosition ),
2796 LocalSource( mPropertyCanScrollVertical ),
2797 OvershootYConstraint(mMaxOvershoot.y) );
2798 mScrollMainInternalOvershootYConstraint = self.ApplyConstraint( constraint );
2802 self.SetProperty(mPropertyOvershootX, 0.0f);
2803 self.SetProperty(mPropertyOvershootY, 0.0f);
2807 void ScrollView::SetInternalConstraints()
2809 // Internal constraints (applied to target ScrollBase Actor itself) /////////
2810 UpdateMainInternalConstraint();
2812 // User definable constraints to apply to all child actors //////////////////
2813 Actor self = Self();
2815 // LocalSource - The Actors to be moved.
2816 // self - The ScrollView
2818 // Apply some default constraints to ScrollView.
2819 // Movement + Scaling + Wrap function
2821 Constraint constraint;
2823 // MoveScaledActor (scrolling/zooming)
2824 constraint = Constraint::New<Vector3>( Actor::POSITION,
2825 Source( self, mPropertyPosition ),
2826 Source( self, mPropertyScale ),
2827 MoveScaledActorConstraint );
2828 constraint.SetRemoveAction(Constraint::Discard);
2829 ApplyConstraintToBoundActors(constraint);
2831 // ScaleActor (scrolling/zooming)
2832 constraint = Constraint::New<Vector3>( Actor::SCALE,
2833 Source( self, mPropertyScale ),
2834 ScaleActorConstraint );
2835 constraint.SetRemoveAction(Constraint::Discard);
2836 ApplyConstraintToBoundActors(constraint);
2838 // WrapActor (wrap functionality)
2839 constraint = Constraint::New<Vector3>( Actor::POSITION,
2840 LocalSource( Actor::SCALE ),
2841 LocalSource( Actor::ANCHOR_POINT ),
2842 LocalSource( Actor::SIZE ),
2843 Source( self, mPropertyPositionMin ),
2844 Source( self, mPropertyPositionMax ),
2845 Source( self, mPropertyWrap ),
2846 WrapActorConstraint );
2847 constraint.SetRemoveAction(Constraint::Discard);
2848 ApplyConstraintToBoundActors(constraint);
2851 } // namespace Internal
2853 } // namespace Toolkit