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;
62 // predefined effect values
63 const Vector3 ANGLE_CAROUSEL_ROTATE(Math::PI * 0.5f, Math::PI * 0.5f, 0.0f);
64 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
65 const Vector2 ANGLE_CUSTOM_CUBE_SWING(-Math::PI * 0.45f, -Math::PI * 0.45f); ///< outer cube pages swing 90 degrees as they pan offscreen
66 const Vector2 ANGLE_SPIRAL_SWING_IN(Math::PI * 0.5f, Math::PI * 0.5f);
67 const Vector2 ANGLE_SPIRAL_SWING_OUT(Math::PI * 0.35f, Math::PI * 0.35f);
68 const Vector2 ANGLE_OUTER_CUBE_SWING(Math::PI * 0.5f, Math::PI * 0.5f); ///< outer cube pages swing 90 degrees as they pan offscreen
70 // Helpers ////////////////////////////////////////////////////////////////////////////////////////
72 // TODO: GetAngle for Vector2 can be moved.
73 // GetAngle for Vector3 needs to be measured against a normal/plane.
76 * @param[in] vector The 3D vector to be measured
77 * @return angle in radians from 0 to 2PI
79 float GetAngle(const Vector3& vector)
81 return atan2(vector.y, vector.x) + Math::PI;
85 * @param[in] vector The 2D vector to be measured
86 * @return angle in radians from 0 to 2PI
88 float GetAngle(const Vector2& vector)
90 return atan2(vector.y, vector.x) + Math::PI;
94 * Find the vector (distance) from (a) to (b)
95 * in domain (start) to (end)
96 * (\ / start) (\ / end)
99 * @note assumes both (a) and (b) are already with the domain
102 * @param[in] a the current point
103 * @param[in] b the target point
104 * @param[in] start the start of the domain
105 * @param[in] end the end of the domain
106 * @param[in] bias whether to only take the right direction or the left direction,
107 * or the shortest direction.
108 * @return the shortest direction and distance
110 float VectorInDomain(float a, float b, float start, float end, Dali::Toolkit::DirectionBias bias)
112 if(bias == Dali::Toolkit::DirectionBiasNone)
114 return ShortestDistanceInDomain( a, b, start, end );
117 float size = end-start;
123 if(bias == Dali::Toolkit::DirectionBiasRight) // going right, take the vector.
129 float aRight = a+size;
136 if(bias == Dali::Toolkit::DirectionBiasLeft) // going left, take the vector.
142 float aLeft = a-size;
149 * Returns the position of the anchor within actor
151 * @param actor The Actor
152 * @param anchor The Anchor point of interest.
153 * @return The position of the Anchor
155 Vector3 GetPositionOfAnchor(Actor &actor, const Vector3 &anchor)
157 Vector3 childPosition = actor.GetCurrentPosition();
158 Vector3 childAnchor = - actor.GetCurrentAnchorPoint() + anchor;
159 Vector3 childSize = actor.GetCurrentSize();
161 return childPosition + childAnchor * childSize;
164 // AlphaFunctions /////////////////////////////////////////////////////////////////////////////////
166 float FinalDefaultAlphaFunction(float offset)
168 return offset * 0.5f;
172 * ConstantDecelerationAlphaFunction
173 * Newtoninan distance for constant deceleration
174 * v = 1 - t, s = t - 1/2 t^2
175 * when t = 0, s = 0.0 (min distance)
176 * when t = 1, s = 0.5 (max distance)
177 * progress = s / (max-min) = 2t - t^2
179 * @param[in] offset The input progress
180 * @return The output progress
182 float ConstantDecelerationAlphaFunction(float progress)
184 return progress * 2.0f - progress * progress;
187 // Internal Constraints ///////////////////////////////////////////////////////////////////////////
190 * Internal Relative position Constraint
191 * Generates the relative position value of the scroll view
192 * based on the absolute position, and it's relation to the
193 * scroll domain. This is a value from 0.0f to 1.0f in each
194 * scroll position axis.
196 Vector3 InternalRelativePositionConstraint(const Vector3& current,
197 const PropertyInput& scrollPositionProperty,
198 const PropertyInput& scrollMinProperty,
199 const PropertyInput& scrollMaxProperty,
200 const PropertyInput& scrollSizeProperty)
202 Vector3 position = -scrollPositionProperty.GetVector3();
203 const Vector3& min = scrollMinProperty.GetVector3();
204 const Vector3& max = scrollMaxProperty.GetVector3();
205 const Vector3& size = scrollSizeProperty.GetVector3();
207 position.x = WrapInDomain(position.x, min.x, max.x);
208 position.y = WrapInDomain(position.y, min.y, max.y);
210 Vector3 relativePosition;
211 Vector3 domainSize = (max - min) - size;
213 relativePosition.x = domainSize.x > Math::MACHINE_EPSILON_1 ? fabsf((position.x - min.x) / domainSize.x) : 0.0f;
214 relativePosition.y = domainSize.y > Math::MACHINE_EPSILON_1 ? fabsf((position.y - min.y) / domainSize.y) : 0.0f;
216 return relativePosition;
219 } // unnamed namespace
234 * Returns whether to lock scrolling to a particular axis
236 * @param[in] panDelta Distance panned since gesture started
237 * @param[in] currentLockAxis The current lock axis value
238 * @param[in] lockGradient How quickly to lock to a particular axis
240 * @return The new axis lock state
242 ScrollView::LockAxis GetLockAxis(const Vector2& panDelta, ScrollView::LockAxis currentLockAxis, float lockGradient)
244 if(panDelta.LengthSquared() > AUTOLOCK_AXIS_MINIMUM_DISTANCE2 &&
245 currentLockAxis == ScrollView::LockPossible)
247 float dx = fabsf(panDelta.x);
248 float dy = fabsf(panDelta.y);
249 if(dx * lockGradient >= dy)
251 // 0.36:1 gradient to the horizontal (deviate < 20 degrees)
252 currentLockAxis = ScrollView::LockVertical;
254 else if(dy * lockGradient > dx)
256 // 0.36:1 gradient to the vertical (deviate < 20 degrees)
257 currentLockAxis = ScrollView::LockHorizontal;
261 currentLockAxis = ScrollView::LockNone;
264 return currentLockAxis;
268 * Internal Pre-Position Property Constraint.
270 * Generates position property based on current position + gesture displacement.
271 * Or generates position property based on positionX/Y.
272 * Note: This is the position prior to any clamping at scroll boundaries.
273 * TODO: Scale & Rotation Transforms.
275 struct InternalPrePositionConstraint
277 InternalPrePositionConstraint(const Vector2& initialPanMask,
279 float axisAutoLockGradient,
280 ScrollView::LockAxis initialLockAxis,
281 const Vector2& maxOvershoot,
282 const RulerDomain& domainX, const RulerDomain& domainY)
283 : mInitialPanMask(initialPanMask),
284 mDomainMin( -domainX.min, -domainY.min ),
285 mDomainMax( -domainX.max, -domainY.max ),
286 mMaxOvershoot(maxOvershoot),
287 mAxisAutoLockGradient(axisAutoLockGradient),
288 mLockAxis(initialLockAxis),
289 mAxisAutoLock(axisAutoLock),
291 mClampX( domainX.enabled ),
292 mClampY( domainY.enabled )
296 Vector3 operator()(const Vector3& current,
297 const PropertyInput& gesturePositionProperty,
298 const PropertyInput& gestureDisplacementProperty,
299 const PropertyInput& sizeProperty)
301 Vector3 scrollPostPosition = current;
302 Vector2 panPosition = gesturePositionProperty.GetVector2();
306 mLocalStart = gesturePositionProperty.GetVector2() - gestureDisplacementProperty.GetVector2();
307 mPrePosition = current;
308 mCurrentPanMask = mInitialPanMask;
312 // Calculate Deltas...
313 Vector2 currentPosition = gesturePositionProperty.GetVector2();
314 Vector2 panDelta( currentPosition - mLocalStart );
316 // Axis Auto Lock - locks the panning to the horizontal or vertical axis if the pan
317 // appears mostly horizontal or mostly vertical respectively...
320 mLockAxis = GetLockAxis(panDelta, mLockAxis, mAxisAutoLockGradient);
321 if( mLockAxis == ScrollView::LockVertical )
323 mCurrentPanMask.y = 0.0f;
325 else if( mLockAxis == ScrollView::LockHorizontal )
327 mCurrentPanMask.x = 0.0f;
331 // Restrict deltas based on ruler enable/disable and axis-lock state...
332 panDelta *= mCurrentPanMask;
334 // Perform Position transform based on input deltas...
335 scrollPostPosition = mPrePosition;
336 scrollPostPosition.GetVectorXY() += panDelta;
338 // if no wrapping then clamp preposition to maximum overshoot amount
339 const Vector3& size = sizeProperty.GetVector3();
342 float newXPosition = Clamp(scrollPostPosition.x, (mDomainMax.x + size.x) - mMaxOvershoot.x, mDomainMin.x + mMaxOvershoot.x );
343 if( (newXPosition < scrollPostPosition.x - Math::MACHINE_EPSILON_1)
344 || (newXPosition > scrollPostPosition.x + Math::MACHINE_EPSILON_1) )
346 mPrePosition.x = newXPosition;
347 mLocalStart.x = panPosition.x;
349 scrollPostPosition.x = newXPosition;
353 float newYPosition = Clamp(scrollPostPosition.y, (mDomainMax.y + size.y) - mMaxOvershoot.y, mDomainMin.y + mMaxOvershoot.y );
354 if( (newYPosition < scrollPostPosition.y - Math::MACHINE_EPSILON_1)
355 || (newYPosition > scrollPostPosition.y + Math::MACHINE_EPSILON_1) )
357 mPrePosition.y = newYPosition;
358 mLocalStart.y = panPosition.y;
360 scrollPostPosition.y = newYPosition;
363 return scrollPostPosition;
366 Vector3 mPrePosition;
368 Vector2 mInitialPanMask; ///< Initial pan mask (based on ruler settings)
369 Vector2 mCurrentPanMask; ///< Current pan mask that can be altered by axis lock mode.
372 Vector2 mMaxOvershoot;
374 float mAxisAutoLockGradient; ///< Set by ScrollView
375 ScrollView::LockAxis mLockAxis;
377 bool mAxisAutoLock:1; ///< Set by ScrollView
384 * Internal Position Property Constraint.
386 * Generates position property based on pre-position
387 * Note: This is the position after clamping.
388 * (uses result of InternalPrePositionConstraint)
390 struct InternalPositionConstraint
392 InternalPositionConstraint(const RulerDomain& domainX, const RulerDomain& domainY, bool wrap)
393 : mDomainMin( -domainX.min, -domainY.min ),
394 mDomainMax( -domainX.max, -domainY.max ),
395 mClampX( domainX.enabled ),
396 mClampY( domainY.enabled ),
401 Vector3 operator()(const Vector3& current,
402 const PropertyInput& scrollPositionProperty,
403 const PropertyInput& scrollMinProperty,
404 const PropertyInput& scrollMaxProperty,
405 const PropertyInput& scrollSizeProperty)
407 Vector3 position = scrollPositionProperty.GetVector3();
408 const Vector2& size = scrollSizeProperty.GetVector3().GetVectorXY();
409 const Vector3& min = scrollMinProperty.GetVector3();
410 const Vector3& max = scrollMaxProperty.GetVector3();
414 position.x = -WrapInDomain(-position.x, min.x, max.x);
415 position.y = -WrapInDomain(-position.y, min.y, max.y);
419 // clamp post position to domain
420 position.x = mClampX ? Clamp(position.x, mDomainMax.x + size.x, mDomainMin.x ) : position.x;
421 position.y = mClampY ? Clamp(position.y, mDomainMax.y + size.y, mDomainMin.y ) : position.y;
436 * This constraint updates the X overshoot property using the difference
437 * mPropertyPrePosition.x and mPropertyPosition.x, returning a relative value between 0.0f and 1.0f
439 struct OvershootXConstraint
441 OvershootXConstraint(float maxOvershoot) : mMaxOvershoot(maxOvershoot) {}
443 float operator()(const float& current,
444 const PropertyInput& scrollPrePositionProperty,
445 const PropertyInput& scrollPostPositionProperty,
446 const PropertyInput& canScrollProperty)
448 if( canScrollProperty.GetBoolean() )
450 const Vector3& scrollPrePosition = scrollPrePositionProperty.GetVector3();
451 const Vector3& scrollPostPosition = scrollPostPositionProperty.GetVector3();
452 float newOvershoot = scrollPrePosition.x - scrollPostPosition.x;
453 return (newOvershoot > 0.0f ? std::min(newOvershoot, mMaxOvershoot) : std::max(newOvershoot, -mMaxOvershoot)) / mMaxOvershoot;
462 * This constraint updates the Y overshoot property using the difference
463 * mPropertyPrePosition.y and mPropertyPosition.y, returning a relative value between 0.0f and 1.0f
465 struct OvershootYConstraint
467 OvershootYConstraint(float maxOvershoot) : mMaxOvershoot(maxOvershoot) {}
469 float operator()(const float& current,
470 const PropertyInput& scrollPrePositionProperty,
471 const PropertyInput& scrollPostPositionProperty,
472 const PropertyInput& canScrollProperty)
474 if( canScrollProperty.GetBoolean() )
476 const Vector3& scrollPrePosition = scrollPrePositionProperty.GetVector3();
477 const Vector3& scrollPostPosition = scrollPostPositionProperty.GetVector3();
478 float newOvershoot = scrollPrePosition.y - scrollPostPosition.y;
479 return (newOvershoot > 0.0f ? std::min(newOvershoot, mMaxOvershoot) : std::max(newOvershoot, -mMaxOvershoot)) / mMaxOvershoot;
488 * When panning, this constraint updates the X property, otherwise
489 * it has no effect on the X property.
491 float InternalXConstraint(const float& current,
492 const PropertyInput& scrollPosition)
494 return scrollPosition.GetVector3().x;
498 * When panning, this constraint updates the Y property, otherwise
499 * it has no effect on the Y property.
501 float InternalYConstraint(const float& current,
502 const PropertyInput& scrollPosition)
504 return scrollPosition.GetVector3().y;
508 * Internal Position-Delta Property Constraint.
510 * Generates position-delta property based on scroll-position + scroll-offset properties.
512 Vector3 InternalPositionDeltaConstraint(const Vector3& current,
513 const PropertyInput& scrollPositionProperty,
514 const PropertyInput& scrollOffsetProperty)
516 const Vector3& scrollPosition = scrollPositionProperty.GetVector3();
517 const Vector3& scrollOffset = scrollOffsetProperty.GetVector3();
519 return scrollPosition + scrollOffset;
523 * Internal Final Position Constraint
524 * The position of content is:
525 * of scroll-position + f(scroll-overshoot)
526 * where f(...) function defines how overshoot
527 * should affect final-position.
529 struct InternalFinalConstraint
531 InternalFinalConstraint(AlphaFunction functionX,
532 AlphaFunction functionY)
533 : mFunctionX(functionX),
534 mFunctionY(functionY)
538 Vector3 operator()(const Vector3& current,
539 const PropertyInput& scrollPositionProperty,
540 const PropertyInput& scrollOvershootXProperty,
541 const PropertyInput& scrollOvershootYProperty)
543 const float& overshootx = scrollOvershootXProperty.GetFloat();
544 const float& overshooty = scrollOvershootYProperty.GetFloat();
545 Vector3 offset( mFunctionX(overshootx),
546 mFunctionY(overshooty),
549 return scrollPositionProperty.GetVector3() - offset;
552 AlphaFunction mFunctionX;
553 AlphaFunction mFunctionY;
559 return Toolkit::ScrollView::New();
562 TypeRegistration typeRegistration( typeid(Toolkit::ScrollView), typeid(Toolkit::Scrollable), Create );
564 SignalConnectorType signalConnector1( typeRegistration, Toolkit::ScrollView::SIGNAL_SNAP_STARTED, &ScrollView::DoConnectSignal );
569 ///////////////////////////////////////////////////////////////////////////////////////////////////
571 ///////////////////////////////////////////////////////////////////////////////////////////////////
573 Dali::Toolkit::ScrollView ScrollView::New()
575 // Create the implementation
576 ScrollViewPtr scrollView(new ScrollView());
578 // Pass ownership to CustomActor via derived handle
579 Dali::Toolkit::ScrollView handle(*scrollView);
581 // Second-phase init of the implementation
582 // This can only be done after the CustomActor connection has been made...
583 scrollView->Initialize();
588 ScrollView::ScrollView()
591 mGestureStackDepth(0),
592 mRotationDelta(0.0f),
593 mScrollStateFlags(0),
594 mScrollPreRotation(0.0f),
595 mScrollPostRotation(0.0f),
596 mMinTouchesForPanning(1),
597 mMaxTouchesForPanning(1),
598 mLockAxis(LockPossible),
599 mRefreshIntervalMilliseconds(DEFAULT_REFRESH_INTERVAL_MILLISECONDS),
600 mOvershootDelay(1.0f),
601 mMaxOvershoot(Toolkit::ScrollView::DEFAULT_MAX_OVERSHOOT, Toolkit::ScrollView::DEFAULT_MAX_OVERSHOOT),
602 mUserMaxOvershoot(Toolkit::ScrollView::DEFAULT_MAX_OVERSHOOT, Toolkit::ScrollView::DEFAULT_MAX_OVERSHOOT),
603 mSnapOvershootDuration(Toolkit::ScrollView::DEFAULT_SNAP_OVERSHOOT_DURATION),
604 mSnapOvershootAlphaFunction(AlphaFunctions::EaseOut),
605 mSnapDuration(Toolkit::ScrollView::DEFAULT_SLOW_SNAP_ANIMATION_DURATION),
606 mSnapAlphaFunction(AlphaFunctions::EaseOut),
607 mFlickDuration(Toolkit::ScrollView::DEFAULT_FAST_SNAP_ANIMATION_DURATION),
608 mFlickAlphaFunction(AlphaFunctions::EaseOut),
609 mAxisAutoLockGradient(Toolkit::ScrollView::DEFAULT_AXIS_AUTO_LOCK_GRADIENT),
610 mFrictionCoefficient(Toolkit::ScrollView::DEFAULT_FRICTION_COEFFICIENT),
611 mFlickSpeedCoefficient(Toolkit::ScrollView::DEFAULT_FLICK_SPEED_COEFFICIENT),
612 mMaxFlickSpeed(Toolkit::ScrollView::DEFAULT_MAX_FLICK_SPEED),
613 mInAccessibilityPan(false),
616 mScrollInterrupted(false),
619 mTouchDownTimeoutReached(false),
620 mActorAutoSnapEnabled(false),
621 mAutoResizeContainerEnabled(false),
623 mAxisAutoLock(false),
625 mDefaultMaxOvershoot(true)
627 SetRequiresMouseWheelEvents(true);
630 void ScrollView::OnInitialize()
634 // Internal Actor, used to hide actors from enumerations.
635 // Also actors added to Internal actor appear as overlays e.g. ScrollBar components.
636 mInternalActor = Actor::New();
637 mInternalActor.SetDrawMode(DrawMode::OVERLAY);
638 self.Add(mInternalActor);
639 mInternalActor.ApplyConstraint( Constraint::New<Vector3>( Actor::SIZE, ParentSource( Actor::SIZE ), EqualToConstraint() ) );
640 mInternalActor.SetParentOrigin(ParentOrigin::CENTER);
641 mInternalActor.SetAnchorPoint(AnchorPoint::CENTER);
645 // Register Scroll Properties.
646 RegisterProperties();
648 mScrollPostPosition = mScrollPrePosition = Vector3::ZERO;
649 mScrollPostScale = mScrollPreScale = Vector3::ONE;
650 mScrollPostRotation = mScrollPreRotation = 0.0f;
652 mMouseWheelScrollDistanceStep = Stage::GetCurrent().GetSize() * DEFAULT_MOUSE_WHEEL_SCROLL_DISTANCE_STEP_PROPORTION;
656 mGestureStackDepth = 0;
658 EnableGestureDetection( Gesture::Type( Gesture::Pan ) );
660 // For pan, default to only 1 touch required, ignoring touches outside this range.
661 SetTouchesRequiredForPanning(1, 1, false);
663 // By default we'll allow the user to freely drag the scroll view,
664 // while disabling the other rulers.
665 RulerPtr ruler = new DefaultRuler();
666 RulerPtr rulerDisabled = new DefaultRuler();
667 rulerDisabled->Disable();
670 mRulerScaleX = rulerDisabled;
671 mRulerScaleY = rulerDisabled;
672 mRulerRotation = rulerDisabled;
674 EnableScrollComponent(Toolkit::Scrollable::OvershootIndicator);
676 Vector3 size = GetControlSize();
677 UpdatePropertyDomain(size);
678 SetInternalConstraints();
681 void ScrollView::OnControlStageConnection()
683 DALI_LOG_SCROLL_STATE("[0x%X]", this);
687 SetScrollSensitive( false );
688 SetScrollSensitive( true );
690 if(IsScrollComponentEnabled(Toolkit::Scrollable::OvershootIndicator))
692 // try and make sure property notifications are set
693 EnableScrollComponent(Toolkit::Scrollable::OvershootIndicator);
697 void ScrollView::OnControlStageDisconnection()
699 DALI_LOG_SCROLL_STATE("[0x%X]", this);
704 ScrollView::~ScrollView()
706 DALI_LOG_SCROLL_STATE("[0x%X]", this);
709 AlphaFunction ScrollView::GetScrollSnapAlphaFunction() const
711 return mSnapAlphaFunction;
714 void ScrollView::SetScrollSnapAlphaFunction(AlphaFunction alpha)
716 mSnapAlphaFunction = alpha;
719 AlphaFunction ScrollView::GetScrollFlickAlphaFunction() const
721 return mFlickAlphaFunction;
724 void ScrollView::SetScrollFlickAlphaFunction(AlphaFunction alpha)
726 mFlickAlphaFunction = alpha;
729 float ScrollView::GetScrollSnapDuration() const
731 return mSnapDuration;
734 void ScrollView::SetScrollSnapDuration(float time)
736 mSnapDuration = time;
739 float ScrollView::GetScrollFlickDuration() const
741 return mFlickDuration;
744 void ScrollView::SetScrollFlickDuration(float time)
746 mFlickDuration = time;
749 void ScrollView::ApplyEffect(Toolkit::ScrollViewEffect effect)
751 Dali::Toolkit::ScrollView self = Dali::Toolkit::ScrollView::DownCast(Self());
753 // Assertion check to ensure effect doesn't already exist in this scrollview
754 bool effectAlreadyExistsInScrollView(false);
755 for (ScrollViewEffectIter iter = mEffects.begin(); iter != mEffects.end(); ++iter)
759 effectAlreadyExistsInScrollView = true;
764 DALI_ASSERT_ALWAYS(!effectAlreadyExistsInScrollView);
766 // add effect to effects list
767 mEffects.push_back(effect);
769 // invoke Attachment request to ScrollView first
770 GetImpl(effect).Attach(self);
773 Toolkit::ScrollViewEffect ScrollView::ApplyEffect(Toolkit::ScrollView::PageEffect effect)
775 Toolkit::ScrollViewEffect scrollEffect;
778 case Toolkit::ScrollView::PageEffectNone:
782 case Toolkit::ScrollView::PageEffectOuterCube:
784 Toolkit::ScrollViewCustomEffect customEffect;
785 scrollEffect = customEffect = Toolkit::ScrollViewCustomEffect::New();
786 Vector2 pageSize = Stage::GetCurrent().GetSize();
787 // 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
788 // 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)
789 // the page moving off screen will slowly build a spacing from 0.0f to 20.0f
790 // the spacing from each page is added together for the final spacing between the two pages.
791 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));
792 customEffect.SetSwingAngleOut(ANGLE_CUSTOM_CUBE_SWING.x, Vector3(0.0f, -1.0f, 0.0f));
793 customEffect.SetSwingAnchor(AnchorPoint::CENTER, AnchorPoint::CENTER_LEFT);
794 customEffect.SetOpacityThreshold(0.7f);
797 case Toolkit::ScrollView::PageEffectDepth:
799 Toolkit::ScrollViewCustomEffect customEffect;
800 scrollEffect = customEffect = Toolkit::ScrollViewCustomEffect::New();
803 case Toolkit::ScrollView::PageEffectInnerCube:
805 Toolkit::ScrollViewCustomEffect customEffect;
806 scrollEffect = customEffect = Toolkit::ScrollViewCustomEffect::New();
807 customEffect.SetPageSpacing(Vector2(30.0f, 30.0f));
808 customEffect.SetAngledOriginPageRotation(ANGLE_CUBE_PAGE_ROTATE);
809 customEffect.SetSwingAngle(ANGLE_CUBE_PAGE_ROTATE.x, Vector3(0,-1,0));
810 customEffect.SetOpacityThreshold(0.5f);
813 case Toolkit::ScrollView::PageEffectCarousel:
815 Toolkit::ScrollViewCustomEffect customEffect;
816 scrollEffect = customEffect = Toolkit::ScrollViewCustomEffect::New();
817 customEffect.SetPageTranslation(Vector3(0,0,0), Vector3(-30, 0, 0));
818 customEffect.SetPageSpacing(Vector2(60.0f, 60.0f));
819 customEffect.SetAngledOriginPageRotation(-ANGLE_CUBE_PAGE_ROTATE);
820 customEffect.SetOpacityThreshold(0.2f, 0.6f);
823 case Toolkit::ScrollView::PageEffectSpiral:
825 Toolkit::ScrollViewCustomEffect customEffect;
826 scrollEffect = customEffect = Toolkit::ScrollViewCustomEffect::New();
828 Vector2 pageSize = Stage::GetCurrent().GetSize();
829 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));
830 //customEffect.SetSwingAngleAlphaFunctionOut(AlphaFunctions::EaseOut);
831 customEffect.SetSwingAnchor(AnchorPoint::CENTER_RIGHT);
832 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);
833 //customEffect.SetPageTranslateAlphaFunctionOut(AlphaFunctions::EaseOut);
834 customEffect.SetOpacityThreshold(0.75f, 0.6f);
835 customEffect.SetOpacityAlphaFunctionIn(AlphaFunctions::EaseInOut);
840 DALI_ASSERT_DEBUG(0 && "unknown scroll view effect");
843 RemoveConstraintsFromChildren();
846 ApplyEffect(scrollEffect);
851 void ScrollView::RemoveEffect(Toolkit::ScrollViewEffect effect)
853 Dali::Toolkit::ScrollView self = Dali::Toolkit::ScrollView::DownCast(Self());
855 // remove effect from effects list
856 bool effectExistedInScrollView(false);
857 for (ScrollViewEffectIter iter = mEffects.begin(); iter != mEffects.end(); ++iter)
861 mEffects.erase(iter);
862 effectExistedInScrollView = true;
867 // Assertion check to ensure effect existed.
868 DALI_ASSERT_ALWAYS(effectExistedInScrollView);
870 // invoke Detachment request to ScrollView last
871 GetImpl(effect).Detach(self);
874 void ScrollView::RemoveAllEffects()
876 Dali::Toolkit::ScrollView self = Dali::Toolkit::ScrollView::DownCast(Self());
878 for (ScrollViewEffectIter effectIter = mEffects.begin(); effectIter != mEffects.end(); ++effectIter)
880 Toolkit::ScrollViewEffect effect = *effectIter;
882 // invoke Detachment request to ScrollView last
883 GetImpl(effect).Detach(self);
889 void ScrollView::ApplyConstraintToChildren(Constraint constraint)
891 ApplyConstraintToBoundActors(constraint);
894 void ScrollView::RemoveConstraintsFromChildren()
896 RemoveConstraintsFromBoundActors();
899 const RulerPtr ScrollView::GetRulerX() const
904 const RulerPtr ScrollView::GetRulerY() const
909 void ScrollView::SetRulerX(RulerPtr ruler)
913 Vector3 size = GetControlSize();
914 UpdatePropertyDomain(size);
915 UpdateMainInternalConstraint();
918 void ScrollView::SetRulerY(RulerPtr ruler)
922 Vector3 size = GetControlSize();
923 UpdatePropertyDomain(size);
924 UpdateMainInternalConstraint();
927 void ScrollView::UpdatePropertyDomain(const Vector3& size)
930 Vector3 min = mMinScroll;
931 Vector3 max = mMaxScroll;
932 bool scrollPositionChanged = false;
933 bool domainChanged = false;
935 bool canScrollVertical = false;
936 bool canScrollHorizontal = false;
937 UpdateLocalScrollProperties();
938 if(mRulerX->IsEnabled())
940 const Toolkit::RulerDomain& rulerDomain = mRulerX->GetDomain();
941 if( fabsf(min.x - rulerDomain.min) > Math::MACHINE_EPSILON_10000
942 || fabsf(max.x - rulerDomain.max) > Math::MACHINE_EPSILON_10000 )
944 domainChanged = true;
945 min.x = rulerDomain.min;
946 max.x = rulerDomain.max;
948 // make sure new scroll value is within new domain
949 if( mScrollPrePosition.x < min.x
950 || mScrollPrePosition.x > max.x )
952 scrollPositionChanged = true;
953 mScrollPrePosition.x = Clamp(mScrollPrePosition.x, -(max.x - size.x), -min.x);
956 if( (fabsf(rulerDomain.max - rulerDomain.min) - size.x) > Math::MACHINE_EPSILON_10000 )
958 canScrollHorizontal = true;
962 if(mRulerY->IsEnabled())
964 const Toolkit::RulerDomain& rulerDomain = mRulerY->GetDomain();
965 if( fabsf(min.y - rulerDomain.min) > Math::MACHINE_EPSILON_10000
966 || fabsf(max.y - rulerDomain.max) > Math::MACHINE_EPSILON_10000 )
968 domainChanged = true;
969 min.y = rulerDomain.min;
970 max.y = rulerDomain.max;
972 // make sure new scroll value is within new domain
973 if( mScrollPrePosition.y < min.y
974 || mScrollPrePosition.y > max.y )
976 scrollPositionChanged = true;
977 mScrollPrePosition.y = Clamp(mScrollPrePosition.y, -(max.y - size.y), -min.y);
980 if( (fabsf(rulerDomain.max - rulerDomain.min) - size.y) > Math::MACHINE_EPSILON_10000 )
982 canScrollVertical = true;
985 // avoid setting properties if possible, otherwise this will cause an entire update as well as triggering constraints using each property we update
986 if( self.GetProperty<bool>(mPropertyCanScrollVertical) != canScrollVertical )
988 self.SetProperty(mPropertyCanScrollVertical, canScrollVertical);
990 if( self.GetProperty<bool>(mPropertyCanScrollHorizontal) != canScrollHorizontal )
992 self.SetProperty(mPropertyCanScrollHorizontal, canScrollHorizontal);
994 if( scrollPositionChanged )
996 self.SetProperty(mPropertyPrePosition, mScrollPrePosition);
1002 self.SetProperty(mPropertyPositionMin, min );
1003 self.SetProperty(mPropertyPositionMax, max );
1007 void ScrollView::SetRulerScaleX(RulerPtr ruler)
1009 mRulerScaleX = ruler;
1010 UpdateMainInternalConstraint();
1013 void ScrollView::SetRulerScaleY(RulerPtr ruler)
1015 mRulerScaleY = ruler;
1016 UpdateMainInternalConstraint();
1019 void ScrollView::SetRulerRotation(RulerPtr ruler)
1021 mRulerRotation = ruler;
1022 UpdateMainInternalConstraint();
1025 void ScrollView::SetScrollSensitive(bool sensitive)
1027 Actor self = Self();
1028 PanGestureDetector panGesture( GetPanGestureDetector() );
1030 DALI_LOG_SCROLL_STATE("[0x%X] sensitive[%d]", this, int(sensitive));
1032 if((!mSensitive) && (sensitive))
1034 mSensitive = sensitive;
1035 panGesture.Attach(self);
1037 else if((mSensitive) && (!sensitive))
1039 // while the scroll view is panning, the state needs to be reset.
1040 bool isPanning = self.GetProperty<bool>( mPropertyPanning );
1043 PanGesture cancelGesture( Gesture::Cancelled );
1044 OnPan( cancelGesture );
1047 panGesture.Detach(self);
1048 mSensitive = sensitive;
1050 mGestureStackDepth = 0;
1054 void ScrollView::SetMaxOvershoot(float overshootX, float overshootY)
1056 mMaxOvershoot.x = overshootX;
1057 mMaxOvershoot.y = overshootY;
1058 mUserMaxOvershoot = mMaxOvershoot;
1059 mDefaultMaxOvershoot = false;
1060 UpdateMainInternalConstraint();
1063 void ScrollView::SetSnapOvershootAlphaFunction(AlphaFunction alpha)
1065 mSnapOvershootAlphaFunction = alpha;
1068 void ScrollView::SetSnapOvershootDuration(float duration)
1070 mSnapOvershootDuration = duration;
1073 void ScrollView::SetTouchesRequiredForPanning(unsigned int minTouches, unsigned int maxTouches, bool endOutside)
1075 PanGestureDetector panGesture( GetPanGestureDetector() );
1077 mMinTouchesForPanning = minTouches;
1078 mMaxTouchesForPanning = maxTouches;
1082 panGesture.SetMinimumTouchesRequired(minTouches);
1083 panGesture.SetMaximumTouchesRequired(maxTouches);
1087 panGesture.SetMinimumTouchesRequired(1);
1088 panGesture.SetMaximumTouchesRequired(UINT_MAX);
1092 void ScrollView::SetActorAutoSnap(bool enable)
1094 mActorAutoSnapEnabled = enable;
1097 void ScrollView::SetAutoResize(bool enable)
1099 mAutoResizeContainerEnabled = enable;
1100 // TODO: This needs a lot of issues to be addressed before working.
1103 bool ScrollView::GetWrapMode() const
1108 void ScrollView::SetWrapMode(bool enable)
1111 Self().SetProperty(mPropertyWrap, enable);
1114 int ScrollView::GetRefreshInterval() const
1116 return mRefreshIntervalMilliseconds;
1119 void ScrollView::SetRefreshInterval(int milliseconds)
1121 mRefreshIntervalMilliseconds = milliseconds;
1124 bool ScrollView::GetAxisAutoLock() const
1126 return mAxisAutoLock;
1129 void ScrollView::SetAxisAutoLock(bool enable)
1131 mAxisAutoLock = enable;
1132 UpdateMainInternalConstraint();
1135 float ScrollView::GetAxisAutoLockGradient() const
1137 return mAxisAutoLockGradient;
1140 void ScrollView::SetAxisAutoLockGradient(float gradient)
1142 DALI_ASSERT_DEBUG( gradient >= 0.0f && gradient <= 1.0f );
1143 mAxisAutoLockGradient = gradient;
1144 UpdateMainInternalConstraint();
1147 float ScrollView::GetFrictionCoefficient() const
1149 return mFrictionCoefficient;
1152 void ScrollView::SetFrictionCoefficient(float friction)
1154 DALI_ASSERT_DEBUG( friction > 0.0f );
1155 mFrictionCoefficient = friction;
1158 float ScrollView::GetFlickSpeedCoefficient() const
1160 return mFlickSpeedCoefficient;
1163 void ScrollView::SetFlickSpeedCoefficient(float speed)
1165 mFlickSpeedCoefficient = speed;
1168 float ScrollView::GetMaxFlickSpeed() const
1170 return mMaxFlickSpeed;
1173 void ScrollView::SetMaxFlickSpeed(float speed)
1175 mMaxFlickSpeed = speed;
1178 void ScrollView::SetMouseWheelScrollDistanceStep(Vector2 step)
1180 mMouseWheelScrollDistanceStep = step;
1183 Vector2 ScrollView::GetMouseWheelScrollDistanceStep() const
1185 return mMouseWheelScrollDistanceStep;
1188 unsigned int ScrollView::GetCurrentPage() const
1190 // in case animation is currently taking place.
1191 Vector3 position = GetPropertyPosition();
1193 Actor self = Self();
1194 unsigned int page = 0;
1195 unsigned int pagesPerVolume = 1;
1196 unsigned int volume = 0;
1198 // if rulerX is enabled, then get page count (columns)
1199 page = mRulerX->GetPageFromPosition(-position.x, mWrapMode);
1200 volume = mRulerY->GetPageFromPosition(-position.y, mWrapMode);
1201 pagesPerVolume = mRulerX->GetTotalPages();
1203 return volume * pagesPerVolume + page;
1206 Vector3 ScrollView::GetCurrentScrollPosition() const
1208 return -GetPropertyPosition();
1211 void ScrollView::SetScrollPosition(const Vector3& position)
1213 mScrollPrePosition = position;
1216 Vector3 ScrollView::GetCurrentScrollScale() const
1218 // in case animation is currently taking place.
1219 return GetPropertyScale();
1222 Vector3 ScrollView::GetDomainSize() const
1224 Vector3 size = Self().GetCurrentSize();
1226 const RulerDomain& xDomain = GetRulerX()->GetDomain();
1227 const RulerDomain& yDomain = GetRulerY()->GetDomain();
1229 Vector3 domainSize = Vector3( xDomain.max - xDomain.min, yDomain.max - yDomain.min, 0.0f ) - size;
1233 void ScrollView::TransformTo(const Vector3& position, const Vector3& scale, float rotation,
1234 DirectionBias horizontalBias, DirectionBias verticalBias)
1236 TransformTo(position, scale, rotation, mSnapDuration, horizontalBias, verticalBias);
1239 void ScrollView::TransformTo(const Vector3& position, const Vector3& scale, float rotation, float duration,
1240 DirectionBias horizontalBias, DirectionBias verticalBias)
1242 // Guard against destruction during signal emission
1243 // Note that Emit() methods are called indirectly e.g. from within ScrollView::AnimateTo()
1244 Toolkit::ScrollView handle( GetOwner() );
1246 Vector3 currentScrollPosition = GetCurrentScrollPosition();
1247 Self().SetProperty( mPropertyScrollStartPagePosition, currentScrollPosition );
1249 if(mScrolling) // are we interrupting a current scroll?
1251 // set mScrolling to false, in case user has code that interrogates mScrolling Getter() in complete.
1253 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignalV2 1 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
1254 mScrollCompletedSignalV2.Emit( currentScrollPosition );
1257 Self().SetProperty(mPropertyScrolling, true);
1259 mScrollStartedSignalV2.Emit( currentScrollPosition );
1260 bool animating = AnimateTo(-position,
1261 Vector3::ONE * duration,
1263 Vector3::ONE * duration,
1274 // if not animating, then this pan has completed right now.
1275 Self().SetProperty(mPropertyScrolling, false);
1277 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignalV2 2 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
1278 mScrollCompletedSignalV2.Emit( currentScrollPosition );
1282 void ScrollView::ScrollTo(const Vector3& position)
1284 ScrollTo(position, mSnapDuration );
1287 void ScrollView::ScrollTo(const Vector3& position, float duration)
1289 ScrollTo(position, duration, DirectionBiasNone, DirectionBiasNone);
1292 void ScrollView::ScrollTo(const Vector3& position, float duration,
1293 DirectionBias horizontalBias, DirectionBias verticalBias)
1295 TransformTo(position, mScrollPostScale, mScrollPostRotation, duration, horizontalBias, verticalBias);
1298 void ScrollView::ScrollTo(unsigned int page)
1300 ScrollTo(page, mSnapDuration);
1303 void ScrollView::ScrollTo(unsigned int page, float duration, DirectionBias bias)
1306 unsigned int volume;
1307 unsigned int libraries;
1309 // The position to scroll to is continuous and linear
1310 // unless a domain has been enabled on the X axis.
1311 // or if WrapMode has been enabled.
1312 bool carryX = mRulerX->GetDomain().enabled | mWrapMode;
1313 bool carryY = mRulerY->GetDomain().enabled | mWrapMode;
1315 position.x = mRulerX->GetPositionFromPage(page, volume, carryX);
1316 position.y = mRulerY->GetPositionFromPage(volume, libraries, carryY);
1318 ScrollTo(position, duration, bias, bias);
1321 void ScrollView::ScrollTo(Actor &actor)
1323 ScrollTo(actor, mSnapDuration);
1326 void ScrollView::ScrollTo(Actor &actor, float duration)
1328 DALI_ASSERT_ALWAYS(actor.GetParent() == Self());
1330 Actor self = Self();
1331 Vector3 size = self.GetCurrentSize();
1332 Vector3 position = actor.GetCurrentPosition();
1333 position -= GetPropertyPrePosition();
1335 ScrollTo(Vector3(position.x - size.width * 0.5f, position.y - size.height * 0.5f, 0.0f), duration);
1338 Actor ScrollView::FindClosestActor()
1340 Actor self = Self();
1341 Vector3 size = self.GetCurrentSize();
1343 return FindClosestActorToPosition(Vector3(size.width * 0.5f,size.height * 0.5f,0.0f));
1346 Actor ScrollView::FindClosestActorToPosition(const Vector3& position, FindDirection dirX, FindDirection dirY, FindDirection dirZ)
1349 float closestDistance2 = 0.0f;
1350 Vector3 actualPosition = position;
1352 unsigned int numChildren = Self().GetChildCount();
1354 for(unsigned int i = 0; i < numChildren; ++i)
1356 Actor child = Self().GetChildAt(i);
1358 if(mInternalActor == child) // ignore internal actor.
1363 Vector3 childPosition = GetPositionOfAnchor(child, AnchorPoint::CENTER);
1365 Vector3 delta = childPosition - actualPosition;
1367 // X-axis checking (only find Actors to the [dirX] of actualPosition)
1368 if(dirX > All) // != All,None
1370 FindDirection deltaH = delta.x > 0 ? Right : Left;
1377 // Y-axis checking (only find Actors to the [dirY] of actualPosition)
1378 if(dirY > All) // != All,None
1380 FindDirection deltaV = delta.y > 0 ? Down : Up;
1387 // Z-axis checking (only find Actors to the [dirZ] of actualPosition)
1388 if(dirZ > All) // != All,None
1390 FindDirection deltaV = delta.y > 0 ? In : Out;
1397 // compare child to closest child in terms of distance.
1398 float distance2 = 0.0f;
1400 // distance2 = the Square of the relevant dimensions of delta
1403 distance2 += delta.x * delta.x;
1408 distance2 += delta.y * delta.y;
1413 distance2 += delta.z * delta.z;
1416 if(closestChild) // Next time.
1418 if(distance2 < closestDistance2)
1420 closestChild = child;
1421 closestDistance2 = distance2;
1426 closestChild = child;
1427 closestDistance2 = distance2;
1431 return closestChild;
1434 bool ScrollView::ScrollToSnapPoint()
1436 Vector2 stationaryVelocity = Vector2(0.0f, 0.0f);
1437 return SnapWithVelocity( stationaryVelocity );
1440 void ScrollView::ScaleTo(const Vector3& scale)
1442 ScaleTo(scale, mSnapDuration);
1445 void ScrollView::ScaleTo(const Vector3& scale, float duration)
1447 TransformTo(mScrollPostPosition, scale, mScrollPostRotation, duration);
1451 // TODO: In situations where axes are different (X snap, Y free)
1452 // Each axis should really have their own independent animation (time and equation)
1453 // Consider, X axis snapping to nearest grid point (EaseOut over fixed time)
1454 // Consider, Y axis simulating physics to arrive at a point (Physics equation over variable time)
1455 // Currently, the axes have been split however, they both use the same EaseOut equation.
1456 bool ScrollView::SnapWithVelocity(Vector2 velocity)
1458 // Animator takes over now, touches are assumed not to interfere.
1459 // And if touches do interfere, then we'll stop animation, update PrePosition
1460 // to current mScroll's properties, and then resume.
1461 // Note: For Flicking this may work a bit different...
1463 float angle = atan2(velocity.y, velocity.x);
1464 float speed2 = velocity.LengthSquared();
1465 AlphaFunction alphaFunction = mSnapAlphaFunction;
1466 Vector3 positionDuration = Vector3::ONE * mSnapDuration;
1467 Vector3 scaleDuration = Vector3::ONE * mSnapDuration;
1468 float rotationDuration = mSnapDuration;
1471 FindDirection horizontal = None;
1472 FindDirection vertical = None;
1474 // orthoAngleRange = Angle tolerance within the Exact N,E,S,W direction
1475 // that will be accepted as a general N,E,S,W flick direction.
1477 const float orthoAngleRange = FLICK_ORTHO_ANGLE_RANGE * M_PI / 180.0f;
1478 const float flickSpeedThreshold2 = FLICK_SPEED_THRESHOLD*FLICK_SPEED_THRESHOLD;
1480 Vector3 positionSnap = mScrollPrePosition;
1482 // Flick logic X Axis
1484 if(mRulerX->IsEnabled() && mLockAxis != LockHorizontal)
1488 if( speed2 > flickSpeedThreshold2 || // exceeds flick threshold
1489 mInAccessibilityPan ) // With AccessibilityPan its easier to move between snap positions
1491 if((angle >= -orthoAngleRange) && (angle < orthoAngleRange)) // Swiping East
1493 biasX = 0.0f, horizontal = Left;
1495 // This guards against an error where no movement occurs, due to the flick finishing
1496 // before the update-thread has advanced mScrollPostPosition past the the previous snap point.
1497 positionSnap.x += 1.0f;
1499 else if((angle >= M_PI-orthoAngleRange) || (angle < -M_PI+orthoAngleRange)) // Swiping West
1501 biasX = 1.0f, horizontal = Right;
1503 // This guards against an error where no movement occurs, due to the flick finishing
1504 // before the update-thread has advanced mScrollPostPosition past the the previous snap point.
1505 positionSnap.x -= 1.0f;
1510 // Flick logic Y Axis
1512 if(mRulerY->IsEnabled() && mLockAxis != LockVertical)
1516 if( speed2 > flickSpeedThreshold2 || // exceeds flick threshold
1517 mInAccessibilityPan ) // With AccessibilityPan its easier to move between snap positions
1519 if((angle >= M_PI_2-orthoAngleRange) && (angle < M_PI_2+orthoAngleRange)) // Swiping South
1521 biasY = 0.0f, vertical = Up;
1523 else if((angle >= -M_PI_2-orthoAngleRange) && (angle < -M_PI_2+orthoAngleRange)) // Swiping North
1525 biasY = 1.0f, vertical = Down;
1530 // isFlick: Whether this gesture is a flick or not.
1531 bool isFlick = (horizontal != All || vertical != All);
1532 // isFreeFlick: Whether this gesture is a flick under free panning criteria.
1533 bool isFreeFlick = velocity.LengthSquared() > (FREE_FLICK_SPEED_THRESHOLD*FREE_FLICK_SPEED_THRESHOLD);
1535 if(isFlick || isFreeFlick)
1537 positionDuration = Vector3::ONE * mFlickDuration;
1538 alphaFunction = mFlickAlphaFunction;
1541 // Calculate next positionSnap ////////////////////////////////////////////////////////////
1543 if(mActorAutoSnapEnabled)
1545 Vector3 size = Self().GetCurrentSize();
1547 Actor child = FindClosestActorToPosition( Vector3(size.width * 0.5f,size.height * 0.5f,0.0f), horizontal, vertical );
1549 if(!child && isFlick )
1551 // If we conducted a direction limited search and found no actor, then just snap to the closest actor.
1552 child = FindClosestActorToPosition( Vector3(size.width * 0.5f,size.height * 0.5f,0.0f) );
1557 Vector3 position = Self().GetProperty<Vector3>(mPropertyPosition);
1559 // Get center-point of the Actor.
1560 Vector3 childPosition = GetPositionOfAnchor(child, AnchorPoint::CENTER);
1562 if(mRulerX->IsEnabled())
1564 positionSnap.x = position.x - childPosition.x + size.width * 0.5f;
1566 if(mRulerY->IsEnabled())
1568 positionSnap.y = position.y - childPosition.y + size.height * 0.5f;
1573 Vector3 startPosition = positionSnap;
1574 positionSnap.x = -mRulerX->Snap(-positionSnap.x, biasX); // NOTE: X & Y rulers think in -ve coordinate system.
1575 positionSnap.y = -mRulerY->Snap(-positionSnap.y, biasY); // That is scrolling RIGHT (e.g. 100.0, 0.0) means moving LEFT.
1577 Vector3 clampDelta(Vector3::ZERO);
1578 ClampPosition(positionSnap);
1580 if( (mRulerX->GetType() == Ruler::Free || mRulerY->GetType() == Ruler::Free)
1581 && isFreeFlick && !mActorAutoSnapEnabled)
1583 // Calculate target position based on velocity of flick.
1585 // a = Deceleration (Set to diagonal stage length * friction coefficient)
1586 // u = Initial Velocity (Flick velocity)
1587 // v = 0 (Final Velocity)
1588 // t = Time (Velocity / Deceleration)
1589 Vector2 stageSize = Stage::GetCurrent().GetSize();
1590 float stageLength = Vector3(stageSize.x, stageSize.y, 0.0f).Length();
1591 float a = (stageLength * mFrictionCoefficient);
1592 Vector3 u = Vector3(velocity.x, velocity.y, 0.0f) * mFlickSpeedCoefficient;
1593 float speed = u.Length();
1596 // TODO: Change this to a decay function. (faster you flick, the slower it should be)
1597 speed = std::min(speed, stageLength * mMaxFlickSpeed );
1599 alphaFunction = ConstantDecelerationAlphaFunction;
1601 float t = speed / a;
1603 if(mRulerX->IsEnabled() && mRulerX->GetType() == Ruler::Free)
1605 positionSnap.x += t*u.x*0.5f;
1608 if(mRulerY->IsEnabled() && mRulerY->GetType() == Ruler::Free)
1610 positionSnap.y += t*u.y*0.5f;
1613 clampDelta = positionSnap;
1614 ClampPosition(positionSnap);
1615 if((positionSnap - startPosition).LengthSquared() > Math::MACHINE_EPSILON_0)
1617 clampDelta -= positionSnap;
1618 clampDelta.x = clampDelta.x > 0.0f ? std::min(clampDelta.x, mMaxOvershoot.x) : std::max(clampDelta.x, -mMaxOvershoot.x);
1619 clampDelta.y = clampDelta.y > 0.0f ? std::min(clampDelta.y, mMaxOvershoot.y) : std::max(clampDelta.y, -mMaxOvershoot.y);
1623 clampDelta = Vector3::ZERO;
1626 // If Axis is Free and has velocity, then calculate time taken
1627 // to reach target based on velocity in axis.
1628 if(mRulerX->IsEnabled() && mRulerX->GetType() == Ruler::Free)
1630 float deltaX = fabsf(startPosition.x - positionSnap.x);
1632 if(fabsf(u.x) > Math::MACHINE_EPSILON_1)
1634 positionDuration.x = fabsf(deltaX / u.x);
1638 positionDuration.x = 0;
1642 if(mRulerY->IsEnabled() && mRulerY->GetType() == Ruler::Free)
1644 float deltaY = fabsf(startPosition.y - positionSnap.y);
1646 if(fabsf(u.y) > Math::MACHINE_EPSILON_1)
1648 positionDuration.y = fabsf(deltaY / u.y);
1652 positionDuration.y = 0;
1656 positionSnap += clampDelta;
1658 // Scale Snap ///////////////////////////////////////////////////////////////
1659 Vector3 scaleSnap = mScrollPostScale;
1661 scaleSnap.x = mRulerScaleX->Snap(scaleSnap.x);
1662 scaleSnap.y = mRulerScaleY->Snap(scaleSnap.y);
1664 ClampScale(scaleSnap);
1666 // Rotation Snap ////////////////////////////////////////////////////////////
1667 float rotationSnap = mScrollPostRotation;
1668 // TODO: implement rotation snap
1670 bool animating = AnimateTo(positionSnap, positionDuration,
1671 scaleSnap, scaleDuration,
1672 rotationSnap, rotationDuration,
1673 alphaFunction, false,
1674 DirectionBiasNone, DirectionBiasNone,
1675 isFlick || isFreeFlick ? Flick : Snap);
1680 void ScrollView::StopAnimation(void)
1682 // Clear Snap animation if exists.
1683 StopAnimation(mSnapAnimation);
1684 StopAnimation(mInternalXAnimation);
1685 StopAnimation(mInternalYAnimation);
1686 mScrollStateFlags = 0;
1687 // remove scroll animation flags
1688 HandleStoppedAnimation();
1691 void ScrollView::StopAnimation(Animation& animation)
1700 bool ScrollView::AnimateTo(const Vector3& position, const Vector3& positionDuration,
1701 const Vector3& scale, const Vector3& scaleDuration,
1702 float rotation, float rotationDuration,
1703 AlphaFunction alpha, bool findShortcuts,
1704 DirectionBias horizontalBias, DirectionBias verticalBias,
1707 // Here we perform an animation on a number of properties (depending on which have changed)
1708 // The animation is applied to all ScrollBases
1709 Actor self = Self();
1710 mScrollTargetPosition = position;
1711 float totalDuration = 0.0f;
1713 bool positionChanged = (mScrollTargetPosition != mScrollPostPosition);
1714 bool scaleChanged = (scale != mScrollPostScale);
1715 bool rotationChanged = fabsf(rotation - mScrollPostRotation) > Math::MACHINE_EPSILON_0;
1719 totalDuration = std::max(totalDuration, positionDuration.x);
1720 totalDuration = std::max(totalDuration, positionDuration.y);
1724 // try to animate for a frame, on some occasions update will be changing scroll value while event side thinks it hasnt changed
1725 totalDuration = 0.01f;
1726 positionChanged = true;
1731 totalDuration = std::max(totalDuration, scaleDuration.x);
1732 totalDuration = std::max(totalDuration, scaleDuration.y);
1737 totalDuration = std::max(totalDuration, rotationDuration);
1741 // Position Delta ///////////////////////////////////////////////////////
1744 if(mWrapMode && findShortcuts)
1746 // In Wrap Mode, the shortest distance is a little less intuitive...
1747 const RulerDomain rulerDomainX = mRulerX->GetDomain();
1748 const RulerDomain rulerDomainY = mRulerY->GetDomain();
1750 if(mRulerX->IsEnabled())
1752 float dir = VectorInDomain(-mScrollPostPosition.x, -mScrollTargetPosition.x, rulerDomainX.min, rulerDomainX.max, horizontalBias);
1753 mScrollTargetPosition.x = mScrollPostPosition.x + -dir;
1756 if(mRulerY->IsEnabled())
1758 float dir = VectorInDomain(-mScrollPostPosition.y, -mScrollTargetPosition.y, rulerDomainY.min, rulerDomainY.max, verticalBias);
1759 mScrollTargetPosition.y = mScrollPostPosition.y + -dir;
1763 // note we have two separate animations for X & Y, this deals with sliding diagonally and hitting
1764 // a horizonal/vertical wall.delay
1765 AnimateInternalXTo(mScrollTargetPosition.x, positionDuration.x, alpha);
1766 AnimateInternalYTo(mScrollTargetPosition.y, positionDuration.y, alpha);
1768 if( !(mScrollStateFlags & SCROLL_ANIMATION_FLAGS) )
1770 self.SetProperty(mPropertyPrePosition, mScrollTargetPosition);
1771 mScrollPrePosition = mScrollTargetPosition;
1775 // Scale Delta ///////////////////////////////////////////////////////
1778 if(totalDuration > Math::MACHINE_EPSILON_1)
1780 mSnapAnimation = Animation::New(totalDuration);
1781 mSnapAnimation.FinishedSignal().Connect(this, &ScrollView::OnScrollAnimationFinished);
1782 // TODO: for non-uniform scaling to different bounds e.g. scaling a square to a 4:3 aspect ratio screen with a velocity
1783 // the height will hit first, and then the width, so that would require two different animation times just like position.
1784 mSnapAnimation.AnimateTo( Property(self, mPropertyScale), scale, alpha, TimePeriod(0.0f, scaleDuration.x));
1786 mSnapAnimation.AnimateTo( Property(self, mPropertyTime), totalDuration, AlphaFunctions::Linear );
1787 mSnapAnimation.Play();
1791 self.SetProperty(mPropertyScale, scale);
1793 mScrollPreScale = mScrollPostScale = scale;
1796 StartRefreshTimer();
1798 // Always send a snap event when AnimateTo is called.
1799 Toolkit::ScrollView::SnapEvent snapEvent;
1800 snapEvent.type = snapType;
1801 snapEvent.position = -mScrollTargetPosition;
1802 snapEvent.scale = scale;
1803 snapEvent.rotation = rotation;
1804 snapEvent.duration = totalDuration;
1806 mSnapStartedSignalV2.Emit( snapEvent );
1808 return (mScrollStateFlags & SCROLL_ANIMATION_FLAGS) != 0;
1811 void ScrollView::SetOvershootEnabled(bool enabled)
1813 if(enabled && !mOvershootIndicator)
1815 mOvershootIndicator = ScrollOvershootIndicator::New();
1819 mMaxOvershoot = OVERSCROLL_CLAMP;
1820 mOvershootIndicator->AttachToScrollable(*this);
1824 mMaxOvershoot = mUserMaxOvershoot;
1825 mOvershootIndicator->DetachFromScrollable(*this);
1827 UpdateMainInternalConstraint();
1830 void ScrollView::AddOverlay(Actor actor)
1832 mInternalActor.Add( actor );
1835 void ScrollView::RemoveOverlay(Actor actor)
1837 mInternalActor.Remove( actor );
1840 void ScrollView::SetScrollingDirection( Radian direction, Radian threshold )
1842 PanGestureDetector panGesture( GetPanGestureDetector() );
1844 // First remove just in case we have some set, then add.
1845 panGesture.RemoveDirection( direction );
1846 panGesture.AddDirection( direction, threshold );
1849 void ScrollView::RemoveScrollingDirection( Radian direction )
1851 PanGestureDetector panGesture( GetPanGestureDetector() );
1852 panGesture.RemoveDirection( direction );
1855 Toolkit::ScrollView::SnapStartedSignalV2& ScrollView::SnapStartedSignal()
1857 return mSnapStartedSignalV2;
1860 void ScrollView::FindAndUnbindActor(Actor child)
1865 Vector3 ScrollView::GetPropertyPrePosition() const
1867 Vector3 position = Self().GetProperty<Vector3>(mPropertyPrePosition);
1868 WrapPosition(position);
1872 Vector3 ScrollView::GetPropertyPosition() const
1874 Vector3 position = Self().GetProperty<Vector3>(mPropertyPosition);
1875 WrapPosition(position);
1880 Vector3 ScrollView::GetPropertyScale() const
1882 return Self().GetProperty<Vector3>(mPropertyScale);
1885 void ScrollView::HandleStoppedAnimation()
1887 // Animation has stopped, so stop sending the scroll-update signal.
1888 CancelRefreshTimer();
1891 void ScrollView::HandleSnapAnimationFinished()
1893 // Emit Signal that scrolling has completed.
1895 Actor self = Self();
1896 self.SetProperty(mPropertyScrolling, false);
1898 Vector3 deltaPosition(mScrollPrePosition);
1900 UpdateLocalScrollProperties();
1901 WrapPosition(mScrollPrePosition);
1902 self.SetProperty(mPropertyPrePosition, mScrollPrePosition);
1904 Vector3 currentScrollPosition = GetCurrentScrollPosition();
1905 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignalV2 3 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
1906 mScrollCompletedSignalV2.Emit( currentScrollPosition );
1908 mDomainOffset += deltaPosition - mScrollPostPosition;
1909 self.SetProperty(mPropertyDomainOffset, mDomainOffset);
1910 HandleStoppedAnimation();
1913 bool ScrollView::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
1915 Dali::BaseHandle handle( object );
1917 bool connected( true );
1918 Toolkit::ScrollView view = Toolkit::ScrollView::DownCast( handle );
1920 if( Toolkit::ScrollView::SIGNAL_SNAP_STARTED == signalName )
1922 view.SnapStartedSignal().Connect( tracker, functor );
1926 // signalName does not match any signal
1933 void ScrollView::OnSizeAnimation(Animation& animation, const Vector3& targetSize)
1935 // need to update domain properties for new size
1936 UpdatePropertyDomain(targetSize);
1939 void ScrollView::OnControlSizeSet( const Vector3& size )
1941 // need to update domain properties for new size
1942 if( mDefaultMaxOvershoot )
1944 mUserMaxOvershoot.x = size.x * 0.5f;
1945 mUserMaxOvershoot.y = size.y * 0.5f;
1946 if( !IsScrollComponentEnabled(Toolkit::Scrollable::OvershootIndicator) )
1948 mMaxOvershoot = mUserMaxOvershoot;
1951 UpdatePropertyDomain(size);
1952 UpdateMainInternalConstraint();
1953 if( IsScrollComponentEnabled(Toolkit::Scrollable::OvershootIndicator) )
1955 mOvershootIndicator->Reset();
1959 void ScrollView::OnChildAdd(Actor& child)
1967 void ScrollView::OnChildRemove(Actor& child)
1969 // TODO: Actor needs a RemoveConstraint method to take out an individual constraint.
1973 void ScrollView::OnPropertySet( Property::Index index, Property::Value propertyValue )
1975 Actor self = Self();
1976 if( index == mPropertyX )
1978 self.GetProperty(mPropertyPrePosition).Get(mScrollPrePosition);
1979 propertyValue.Get(mScrollPrePosition.x);
1980 self.SetProperty(mPropertyPrePosition, mScrollPrePosition);
1982 else if( index == mPropertyY )
1984 self.GetProperty(mPropertyPrePosition).Get(mScrollPrePosition);
1985 propertyValue.Get(mScrollPrePosition.y);
1986 self.SetProperty(mPropertyPrePosition, mScrollPrePosition);
1988 else if( index == mPropertyPrePosition )
1990 DALI_LOG_SCROLL_STATE("[0x%X]", this);
1991 propertyValue.Get(mScrollPrePosition);
1995 void ScrollView::StartTouchDownTimer()
1997 if ( !mTouchDownTimer )
1999 mTouchDownTimer = Timer::New( TOUCH_DOWN_TIMER_INTERVAL );
2000 mTouchDownTimer.TickSignal().Connect( this, &ScrollView::OnTouchDownTimeout );
2003 mTouchDownTimer.Start();
2006 void ScrollView::StopTouchDownTimer()
2008 if ( mTouchDownTimer )
2010 mTouchDownTimer.Stop();
2014 bool ScrollView::OnTouchDownTimeout()
2016 mTouchDownTimeoutReached = true;
2018 if( mScrollStateFlags & (SCROLL_ANIMATION_FLAGS | SNAP_ANIMATION_FLAGS) )
2021 if( mScrollStateFlags & SCROLL_ANIMATION_FLAGS )
2023 mScrollInterrupted = true;
2024 // reset domain offset as scrolling from original plane.
2025 mDomainOffset = Vector3::ZERO;
2026 Self().SetProperty(mPropertyDomainOffset, Vector3::ZERO);
2028 UpdateLocalScrollProperties();
2029 Vector3 currentScrollPosition = GetCurrentScrollPosition();
2030 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignalV2 4 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
2031 mScrollCompletedSignalV2.Emit( currentScrollPosition );
2038 bool ScrollView::OnTouchEvent(const TouchEvent& event)
2042 // Ignore this touch event, if scrollview is insensitive.
2046 // Ignore events with multiple-touch points
2047 if (event.GetPointCount() != 1)
2052 if( event.GetPoint(0).state == TouchPoint::Down )
2054 if(mGestureStackDepth==0)
2056 mTouchDownTime = event.time;
2058 // This allows time for a pan-gesture to start, to avoid breaking snap-animation behavior with fast flicks.
2059 // If touch-down does not become a pan (after timeout interval), then snap-animation can be interrupted.
2060 StartTouchDownTimer();
2063 else if( event.GetPoint(0).state == TouchPoint::Up )
2065 StopTouchDownTimer();
2067 // if the user touches and releases without enough movement to go
2068 // into a gesture state, then we should snap to nearest point.
2069 // otherwise our scroll could be stopped (interrupted) half way through an animation.
2070 if(mGestureStackDepth==0 && mTouchDownTimeoutReached)
2072 unsigned timeDelta( event.time - mTouchDownTime );
2073 if ( timeDelta >= MINIMUM_TIME_BETWEEN_DOWN_AND_UP_FOR_RESET )
2075 // Reset the velocity only if down was received a while ago
2076 mLastVelocity = Vector2( 0.0f, 0.0f );
2079 UpdateLocalScrollProperties();
2080 // Only finish the transform if scrolling was interrupted on down or if we are scrolling
2081 if ( mScrollInterrupted || mScrolling )
2086 mTouchDownTimeoutReached = false;
2087 mScrollInterrupted = false;
2093 bool ScrollView::OnMouseWheelEvent(const MouseWheelEvent& event)
2097 // Ignore this mouse wheel event, if scrollview is insensitive.
2101 Vector3 targetScrollPosition = GetPropertyPosition();
2103 if(mRulerX->IsEnabled() && !mRulerY->IsEnabled())
2105 // If only the ruler in the X axis is enabled, scroll in the X axis.
2106 if(mRulerX->GetType() == Ruler::Free)
2108 // Free panning mode
2109 targetScrollPosition.x += event.z * mMouseWheelScrollDistanceStep.x;
2110 ClampPosition(targetScrollPosition);
2111 ScrollTo(-targetScrollPosition);
2113 else if(!mScrolling)
2115 // Snap mode, only respond to the event when the previous snap animation is finished.
2116 ScrollTo(GetCurrentPage() - event.z);
2121 // If the ruler in the Y axis is enabled, scroll in the Y axis.
2122 if(mRulerY->GetType() == Ruler::Free)
2124 // Free panning mode
2125 targetScrollPosition.y += event.z * mMouseWheelScrollDistanceStep.y;
2126 ClampPosition(targetScrollPosition);
2127 ScrollTo(-targetScrollPosition);
2129 else if(!mScrolling)
2131 // Snap mode, only respond to the event when the previous snap animation is finished.
2132 ScrollTo(GetCurrentPage() - event.z * mRulerX->GetTotalPages());
2139 void ScrollView::ResetScrolling()
2141 Actor self = Self();
2142 self.GetProperty(mPropertyPosition).Get(mScrollPostPosition);
2143 mScrollPrePosition = mScrollPostPosition;
2144 self.SetProperty(mPropertyPrePosition, mScrollPostPosition);
2147 void ScrollView::UpdateLocalScrollProperties()
2149 Actor self = Self();
2150 self.GetProperty(mPropertyPrePosition).Get(mScrollPrePosition);
2151 self.GetProperty(mPropertyPosition).Get(mScrollPostPosition);
2154 // private functions
2156 void ScrollView::PreAnimatedScrollSetup()
2158 // mPropertyPrePosition is our unclamped property with wrapping
2159 // mPropertyPosition is our final scroll position after clamping
2161 Actor self = Self();
2163 Vector3 deltaPosition(mScrollPostPosition);
2164 WrapPosition(mScrollPostPosition);
2165 mDomainOffset += deltaPosition - mScrollPostPosition;
2166 Self().SetProperty(mPropertyDomainOffset, mDomainOffset);
2168 if( mScrollStateFlags & SCROLL_X_STATE_MASK )
2170 // already performing animation on internal x position
2171 StopAnimation(mInternalXAnimation);
2174 if( mScrollStateFlags & SCROLL_Y_STATE_MASK )
2176 // already performing animation on internal y position
2177 StopAnimation(mInternalYAnimation);
2180 mScrollStateFlags = 0;
2182 mScrollPostScale = GetPropertyScale();
2184 // Update Actor position with this wrapped value.
2187 mScrollPreScale = mScrollPostScale;
2188 mScrollPreRotation = mScrollPostRotation;
2191 void ScrollView::FinaliseAnimatedScroll()
2193 // TODO - common animation finishing code in here
2196 void ScrollView::AnimateInternalXTo( float position, float duration, AlphaFunction alpha )
2198 StopAnimation(mInternalXAnimation);
2200 if( duration > Math::MACHINE_EPSILON_10 )
2202 Actor self = Self();
2203 mInternalXAnimation = Animation::New(duration);
2204 mInternalXAnimation.FinishedSignal().Connect(this, &ScrollView::OnScrollAnimationFinished);
2205 mInternalXAnimation.AnimateTo( Property(self, mPropertyPrePosition, 0), position, alpha, duration);
2206 mInternalXAnimation.Play();
2208 // erase current state flags
2209 mScrollStateFlags &= ~SCROLL_X_STATE_MASK;
2210 // add internal animation state flag
2211 mScrollStateFlags |= AnimatingInternalX;
2215 void ScrollView::AnimateInternalYTo( float position, float duration, AlphaFunction alpha )
2217 StopAnimation(mInternalYAnimation);
2219 if( duration > Math::MACHINE_EPSILON_10 )
2221 Actor self = Self();
2222 mInternalYAnimation = Animation::New(duration);
2223 mInternalYAnimation.FinishedSignal().Connect(this, &ScrollView::OnScrollAnimationFinished);
2224 mInternalYAnimation.AnimateTo( Property(self, mPropertyPrePosition, 1), position, alpha, TimePeriod(duration));
2225 mInternalYAnimation.Play();
2227 // erase current state flags
2228 mScrollStateFlags &= ~SCROLL_Y_STATE_MASK;
2229 // add internal animation state flag
2230 mScrollStateFlags |= AnimatingInternalY;
2234 void ScrollView::OnScrollAnimationFinished( Animation& source )
2236 // Guard against destruction during signal emission
2237 // Note that ScrollCompletedSignal is emitted from HandleSnapAnimationFinished()
2238 Toolkit::ScrollView handle( GetOwner() );
2240 bool scrollingFinished = false;
2242 // update our local scroll positions
2243 UpdateLocalScrollProperties();
2245 if( source == mSnapAnimation )
2247 // generic snap animation used for scaling and rotation
2248 mSnapAnimation.Reset();
2251 if( source == mInternalXAnimation )
2253 if( !(mScrollStateFlags & AnimatingInternalY) )
2255 scrollingFinished = true;
2257 mInternalXAnimation.Reset();
2258 SnapInternalXTo(mScrollPostPosition.x);
2261 if( source == mInternalYAnimation )
2263 if( !(mScrollStateFlags & AnimatingInternalX) )
2265 scrollingFinished = true;
2267 mInternalYAnimation.Reset();
2268 SnapInternalYTo(mScrollPostPosition.y);
2271 if(scrollingFinished)
2273 HandleSnapAnimationFinished();
2277 void ScrollView::OnSnapInternalPositionFinished( Animation& source )
2279 Actor self = Self();
2280 UpdateLocalScrollProperties();
2281 if( source == mInternalXAnimation )
2283 // clear internal x animation flags
2284 mScrollStateFlags &= ~SCROLL_X_STATE_MASK;
2285 mInternalXAnimation.Reset();
2286 WrapPosition(mScrollPrePosition);
2288 if( source == mInternalYAnimation )
2290 mScrollStateFlags &= ~SCROLL_Y_STATE_MASK;
2291 mInternalYAnimation.Reset();
2292 WrapPosition(mScrollPrePosition);
2296 void ScrollView::SnapInternalXTo(float position)
2298 Actor self = Self();
2300 StopAnimation(mInternalXAnimation);
2302 // erase current state flags
2303 mScrollStateFlags &= ~SCROLL_X_STATE_MASK;
2305 // if internal x not equal to inputed parameter, animate it
2306 float duration = std::min(fabsf((position - mScrollPrePosition.x) / mMaxOvershoot.x) * mSnapOvershootDuration, mSnapOvershootDuration);
2307 if( duration > Math::MACHINE_EPSILON_1 )
2309 mInternalXAnimation = Animation::New(duration);
2310 mInternalXAnimation.FinishedSignal().Connect(this, &ScrollView::OnSnapInternalPositionFinished);
2311 mInternalXAnimation.AnimateTo(Property(self, mPropertyPrePosition, 0), position);
2312 mInternalXAnimation.Play();
2314 // add internal animation state flag
2315 mScrollStateFlags |= SnappingInternalX;
2319 void ScrollView::SnapInternalYTo(float position)
2321 Actor self = Self();
2323 StopAnimation(mInternalYAnimation);
2325 // erase current state flags
2326 mScrollStateFlags &= ~SCROLL_Y_STATE_MASK;
2328 // if internal y not equal to inputed parameter, animate it
2329 float duration = std::min(fabsf((position - mScrollPrePosition.y) / mMaxOvershoot.y) * mSnapOvershootDuration, mSnapOvershootDuration);
2330 if( duration > Math::MACHINE_EPSILON_1 )
2332 mInternalYAnimation = Animation::New(duration);
2333 mInternalYAnimation.FinishedSignal().Connect(this, &ScrollView::OnSnapInternalPositionFinished);
2334 mInternalYAnimation.AnimateTo(Property(self, mPropertyPrePosition, 1), position);
2335 mInternalYAnimation.Play();
2337 // add internal animation state flag
2338 mScrollStateFlags |= SnappingInternalY;
2342 void ScrollView::GestureStarted()
2344 // we handle the first gesture.
2345 // if we're currently doing a gesture and receive another
2346 // we continue and combine the effects of the gesture instead of reseting.
2347 if(mGestureStackDepth++==0)
2349 Actor self = Self();
2350 StopTouchDownTimer();
2352 mPanDelta = Vector3::ZERO;
2353 mScaleDelta = Vector3::ONE;
2354 mRotationDelta = 0.0f;
2355 mLastVelocity = Vector2(0.0f, 0.0f);
2358 mLockAxis = LockPossible;
2361 if( mScrollStateFlags & SCROLL_X_STATE_MASK )
2363 StopAnimation(mInternalXAnimation);
2365 if( mScrollStateFlags & SCROLL_Y_STATE_MASK )
2367 StopAnimation(mInternalYAnimation);
2369 mScrollStateFlags = 0;
2371 if(mScrolling) // are we interrupting a current scroll?
2373 // set mScrolling to false, in case user has code that interrogates mScrolling Getter() in complete.
2375 // send negative scroll position since scroll internal scroll position works as an offset for actors,
2376 // give applications the position within the domain from the scroll view's anchor position
2377 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignalV2 5 [%.2f, %.2f]", this, -mScrollPostPosition.x, -mScrollPostPosition.y);
2378 mScrollCompletedSignalV2.Emit( -mScrollPostPosition );
2383 void ScrollView::GestureContinuing(const Vector2& panDelta, const Vector2& scaleDelta, float rotationDelta)
2385 mPanDelta.x+= panDelta.x;
2386 mPanDelta.y+= panDelta.y;
2387 mScaleDelta.x*= scaleDelta.x;
2388 mScaleDelta.y*= scaleDelta.y;
2389 mRotationDelta+= rotationDelta;
2391 // Save the velocity, there is a bug in PanGesture
2392 // Whereby the Gesture::Finished's velocity is either:
2393 // NaN (due to time delta of zero between the last two events)
2394 // or 0 (due to position being the same between the last two events)
2396 // Axis Auto Lock - locks the panning to the horizontal or vertical axis if the pan
2397 // appears mostly horizontal or mostly vertical respectively.
2400 mLockAxis = GetLockAxis(mPanDelta.GetVectorXY(), mLockAxis, mAxisAutoLockGradient);
2401 } // end if mAxisAutoLock
2404 // TODO: Upgrade to use a more powerful gesture detector (one that supports multiple touches on pan - so works as pan and flick gesture)
2405 // TODO: Reimplement Scaling (pinching 2+ points)
2406 // TODO: Reimplment Rotation (pinching 2+ points)
2407 // BUG: Gesture::Finished doesn't always return velocity on release (due to
2408 // timeDelta between last two events being 0 sometimes, or posiiton being the same)
2409 void ScrollView::OnPan(PanGesture gesture)
2411 // Guard against destruction during signal emission
2412 // Note that Emit() methods are called indirectly e.g. from within ScrollView::OnGestureEx()
2413 Actor self( Self() );
2417 // If another callback on the same original signal disables sensitivity,
2418 // this callback will still be called, so we must suppress it.
2422 // translate Gesture input to get useful data...
2423 switch(gesture.state)
2425 case Gesture::Started:
2427 UpdateLocalScrollProperties();
2430 self.SetProperty( mPropertyPanning, true );
2431 self.SetProperty( mPropertyScrollStartPagePosition, Vector3(gesture.position.x, gesture.position.y, 0.0f) );
2433 UpdateMainInternalConstraint();
2437 case Gesture::Continuing:
2439 GestureContinuing(gesture.screenDisplacement, Vector2::ZERO, 0.0f);
2443 case Gesture::Finished:
2444 case Gesture::Cancelled:
2446 UpdateLocalScrollProperties();
2447 mLastVelocity = gesture.velocity;
2449 self.SetProperty( mPropertyPanning, false );
2451 if( mScrollMainInternalPrePositionConstraint )
2453 self.RemoveConstraint(mScrollMainInternalPrePositionConstraint);
2458 case Gesture::Possible:
2459 case Gesture::Clear:
2461 // Nothing to do, not needed.
2465 } // end switch(gesture.state)
2467 OnGestureEx(gesture.state);
2470 void ScrollView::OnGestureEx(Gesture::State state)
2472 // call necessary signals for application developer
2474 if(state == Gesture::Started)
2476 Vector3 currentScrollPosition = GetCurrentScrollPosition();
2477 Self().SetProperty(mPropertyScrolling, true);
2479 mScrollStartedSignalV2.Emit( currentScrollPosition );
2481 else if( (state == Gesture::Finished) ||
2482 (state == Gesture::Cancelled) ) // Finished/default
2484 // when all the gestures have finished, we finish the transform.
2485 // so if a user decides to pan (1 gesture), and then pan+zoom (2 gestures)
2486 // then stop panning (back to 1 gesture), and then stop zooming (0 gestures).
2487 // this is the point we end, and perform necessary snapping.
2488 mGestureStackDepth--;
2489 if(mGestureStackDepth==0)
2496 void ScrollView::UpdateTransform()
2498 // TODO: notify clamps using property notifications (or see if we need this, can deprecate it)
2501 void ScrollView::FinishTransform()
2503 // at this stage internal x and x scroll position should have followed prescroll position exactly
2504 Actor self = Self();
2506 PreAnimatedScrollSetup();
2508 bool animating = SnapWithVelocity(mLastVelocity * 1000.0f);
2512 // if not animating, then this pan has completed right now.
2514 Self().SetProperty(mPropertyScrolling, false);
2515 Vector3 currentScrollPosition = GetCurrentScrollPosition();
2516 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignalV2 6 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
2517 mScrollCompletedSignalV2.Emit( currentScrollPosition );
2521 Vector3 ScrollView::GetOvershoot(Vector3& position) const
2523 Vector3 size = Self().GetCurrentSize();
2526 const RulerDomain rulerDomainX = mRulerX->GetDomain();
2527 const RulerDomain rulerDomainY = mRulerY->GetDomain();
2529 if(mRulerX->IsEnabled() && rulerDomainX.enabled)
2531 const float left = rulerDomainX.min - position.x;
2532 const float right = size.width - rulerDomainX.max - position.x;
2539 overshoot.x = right;
2543 if(mRulerY->IsEnabled() && rulerDomainY.enabled)
2545 const float top = rulerDomainY.min - position.y;
2546 const float bottom = size.height - rulerDomainY.max - position.y;
2553 overshoot.y = bottom;
2560 bool ScrollView::OnAccessibilityPan(PanGesture gesture)
2562 // Keep track of whether this is an AccessibilityPan
2563 mInAccessibilityPan = true;
2565 mInAccessibilityPan = false;
2570 void ScrollView::ClampPosition(Vector3& position) const
2572 ClampState3 clamped;
2573 ClampPosition(position, clamped);
2576 void ScrollView::ClampPosition(Vector3& position, ClampState3 &clamped) const
2578 Vector3 size = Self().GetCurrentSize();
2580 // determine size of viewport relative to current scaled size.
2581 // e.g. if you're zoomed in 200%, then each pixel on screen is only 0.5 pixels on subject.
2582 if(fabsf(mScrollPostScale.x) > Math::MACHINE_EPSILON_0)
2584 size.x /= mScrollPostScale.x;
2587 if(fabsf(mScrollPostScale.y) > Math::MACHINE_EPSILON_0)
2589 size.y /= mScrollPostScale.y;
2592 position.x = -mRulerX->Clamp(-position.x, size.width, 1.0f, clamped.x); // NOTE: X & Y rulers think in -ve coordinate system.
2593 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.
2595 clamped.z = NotClamped;
2598 void ScrollView::WrapPosition(Vector3& position) const
2602 const RulerDomain rulerDomainX = mRulerX->GetDomain();
2603 const RulerDomain rulerDomainY = mRulerY->GetDomain();
2605 if(mRulerX->IsEnabled())
2607 position.x = -WrapInDomain(-position.x, rulerDomainX.min, rulerDomainX.max);
2610 if(mRulerY->IsEnabled())
2612 position.y = -WrapInDomain(-position.y, rulerDomainY.min, rulerDomainY.max);
2617 void ScrollView::ClampScale(Vector3& scale) const
2619 ClampState3 clamped;
2620 ClampScale(scale, clamped);
2623 void ScrollView::ClampScale(Vector3& scale, ClampState3 &clamped) const
2625 scale.x = mRulerScaleX->Clamp(scale.x, 0.0f, 1.0f, clamped.x);
2626 scale.y = mRulerScaleY->Clamp(scale.y, 0.0f, 1.0f, clamped.y);
2627 clamped.z = NotClamped;
2630 void ScrollView::UpdateMainInternalConstraint()
2632 // TODO: Only update the constraints which have changed, rather than remove all and add all again.
2633 // Requires a dali-core ApplyConstraintAt, or a ReplaceConstraint. The former is probably more flexible.
2634 Actor self = Self();
2635 PanGestureDetector detector( GetPanGestureDetector() );
2637 if(mScrollMainInternalPositionConstraint)
2639 self.RemoveConstraint(mScrollMainInternalPositionConstraint);
2640 self.RemoveConstraint(mScrollMainInternalDeltaConstraint);
2641 self.RemoveConstraint(mScrollMainInternalFinalConstraint);
2642 self.RemoveConstraint(mScrollMainInternalRelativeConstraint);
2643 self.RemoveConstraint(mScrollMainInternalXConstraint);
2644 self.RemoveConstraint(mScrollMainInternalYConstraint);
2646 if( mScrollMainInternalPrePositionConstraint )
2648 self.RemoveConstraint(mScrollMainInternalPrePositionConstraint);
2651 // TODO: It's probably better to use a local displacement value as this will give a displacement when scrolling just commences
2652 // but we need to make sure than the gesture system gives displacement since last frame (60Hz), not displacement since last touch event (90Hz).
2654 // 1. First calculate the pre-position (this is the scroll position if no clamping has taken place)
2655 Vector2 initialPanMask = Vector2(mRulerX->IsEnabled() ? 1.0f : 0.0f, mRulerY->IsEnabled() ? 1.0f : 0.0f);
2657 if( mLockAxis == LockVertical )
2659 initialPanMask.y = 0.0f;
2661 else if( mLockAxis == LockHorizontal )
2663 initialPanMask.x = 0.0f;
2665 Constraint constraint;
2669 constraint = Constraint::New<Vector3>( mPropertyPrePosition,
2670 Source( detector, PanGestureDetector::LOCAL_POSITION ),
2671 Source( detector, PanGestureDetector::LOCAL_DISPLACEMENT ),
2672 Source( self, Actor::SIZE ),
2673 InternalPrePositionConstraint( initialPanMask, mAxisAutoLock, mAxisAutoLockGradient, mLockAxis, mMaxOvershoot, mRulerX->GetDomain(), mRulerY->GetDomain() ) );
2674 mScrollMainInternalPrePositionConstraint = self.ApplyConstraint( constraint );
2677 // 2. Second calculate the clamped position (actual position)
2678 constraint = Constraint::New<Vector3>( mPropertyPosition,
2679 LocalSource( mPropertyPrePosition ),
2680 LocalSource( mPropertyPositionMin ),
2681 LocalSource( mPropertyPositionMax ),
2682 Source( self, Actor::SIZE ),
2683 InternalPositionConstraint( mRulerX->GetDomain(),
2684 mRulerY->GetDomain(), mWrapMode ) );
2685 mScrollMainInternalPositionConstraint = self.ApplyConstraint( constraint );
2687 constraint = Constraint::New<Vector3>( mPropertyPositionDelta,
2688 LocalSource( mPropertyPosition ),
2689 LocalSource( mPropertyDomainOffset ),
2690 InternalPositionDeltaConstraint );
2691 mScrollMainInternalDeltaConstraint = self.ApplyConstraint( constraint );
2693 constraint = Constraint::New<Vector3>( mPropertyFinal,
2694 LocalSource( mPropertyPosition ),
2695 LocalSource( mPropertyOvershootX ),
2696 LocalSource( mPropertyOvershootY ),
2697 InternalFinalConstraint( FinalDefaultAlphaFunction,
2698 FinalDefaultAlphaFunction ) );
2699 mScrollMainInternalFinalConstraint = self.ApplyConstraint( constraint );
2701 constraint = Constraint::New<Vector3>( mPropertyRelativePosition,
2702 LocalSource( mPropertyPosition ),
2703 LocalSource( mPropertyPositionMin ),
2704 LocalSource( mPropertyPositionMax ),
2705 LocalSource( Actor::SIZE ),
2706 InternalRelativePositionConstraint );
2707 mScrollMainInternalRelativeConstraint = self.ApplyConstraint( constraint );
2709 constraint = Constraint::New<float>( mPropertyX,
2710 LocalSource( mPropertyPrePosition ),
2711 InternalXConstraint );
2712 mScrollMainInternalXConstraint = self.ApplyConstraint( constraint );
2714 constraint = Constraint::New<float>( mPropertyY,
2715 LocalSource( mPropertyPrePosition ),
2716 InternalYConstraint );
2717 mScrollMainInternalYConstraint = self.ApplyConstraint( constraint );
2719 // When panning we want to make sure overshoot values are affected by pre position and post position
2720 SetOvershootConstraintsEnabled(!mWrapMode);
2723 void ScrollView::SetOvershootConstraintsEnabled(bool enabled)
2725 Actor self( Self() );
2726 // remove and reset, it may now be in wrong order with the main internal constraints
2727 if( mScrollMainInternalOvershootXConstraint )
2729 self.RemoveConstraint(mScrollMainInternalOvershootXConstraint);
2730 mScrollMainInternalOvershootXConstraint.Reset();
2731 self.RemoveConstraint(mScrollMainInternalOvershootYConstraint);
2732 mScrollMainInternalOvershootYConstraint.Reset();
2736 Constraint constraint = Constraint::New<float>( mPropertyOvershootX,
2737 LocalSource( mPropertyPrePosition ),
2738 LocalSource( mPropertyPosition ),
2739 LocalSource( mPropertyCanScrollHorizontal ),
2740 OvershootXConstraint(mMaxOvershoot.x) );
2741 mScrollMainInternalOvershootXConstraint = self.ApplyConstraint( constraint );
2743 constraint = Constraint::New<float>( mPropertyOvershootY,
2744 LocalSource( mPropertyPrePosition ),
2745 LocalSource( mPropertyPosition ),
2746 LocalSource( mPropertyCanScrollVertical ),
2747 OvershootYConstraint(mMaxOvershoot.y) );
2748 mScrollMainInternalOvershootYConstraint = self.ApplyConstraint( constraint );
2752 self.SetProperty(mPropertyOvershootX, 0.0f);
2753 self.SetProperty(mPropertyOvershootY, 0.0f);
2757 void ScrollView::SetInternalConstraints()
2759 // Internal constraints (applied to target ScrollBase Actor itself) /////////
2760 UpdateMainInternalConstraint();
2762 // User definable constraints to apply to all child actors //////////////////
2763 Actor self = Self();
2765 // LocalSource - The Actors to be moved.
2766 // self - The ScrollView
2768 // Apply some default constraints to ScrollView.
2769 // Movement + Scaling + Wrap function
2771 Constraint constraint;
2773 // MoveScaledActor (scrolling/zooming)
2774 constraint = Constraint::New<Vector3>( Actor::POSITION,
2775 Source( self, mPropertyPosition ),
2776 Source( self, mPropertyScale ),
2777 MoveScaledActorConstraint );
2778 constraint.SetRemoveAction(Constraint::Discard);
2779 ApplyConstraintToBoundActors(constraint);
2781 // ScaleActor (scrolling/zooming)
2782 constraint = Constraint::New<Vector3>( Actor::SCALE,
2783 Source( self, mPropertyScale ),
2784 ScaleActorConstraint );
2785 constraint.SetRemoveAction(Constraint::Discard);
2786 ApplyConstraintToBoundActors(constraint);
2788 // WrapActor (wrap functionality)
2789 constraint = Constraint::New<Vector3>( Actor::POSITION,
2790 LocalSource( Actor::SCALE ),
2791 LocalSource( Actor::ANCHOR_POINT ),
2792 LocalSource( Actor::SIZE ),
2793 Source( self, mPropertyPositionMin ),
2794 Source( self, mPropertyPositionMax ),
2795 Source( self, mPropertyWrap ),
2796 WrapActorConstraint );
2797 constraint.SetRemoveAction(Constraint::Discard);
2798 ApplyConstraintToBoundActors(constraint);
2801 void ScrollView::StartRefreshTimer()
2803 if(mRefreshIntervalMilliseconds > 0)
2807 mRefreshTimer = Timer::New( mRefreshIntervalMilliseconds );
2808 mRefreshTimer.TickSignal().Connect( this, &ScrollView::OnRefreshTick );
2811 if (!mRefreshTimer.IsRunning())
2813 mRefreshTimer.Start();
2818 void ScrollView::CancelRefreshTimer()
2822 mRefreshTimer.Stop();
2826 bool ScrollView::OnRefreshTick()
2828 // Guard against destruction during signal emission
2829 Toolkit::ScrollView handle( GetOwner() );
2831 Vector3 currentScrollPosition = GetCurrentScrollPosition();
2832 mScrollUpdatedSignalV2.Emit( currentScrollPosition );
2837 } // namespace Internal
2839 } // namespace Toolkit