2 // Copyright (c) 2014 Samsung Electronics Co., Ltd.
4 // Licensed under the Flora License, Version 1.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://floralicense.org/license/
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.
18 #include <dali/public-api/events/mouse-wheel-event.h>
20 #include <dali-toolkit/public-api/controls/scrollable/scroll-view/scroll-view-constraints.h>
21 #include <dali-toolkit/public-api/controls/scrollable/scroll-component-impl.h>
22 #include <dali-toolkit/internal/controls/scrollable/scroll-view/scroll-view-impl.h>
23 #include <dali-toolkit/internal/controls/scrollable/scroll-view/scroll-view-effect-impl.h>
24 #include <dali-toolkit/internal/controls/scrollable/scroll-view/scroll-overshoot-indicator-impl.h>
26 // TODO: Change to two class system:
27 // 1. DraggableActor (is an actor which can be dragged anywhere/scaled/rotated, can be set to range using the ruler)
28 // 2. ScrollView (contains a draggable actor that can a) be dragged in the negative X, and Y domain, b) has a hitArea for touches)
30 // TODO: Asymetrical scaling
31 // TODO: external components (page and status overlays).
33 // TODO: upgrade Vector2/3 to support returning Unit vectors, normals, & cross product (dot product is already provided)
40 const int DEFAULT_REFRESH_INTERVAL_MILLISECONDS = 50; ///< Refresh rate TODO: Animation should have an update signal (and see item-view-impl)
41 const float FLICK_SPEED_THRESHOLD = 500.0f; ///< Flick threshold in pixels/ms
42 const float FREE_FLICK_SPEED_THRESHOLD = 200.0f; ///< Free-Flick threshold in pixels/ms
43 const float AUTOLOCK_AXIS_MINIMUM_DISTANCE2 = 100.0f; ///< Auto-lock axis after minimum distance squared.
44 const float FLICK_ORTHO_ANGLE_RANGE = 60.0f; ///< degrees. (if >45, then supports diagonal flicking)
45 const unsigned int MAXIMUM_NUMBER_OF_VALUES = 5; ///< Number of values to use for weighted pan calculation.
46 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.
47 const unsigned long MINIMUM_TIME_BETWEEN_DOWN_AND_UP_FOR_RESET( 150u );
49 // predefined effect values
50 const Vector3 ANGLE_CAROUSEL_ROTATE(Math::PI * 0.5f, Math::PI * 0.5f, 0.0f);
51 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
52 const Vector2 ANGLE_CUSTOM_CUBE_SWING(-Math::PI * 0.45f, -Math::PI * 0.45f); ///< outer cube pages swing 90 degrees as they pan offscreen
53 const Vector2 ANGLE_SPIRAL_SWING_IN(Math::PI * 0.5f, Math::PI * 0.5f);
54 const Vector2 ANGLE_SPIRAL_SWING_OUT(Math::PI * 0.35f, Math::PI * 0.35f);
55 const Vector2 ANGLE_OUTER_CUBE_SWING(Math::PI * 0.5f, Math::PI * 0.5f); ///< outer cube pages swing 90 degrees as they pan offscreen
57 // Helpers ////////////////////////////////////////////////////////////////////////////////////////
59 // TODO: GetAngle for Vector2 can be moved.
60 // GetAngle for Vector3 needs to be measured against a normal/plane.
63 * @param[in] vector The 3D vector to be measured
64 * @return angle in radians from 0 to 2PI
66 float GetAngle(const Vector3& vector)
68 return atan2(vector.y, vector.x) + Math::PI;
72 * @param[in] vector The 2D vector to be measured
73 * @return angle in radians from 0 to 2PI
75 float GetAngle(const Vector2& vector)
77 return atan2(vector.y, vector.x) + Math::PI;
81 * Find the vector (distance) from (a) to (b)
82 * in domain (start) to (end)
83 * (\ / start) (\ / end)
86 * @note assumes both (a) and (b) are already with the domain
89 * @param[in] a the current point
90 * @param[in] b the target point
91 * @param[in] start the start of the domain
92 * @param[in] end the end of the domain
93 * @param[in] bias whether to only take the right direction or the left direction,
94 * or the shortest direction.
95 * @return the shortest direction and distance
97 float VectorInDomain(float a, float b, float start, float end, Dali::Toolkit::DirectionBias bias)
99 if(bias == Dali::Toolkit::DirectionBiasNone)
101 return ShortestDistanceInDomain( a, b, start, end );
104 float size = end-start;
110 if(bias == Dali::Toolkit::DirectionBiasRight) // going right, take the vector.
116 float aRight = a+size;
123 if(bias == Dali::Toolkit::DirectionBiasLeft) // going left, take the vector.
129 float aLeft = a-size;
136 * Returns the position of the anchor within actor
138 * @param actor The Actor
139 * @param anchor The Anchor point of interest.
140 * @return The position of the Anchor
142 Vector3 GetPositionOfAnchor(Actor &actor, const Vector3 &anchor)
144 Vector3 childPosition = actor.GetCurrentPosition();
145 Vector3 childAnchor = - actor.GetCurrentAnchorPoint() + anchor;
146 Vector3 childSize = actor.GetCurrentSize();
148 return childPosition + childAnchor * childSize;
151 // AlphaFunctions /////////////////////////////////////////////////////////////////////////////////
153 float FinalDefaultAlphaFunction(float offset)
155 return offset * 0.5f;
159 * ConstantDecelerationAlphaFunction
160 * Newtoninan distance for constant deceleration
161 * v = 1 - t, s = t - 1/2 t^2
162 * when t = 0, s = 0.0 (min distance)
163 * when t = 1, s = 0.5 (max distance)
164 * progress = s / (max-min) = 2t - t^2
166 * @param[in] offset The input progress
167 * @return The output progress
169 float ConstantDecelerationAlphaFunction(float progress)
171 return progress * 2.0f - progress * progress;
174 // Internal Constraints ///////////////////////////////////////////////////////////////////////////
177 * Internal Relative position Constraint
178 * Generates the relative position value of the scroll view
179 * based on the absolute position, and it's relation to the
180 * scroll domain. This is a value from 0.0f to 1.0f in each
181 * scroll position axis.
183 Vector3 InternalRelativePositionConstraint(const Vector3& current,
184 const PropertyInput& scrollPositionProperty,
185 const PropertyInput& scrollMinProperty,
186 const PropertyInput& scrollMaxProperty,
187 const PropertyInput& scrollSizeProperty)
189 const Vector3& position = -scrollPositionProperty.GetVector3();
190 const Vector3& min = scrollMinProperty.GetVector3();
191 const Vector3& max = scrollMaxProperty.GetVector3();
192 const Vector3& size = scrollSizeProperty.GetVector3();
194 Vector3 relativePosition;
195 Vector3 domainSize = (max - min) - size;
197 relativePosition.x = domainSize.x > Math::MACHINE_EPSILON_1 ? fabsf((position.x - min.x) / domainSize.x) : 0.0f;
198 relativePosition.y = domainSize.y > Math::MACHINE_EPSILON_1 ? fabsf((position.y - min.y) / domainSize.y) : 0.0f;
200 return relativePosition;
203 } // unnamed namespace
218 * Internal Pre-Position Property Constraint.
220 * Generates position property based on current position + gesture displacement.
221 * Or generates position property based on positionX/Y.
222 * Note: This is the position prior to any clamping at scroll boundaries.
223 * TODO: Scale & Rotation Transforms.
225 struct InternalPrePositionConstraint
227 InternalPrePositionConstraint(const Vector2& initialPanMask,
229 float axisAutoLockGradient)
230 : mInitialPanMask(initialPanMask),
231 mAxisAutoLock(axisAutoLock),
232 mLockAxis(ScrollView::LockPossible),
233 mAxisAutoLockGradient(axisAutoLockGradient),
234 mPrePosition(Vector3::ZERO),
239 Vector3 operator()(const Vector3& current,
240 const PropertyInput& gesturePositionProperty,
241 const PropertyInput& gestureDisplacementProperty,
242 const PropertyInput& scrollPositionXProperty,
243 const PropertyInput& scrollPositionYProperty,
244 const PropertyInput& panningProperty)
246 const bool panning = panningProperty.GetBoolean();
247 Vector3 scrollPostPosition;
251 // Check if panning has just started...
254 mLocalStart = gesturePositionProperty.GetVector2() - gestureDisplacementProperty.GetVector2();
255 mPrePosition = current;
256 mLockAxis = ScrollView::LockPossible;
258 mCurrentPanMask = mInitialPanMask;
261 // Calculate Deltas...
262 Vector2 currentPosition = gesturePositionProperty.GetVector2();
263 Vector2 panDelta( currentPosition - mLocalStart );
265 // Axis Auto Lock - locks the panning to the horizontal or vertical axis if the pan
266 // appears mostly horizontal or mostly vertical respectively...
267 AxisAutoLock(panDelta);
269 // Restrict deltas based on ruler enable/disable and axis-lock state...
270 panDelta *= mCurrentPanMask;
272 // Perform Position transform based on input deltas...
273 scrollPostPosition = mPrePosition;
274 scrollPostPosition.GetVectorXY() += panDelta;
278 scrollPostPosition.x = scrollPositionXProperty.GetFloat();
279 scrollPostPosition.y = scrollPositionYProperty.GetFloat();
282 mWasPanning = panning;
283 return scrollPostPosition;
286 void AxisAutoLock(Vector2& panDelta)
290 if(panDelta.LengthSquared() > AUTOLOCK_AXIS_MINIMUM_DISTANCE2 &&
291 mLockAxis == ScrollView::LockPossible)
293 float dx = fabsf(panDelta.x);
294 float dy = fabsf(panDelta.y);
295 if(dx * mAxisAutoLockGradient >= dy)
297 // 0.36:1 gradient to the horizontal (deviate < 20 degrees)
298 mLockAxis = ScrollView::LockVertical;
299 mCurrentPanMask.y = 0.0f;
301 else if(dy * mAxisAutoLockGradient > dx)
303 // 0.36:1 gradient to the vertical (deviate < 20 degrees)
304 mLockAxis = ScrollView::LockHorizontal;
305 mCurrentPanMask.x = 0.0f;
309 mLockAxis = ScrollView::LockNone;
312 } // end if mAxisAutoLock
316 Vector2 mInitialPanMask; ///< Initial pan mask (based on ruler settings)
317 Vector2 mCurrentPanMask; ///< Current pan mask that can be altered by axis lock mode.
319 bool mAxisAutoLock; ///< Set by ScrollView
320 ScrollView::LockAxis mLockAxis;
321 float mAxisAutoLockGradient; ///< Set by ScrollView
322 Vector3 mPrePosition;
327 * Internal Position Property Constraint.
329 * Generates position property based on pre-position
330 * Note: This is the position after clamping.
331 * (uses result of InternalPrePositionConstraint)
333 struct InternalPositionConstraint
335 InternalPositionConstraint(const RulerDomain& domainX, const RulerDomain& domainY)
336 : mDomainMin( -domainX.min, -domainY.min ),
337 mDomainMax( -domainX.max, -domainY.max ),
338 mClampX( domainX.enabled ),
339 mClampY( domainY.enabled )
343 Vector3 operator()(const Vector3& current,
344 const PropertyInput& scrollPositionProperty,
345 const PropertyInput& scrollSizeProperty)
347 Vector3 position = scrollPositionProperty.GetVector3();
348 const Vector2& size = scrollSizeProperty.GetVector3().GetVectorXY();
350 position.x = mClampX ? Clamp(position.x, mDomainMax.x + size.x, mDomainMin.x ) : position.x;
351 position.y = mClampY ? Clamp(position.y, mDomainMax.y + size.y, mDomainMin.y ) : position.y;
364 * This constraint updates the X overshoot property using the difference
365 * mPropertyPrePosition.x and mPropertyPosition.x, returning a relative value between 0.0f and 1.0f
367 struct OvershootXConstraint
369 OvershootXConstraint(float maxOvershoot) : mLastOvershoot(0.0f), mMaxOvershoot(maxOvershoot) {}
371 float operator()(const float& current,
372 const PropertyInput& scrollPrePositionProperty,
373 const PropertyInput& scrollPostPositionProperty)
375 Vector3 scrollPrePosition = scrollPrePositionProperty.GetVector3();
376 Vector3 scrollPostPosition = scrollPostPositionProperty.GetVector3();
377 float newOvershoot = scrollPrePosition.x - scrollPostPosition.x;
378 return (newOvershoot > 0.0f ? std::min(newOvershoot, mMaxOvershoot) : std::max(newOvershoot, -mMaxOvershoot)) / mMaxOvershoot;
381 float mLastOvershoot;
386 * This constraint updates the Y overshoot property using the difference
387 * mPropertyPrePosition.y and mPropertyPosition.y, returning a relative value between 0.0f and 1.0f
389 struct OvershootYConstraint
391 OvershootYConstraint(float maxOvershoot) : mLastOvershoot(0.0f), mMaxOvershoot(maxOvershoot) {}
393 float operator()(const float& current,
394 const PropertyInput& scrollPrePositionProperty,
395 const PropertyInput& scrollPostPositionProperty)
397 Vector3 scrollPrePosition = scrollPrePositionProperty.GetVector3();
398 Vector3 scrollPostPosition = scrollPostPositionProperty.GetVector3();
399 float newOvershoot = scrollPrePosition.y - scrollPostPosition.y;
400 return (newOvershoot > 0.0f ? std::min(newOvershoot, mMaxOvershoot) : std::max(newOvershoot, -mMaxOvershoot)) / mMaxOvershoot;
403 float mLastOvershoot;
408 * When panning, this constraint updates the X property, otherwise
409 * it has no effect on the X property.
411 float InternalXConstraint(const float& current,
412 const PropertyInput& scrollPosition,
413 const PropertyInput& panningProperty)
415 return scrollPosition.GetVector3().x;
419 * When panning, this constraint updates the Y property, otherwise
420 * it has no effect on the Y property.
422 float InternalYConstraint(const float& current,
423 const PropertyInput& scrollPosition,
424 const PropertyInput& panningProperty)
426 return scrollPosition.GetVector3().y;
430 * Internal Position-Delta Property Constraint.
432 * Generates position-delta property based on scroll-position + scroll-offset properties.
434 Vector3 InternalPositionDeltaConstraint(const Vector3& current,
435 const PropertyInput& scrollPositionProperty,
436 const PropertyInput& scrollOffsetProperty)
438 const Vector3& scrollPosition = scrollPositionProperty.GetVector3();
439 const Vector3& scrollOffset = scrollOffsetProperty.GetVector3();
441 return scrollPosition + scrollOffset;
445 * Internal Final Position Constraint
446 * The position of content is:
447 * of scroll-position + f(scroll-overshoot)
448 * where f(...) function defines how overshoot
449 * should affect final-position.
451 struct InternalFinalConstraint
453 InternalFinalConstraint(AlphaFunction functionX,
454 AlphaFunction functionY)
455 : mFunctionX(functionX),
456 mFunctionY(functionY)
460 Vector3 operator()(const Vector3& current,
461 const PropertyInput& scrollPositionProperty,
462 const PropertyInput& scrollOvershootXProperty,
463 const PropertyInput& scrollOvershootYProperty)
465 const float& overshootx = scrollOvershootXProperty.GetFloat();
466 const float& overshooty = scrollOvershootYProperty.GetFloat();
467 Vector3 offset( mFunctionX(overshootx),
468 mFunctionY(overshooty),
471 return scrollPositionProperty.GetVector3() - offset;
474 AlphaFunction mFunctionX;
475 AlphaFunction mFunctionY;
481 return Toolkit::ScrollView::New();
484 TypeRegistration typeRegistration( typeid(Toolkit::ScrollView), typeid(Toolkit::Scrollable), Create );
486 SignalConnectorType signalConnector1( typeRegistration, Toolkit::ScrollView::SIGNAL_SNAP_STARTED, &ScrollView::DoConnectSignal );
491 ///////////////////////////////////////////////////////////////////////////////////////////////////
493 ///////////////////////////////////////////////////////////////////////////////////////////////////
495 Dali::Toolkit::ScrollView ScrollView::New()
497 // Create the implementation
498 ScrollViewPtr scrollView(new ScrollView());
500 // Pass ownership to CustomActor via derived handle
501 Dali::Toolkit::ScrollView handle(*scrollView);
503 // Second-phase init of the implementation
504 // This can only be done after the CustomActor connection has been made...
505 scrollView->Initialize();
510 ScrollView::ScrollView()
514 mScrollInterrupted(false),
517 mGestureStackDepth(0),
518 mRotationDelta(0.0f),
519 mScrollPreRotation(0.0f),
520 mScrollPostRotation(0.0f),
521 mTouchDownReceived(false),
522 mActorAutoSnapEnabled(false),
523 mAutoResizeContainerEnabled(false),
525 mAxisAutoLock(false),
526 mMinTouchesForPanning(1),
527 mMaxTouchesForPanning(1),
528 mLockAxis(LockPossible),
529 mRefreshIntervalMilliseconds(DEFAULT_REFRESH_INTERVAL_MILLISECONDS),
531 mOvershootDelay(1.0f),
532 mMaxOvershoot(Toolkit::ScrollView::DEFAULT_MAX_OVERSHOOT, Toolkit::ScrollView::DEFAULT_MAX_OVERSHOOT),
533 mDefaultMaxOvershoot(true),
534 mSnapOvershootDuration(Toolkit::ScrollView::DEFAULT_SNAP_OVERSHOOT_DURATION),
535 mSnapOvershootAlphaFunction(AlphaFunctions::EaseOut),
536 mSnapDuration(Toolkit::ScrollView::DEFAULT_SLOW_SNAP_ANIMATION_DURATION),
537 mSnapAlphaFunction(AlphaFunctions::EaseOut),
538 mFlickDuration(Toolkit::ScrollView::DEFAULT_FAST_SNAP_ANIMATION_DURATION),
539 mFlickAlphaFunction(AlphaFunctions::EaseOut),
540 mAxisAutoLockGradient(Toolkit::ScrollView::DEFAULT_AXIS_AUTO_LOCK_GRADIENT),
541 mFrictionCoefficient(Toolkit::ScrollView::DEFAULT_FRICTION_COEFFICIENT),
542 mFlickSpeedCoefficient(Toolkit::ScrollView::DEFAULT_FLICK_SPEED_COEFFICIENT),
543 mMaxFlickSpeed(Toolkit::ScrollView::DEFAULT_MAX_FLICK_SPEED),
544 mInAccessibilityPan(false)
546 SetRequiresMouseWheelEvents(true);
549 void ScrollView::OnInitialize()
552 self.SetLeaveRequired(true);
554 // Internal Actor, used to hide actors from enumerations.
555 // Also actors added to Internal actor appear as overlays e.g. ScrollBar components.
556 mInternalActor = Actor::New();
557 mInternalActor.SetDrawMode(DrawMode::OVERLAY);
558 self.Add(mInternalActor);
559 mInternalActor.ApplyConstraint( Constraint::New<Vector3>( Actor::SIZE, ParentSource( Actor::SIZE ), EqualToConstraint() ) );
560 mInternalActor.SetParentOrigin(ParentOrigin::CENTER);
561 mInternalActor.SetAnchorPoint(AnchorPoint::CENTER);
565 // Register Scroll Properties.
566 RegisterProperties();
568 mScrollPostPosition = mScrollPrePosition = Vector3::ZERO;
569 mScrollPostScale = mScrollPreScale = Vector3::ONE;
570 mScrollPostRotation = mScrollPreRotation = 0.0f;
572 mMouseWheelScrollDistanceStep = Stage::GetCurrent().GetSize() * DEFAULT_MOUSE_WHEEL_SCROLL_DISTANCE_STEP_PROPORTION;
576 mGestureStackDepth = 0;
578 EnableGestureDetection( Gesture::Type( Gesture::Pan ) );
580 // For pan, default to only 1 touch required, ignoring touches outside this range.
581 SetTouchesRequiredForPanning(1, 1, false);
583 // By default we'll allow the user to freely drag the scroll view,
584 // while disabling the other rulers.
585 RulerPtr ruler = new DefaultRuler();
586 RulerPtr rulerDisabled = new DefaultRuler();
587 rulerDisabled->Disable();
590 mRulerScaleX = rulerDisabled;
591 mRulerScaleY = rulerDisabled;
592 mRulerRotation = rulerDisabled;
594 EnableScrollComponent(Toolkit::Scrollable::OvershootIndicator);
596 Vector3 size = GetControlSize();
597 UpdatePropertyDomain(size);
598 SetInternalConstraints();
601 void ScrollView::OnControlStageConnection()
605 SetScrollSensitive( false );
606 SetScrollSensitive( true );
608 if(IsScrollComponentEnabled(Toolkit::Scrollable::OvershootIndicator))
610 // try and make sure property notifications are set
611 EnableScrollComponent(Toolkit::Scrollable::OvershootIndicator);
615 void ScrollView::OnControlStageDisconnection()
617 if ( mSnapOvershootAnimation )
619 SetOvershootToOrigin();
625 ScrollView::~ScrollView()
629 AlphaFunction ScrollView::GetScrollSnapAlphaFunction() const
631 return mSnapAlphaFunction;
634 void ScrollView::SetScrollSnapAlphaFunction(AlphaFunction alpha)
636 mSnapAlphaFunction = alpha;
639 AlphaFunction ScrollView::GetScrollFlickAlphaFunction() const
641 return mFlickAlphaFunction;
644 void ScrollView::SetScrollFlickAlphaFunction(AlphaFunction alpha)
646 mFlickAlphaFunction = alpha;
649 float ScrollView::GetScrollSnapDuration() const
651 return mSnapDuration;
654 void ScrollView::SetScrollSnapDuration(float time)
656 mSnapDuration = time;
659 float ScrollView::GetScrollFlickDuration() const
661 return mFlickDuration;
664 void ScrollView::SetScrollFlickDuration(float time)
666 mFlickDuration = time;
669 void ScrollView::ApplyEffect(Toolkit::ScrollViewEffect effect)
671 Dali::Toolkit::ScrollView self = Dali::Toolkit::ScrollView::DownCast(Self());
673 // Assertion check to ensure effect doesn't already exist in this scrollview
674 bool effectAlreadyExistsInScrollView(false);
675 for (ScrollViewEffectIter iter = mEffects.begin(); iter != mEffects.end(); ++iter)
679 effectAlreadyExistsInScrollView = true;
684 DALI_ASSERT_ALWAYS(!effectAlreadyExistsInScrollView);
686 // add effect to effects list
687 mEffects.push_back(effect);
689 // invoke Attachment request to ScrollView first
690 GetImpl(effect).Attach(self);
693 Toolkit::ScrollViewEffect ScrollView::ApplyEffect(Toolkit::ScrollView::PageEffect effect)
695 Toolkit::ScrollViewEffect scrollEffect;
698 case Toolkit::ScrollView::PageEffectNone:
702 case Toolkit::ScrollView::PageEffectOuterCube:
704 Toolkit::ScrollViewCustomEffect customEffect;
705 scrollEffect = customEffect = Toolkit::ScrollViewCustomEffect::New();
706 Vector2 pageSize = Stage::GetCurrent().GetSize();
707 // 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
708 // 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)
709 // the page moving off screen will slowly build a spacing from 0.0f to 20.0f
710 // the spacing from each page is added together for the final spacing between the two pages.
711 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));
712 customEffect.SetSwingAngleOut(ANGLE_CUSTOM_CUBE_SWING.x, Vector3(0.0f, -1.0f, 0.0f));
713 customEffect.SetSwingAnchor(AnchorPoint::CENTER, AnchorPoint::CENTER_LEFT);
714 customEffect.SetOpacityThreshold(0.7f);
717 case Toolkit::ScrollView::PageEffectDepth:
719 Toolkit::ScrollViewCustomEffect customEffect;
720 scrollEffect = customEffect = Toolkit::ScrollViewCustomEffect::New();
723 case Toolkit::ScrollView::PageEffectInnerCube:
725 Toolkit::ScrollViewCustomEffect customEffect;
726 scrollEffect = customEffect = Toolkit::ScrollViewCustomEffect::New();
727 customEffect.SetPageSpacing(Vector2(30.0f, 30.0f));
728 customEffect.SetAngledOriginPageRotation(ANGLE_CUBE_PAGE_ROTATE);
729 customEffect.SetSwingAngle(ANGLE_CUBE_PAGE_ROTATE.x, Vector3(0,-1,0));
730 customEffect.SetOpacityThreshold(0.5f);
733 case Toolkit::ScrollView::PageEffectCarousel:
735 Toolkit::ScrollViewCustomEffect customEffect;
736 scrollEffect = customEffect = Toolkit::ScrollViewCustomEffect::New();
737 customEffect.SetPageTranslation(Vector3(0,0,0), Vector3(-30, 0, 0));
738 customEffect.SetPageSpacing(Vector2(60.0f, 60.0f));
739 customEffect.SetAngledOriginPageRotation(-ANGLE_CUBE_PAGE_ROTATE);
740 customEffect.SetOpacityThreshold(0.2f, 0.6f);
743 case Toolkit::ScrollView::PageEffectSpiral:
745 Toolkit::ScrollViewCustomEffect customEffect;
746 scrollEffect = customEffect = Toolkit::ScrollViewCustomEffect::New();
748 Vector2 pageSize = Stage::GetCurrent().GetSize();
749 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));
750 //customEffect.SetSwingAngleAlphaFunctionOut(AlphaFunctions::EaseOut);
751 customEffect.SetSwingAnchor(AnchorPoint::CENTER_RIGHT);
752 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);
753 //customEffect.SetPageTranslateAlphaFunctionOut(AlphaFunctions::EaseOut);
754 customEffect.SetOpacityThreshold(0.75f, 0.6f);
755 customEffect.SetOpacityAlphaFunctionIn(AlphaFunctions::EaseInOut);
760 DALI_ASSERT_DEBUG(0 && "unknown scroll view effect");
763 RemoveConstraintsFromChildren();
766 ApplyEffect(scrollEffect);
771 void ScrollView::RemoveEffect(Toolkit::ScrollViewEffect effect)
773 Dali::Toolkit::ScrollView self = Dali::Toolkit::ScrollView::DownCast(Self());
775 // remove effect from effects list
776 bool effectExistedInScrollView(false);
777 for (ScrollViewEffectIter iter = mEffects.begin(); iter != mEffects.end(); ++iter)
781 mEffects.erase(iter);
782 effectExistedInScrollView = true;
787 // Assertion check to ensure effect existed.
788 DALI_ASSERT_ALWAYS(effectExistedInScrollView);
790 // invoke Detachment request to ScrollView last
791 GetImpl(effect).Detach(self);
794 void ScrollView::RemoveAllEffects()
796 Dali::Toolkit::ScrollView self = Dali::Toolkit::ScrollView::DownCast(Self());
798 for (ScrollViewEffectIter effectIter = mEffects.begin(); effectIter != mEffects.end(); ++effectIter)
800 Toolkit::ScrollViewEffect effect = *effectIter;
802 // invoke Detachment request to ScrollView last
803 GetImpl(effect).Detach(self);
809 void ScrollView::ApplyConstraintToChildren(Constraint constraint)
811 ApplyConstraintToBoundActors(constraint);
814 void ScrollView::RemoveConstraintsFromChildren()
816 RemoveConstraintsFromBoundActors();
819 const RulerPtr ScrollView::GetRulerX() const
824 const RulerPtr ScrollView::GetRulerY() const
829 void ScrollView::SetRulerX(RulerPtr ruler)
833 Vector3 size = GetControlSize();
834 UpdatePropertyDomain(size);
835 UpdateMainInternalConstraint();
838 void ScrollView::SetRulerY(RulerPtr ruler)
842 Vector3 size = GetControlSize();
843 UpdatePropertyDomain(size);
844 UpdateMainInternalConstraint();
847 void ScrollView::UpdatePropertyDomain(const Vector3& size)
852 bool canScrollVertical = false;
853 bool canScrollHorizontal = false;
855 if(mRulerX->IsEnabled())
857 const Toolkit::RulerDomain& rulerDomain = mRulerX->GetDomain();
858 min.x = rulerDomain.min;
859 max.x = rulerDomain.max;
861 // make sure new scroll value is within new domain
862 float newScroll = min.x;
863 int scrollXPropertyIndex = self.GetPropertyIndex(Toolkit::ScrollView::SCROLL_X_PROPERTY_NAME);
864 if((fabsf(max.x - min.x) - size.x) > Math::MACHINE_EPSILON_1)
866 canScrollHorizontal = true;
867 float currentScroll = self.GetProperty<float>(scrollXPropertyIndex);
868 newScroll = Clamp(currentScroll, -(max.x - size.x), -min.x);
870 self.SetProperty(scrollXPropertyIndex, newScroll);
873 if(mRulerY->IsEnabled())
875 const Toolkit::RulerDomain& rulerDomain = mRulerY->GetDomain();
876 min.y = rulerDomain.min;
877 max.y = rulerDomain.max;
879 // make sure new scroll value is within new domain
880 float newScroll = min.y;
881 int scrollYPropertyIndex = self.GetPropertyIndex(Toolkit::ScrollView::SCROLL_Y_PROPERTY_NAME);
882 if((fabsf(max.y - min.y) - size.y) > Math::MACHINE_EPSILON_1)
884 canScrollVertical = true;
885 float currentScroll = self.GetProperty<float>(scrollYPropertyIndex);
886 newScroll = Clamp(currentScroll, -(max.y - size.y), -min.y);
888 self.SetProperty(scrollYPropertyIndex, newScroll);
890 self.SetProperty(mPropertyCanScrollVertical, canScrollVertical);
891 self.SetProperty(mPropertyCanScrollHorizontal, canScrollHorizontal);
893 self.SetProperty(mPropertyPositionMin, min );
894 self.SetProperty(mPropertyPositionMax, max );
897 void ScrollView::SetRulerScaleX(RulerPtr ruler)
899 mRulerScaleX = ruler;
900 UpdateMainInternalConstraint();
903 void ScrollView::SetRulerScaleY(RulerPtr ruler)
905 mRulerScaleY = ruler;
906 UpdateMainInternalConstraint();
909 void ScrollView::SetRulerRotation(RulerPtr ruler)
911 mRulerRotation = ruler;
912 UpdateMainInternalConstraint();
915 void ScrollView::SetScrollSensitive(bool sensitive)
918 PanGestureDetector panGesture( GetPanGestureDetector() );
920 if((!mSensitive) && (sensitive))
922 mSensitive = sensitive;
923 panGesture.Attach(self);
925 else if((mSensitive) && (!sensitive))
927 // while the scroll view is panning, the state needs to be reset.
928 bool isPanning = self.GetProperty<bool>( mPropertyPanning );
931 PanGesture cancelGesture( Gesture::Cancelled );
932 OnPan( cancelGesture );
935 panGesture.Detach(self);
936 mSensitive = sensitive;
938 mGestureStackDepth = 0;
942 void ScrollView::SetMaxOvershoot(float overshootX, float overshootY)
944 mMaxOvershoot.x = overshootX;
945 mMaxOvershoot.y = overshootY;
946 mDefaultMaxOvershoot = false;
947 UpdateMainInternalConstraint();
950 void ScrollView::SetSnapOvershootAlphaFunction(AlphaFunction alpha)
952 mSnapOvershootAlphaFunction = alpha;
955 void ScrollView::SetSnapOvershootDuration(float duration)
957 mSnapOvershootDuration = duration;
960 void ScrollView::SetTouchesRequiredForPanning(unsigned int minTouches, unsigned int maxTouches, bool endOutside)
962 PanGestureDetector panGesture( GetPanGestureDetector() );
964 mMinTouchesForPanning = minTouches;
965 mMaxTouchesForPanning = maxTouches;
969 panGesture.SetMinimumTouchesRequired(minTouches);
970 panGesture.SetMaximumTouchesRequired(maxTouches);
974 panGesture.SetMinimumTouchesRequired(1);
975 panGesture.SetMaximumTouchesRequired(UINT_MAX);
979 void ScrollView::SetActorAutoSnap(bool enable)
981 mActorAutoSnapEnabled = enable;
984 void ScrollView::SetAutoResize(bool enable)
986 mAutoResizeContainerEnabled = enable;
987 // TODO: This needs a lot of issues to be addressed before working.
990 bool ScrollView::GetWrapMode() const
995 void ScrollView::SetWrapMode(bool enable)
998 Self().SetProperty(mPropertyWrap, enable);
1001 int ScrollView::GetRefreshInterval() const
1003 return mRefreshIntervalMilliseconds;
1006 void ScrollView::SetRefreshInterval(int milliseconds)
1008 mRefreshIntervalMilliseconds = milliseconds;
1011 bool ScrollView::GetAxisAutoLock() const
1013 return mAxisAutoLock;
1016 void ScrollView::SetAxisAutoLock(bool enable)
1018 mAxisAutoLock = enable;
1019 UpdateMainInternalConstraint();
1022 float ScrollView::GetAxisAutoLockGradient() const
1024 return mAxisAutoLockGradient;
1027 void ScrollView::SetAxisAutoLockGradient(float gradient)
1029 DALI_ASSERT_DEBUG( gradient >= 0.0f && gradient <= 1.0f );
1030 mAxisAutoLockGradient = gradient;
1031 UpdateMainInternalConstraint();
1034 float ScrollView::GetFrictionCoefficient() const
1036 return mFrictionCoefficient;
1039 void ScrollView::SetFrictionCoefficient(float friction)
1041 DALI_ASSERT_DEBUG( friction > 0.0f );
1042 mFrictionCoefficient = friction;
1045 float ScrollView::GetFlickSpeedCoefficient() const
1047 return mFlickSpeedCoefficient;
1050 void ScrollView::SetFlickSpeedCoefficient(float speed)
1052 mFlickSpeedCoefficient = speed;
1055 float ScrollView::GetMaxFlickSpeed() const
1057 return mMaxFlickSpeed;
1060 void ScrollView::SetMaxFlickSpeed(float speed)
1062 mMaxFlickSpeed = speed;
1065 void ScrollView::SetMouseWheelScrollDistanceStep(Vector2 step)
1067 mMouseWheelScrollDistanceStep = step;
1070 Vector2 ScrollView::GetMouseWheelScrollDistanceStep() const
1072 return mMouseWheelScrollDistanceStep;
1075 unsigned int ScrollView::GetCurrentPage() const
1077 // in case animation is currently taking place.
1078 Vector3 position = GetPropertyPrePosition();
1080 Actor self = Self();
1081 unsigned int page = 0;
1082 unsigned int pagesPerVolume = 1;
1083 unsigned int volume = 0;
1085 // if rulerX is enabled, then get page count (columns)
1086 page = mRulerX->GetPageFromPosition(-position.x, mWrapMode);
1087 volume = mRulerY->GetPageFromPosition(-position.y, mWrapMode);
1088 pagesPerVolume = mRulerX->GetTotalPages();
1090 return volume * pagesPerVolume + page;
1093 Vector3 ScrollView::GetCurrentScrollPosition() const
1095 // in case animation is currently taking place.
1096 return -GetPropertyPrePosition();
1099 Vector3 ScrollView::GetCurrentScrollScale() const
1101 // in case animation is currently taking place.
1102 return GetPropertyScale();
1105 Vector3 ScrollView::GetDomainSize() const
1107 Vector3 size = Self().GetCurrentSize();
1109 const RulerDomain& xDomain = GetRulerX()->GetDomain();
1110 const RulerDomain& yDomain = GetRulerY()->GetDomain();
1112 Vector3 domainSize = Vector3( xDomain.max - xDomain.min, yDomain.max - yDomain.min, 0.0f ) - size;
1116 void ScrollView::TransformTo(const Vector3& position, const Vector3& scale, float rotation,
1117 DirectionBias horizontalBias, DirectionBias verticalBias)
1119 TransformTo(position, scale, rotation, mSnapDuration, horizontalBias, verticalBias);
1122 void ScrollView::TransformTo(const Vector3& position, const Vector3& scale, float rotation, float duration,
1123 DirectionBias horizontalBias, DirectionBias verticalBias)
1125 // Guard against destruction during signal emission
1126 // Note that Emit() methods are called indirectly e.g. from within ScrollView::AnimateTo()
1127 Toolkit::ScrollView handle( GetOwner() );
1129 Vector3 currentScrollPosition = GetCurrentScrollPosition();
1130 Self().SetProperty( mPropertyScrollStartPagePosition, currentScrollPosition );
1132 if(mScrolling) // are we interrupting a current scroll?
1134 // set mScrolling to false, in case user has code that interrogates mScrolling Getter() in complete.
1136 mScrollCompletedSignalV2.Emit( currentScrollPosition );
1139 Self().SetProperty(mPropertyScrolling, true);
1141 mScrollStartedSignalV2.Emit( currentScrollPosition );
1142 bool animating = AnimateTo(-position,
1143 Vector3::ONE * duration,
1145 Vector3::ONE * duration,
1156 // if not animating, then this pan has completed right now.
1157 Self().SetProperty(mPropertyScrolling, false);
1159 mScrollCompletedSignalV2.Emit( currentScrollPosition );
1163 void ScrollView::ScrollTo(const Vector3& position)
1165 ScrollTo(position, mSnapDuration );
1168 void ScrollView::ScrollTo(const Vector3& position, float duration)
1170 ScrollTo(position, duration, DirectionBiasNone, DirectionBiasNone);
1173 void ScrollView::ScrollTo(const Vector3& position, float duration,
1174 DirectionBias horizontalBias, DirectionBias verticalBias)
1176 TransformTo(position, mScrollPostScale, mScrollPostRotation, duration, horizontalBias, verticalBias);
1179 void ScrollView::ScrollTo(unsigned int page)
1181 ScrollTo(page, mSnapDuration);
1184 void ScrollView::ScrollTo(unsigned int page, float duration, DirectionBias bias)
1187 unsigned int volume;
1188 unsigned int libraries;
1190 // The position to scroll to is continuous and linear
1191 // unless a domain has been enabled on the X axis.
1192 // or if WrapMode has been enabled.
1193 bool carryX = mRulerX->GetDomain().enabled | mWrapMode;
1194 bool carryY = mRulerY->GetDomain().enabled | mWrapMode;
1196 position.x = mRulerX->GetPositionFromPage(page, volume, carryX);
1197 position.y = mRulerY->GetPositionFromPage(volume, libraries, carryY);
1199 ScrollTo(position, duration, bias, bias);
1202 void ScrollView::ScrollTo(Actor &actor)
1204 ScrollTo(actor, mSnapDuration);
1207 void ScrollView::ScrollTo(Actor &actor, float duration)
1209 DALI_ASSERT_ALWAYS(actor.GetParent() == Self());
1211 Actor self = Self();
1212 Vector3 size = self.GetCurrentSize();
1213 Vector3 position = actor.GetCurrentPosition();
1214 position -= GetPropertyPrePosition();
1216 ScrollTo(Vector3(position.x - size.width * 0.5f, position.y - size.height * 0.5f, 0.0f), duration);
1219 Actor ScrollView::FindClosestActor()
1221 Actor self = Self();
1222 Vector3 size = self.GetCurrentSize();
1224 return FindClosestActorToPosition(Vector3(size.width * 0.5f,size.height * 0.5f,0.0f));
1227 Actor ScrollView::FindClosestActorToPosition(const Vector3& position, FindDirection dirX, FindDirection dirY, FindDirection dirZ)
1230 float closestDistance2 = 0.0f;
1231 Vector3 actualPosition = position;
1233 unsigned int numChildren = Self().GetChildCount();
1235 for(unsigned int i = 0; i < numChildren; ++i)
1237 Actor child = Self().GetChildAt(i);
1239 if(mInternalActor == child) // ignore internal actor.
1244 Vector3 childPosition = GetPositionOfAnchor(child, AnchorPoint::CENTER);
1246 Vector3 delta = childPosition - actualPosition;
1248 // X-axis checking (only find Actors to the [dirX] of actualPosition)
1249 if(dirX > All) // != All,None
1251 FindDirection deltaH = delta.x > 0 ? Right : Left;
1258 // Y-axis checking (only find Actors to the [dirY] of actualPosition)
1259 if(dirY > All) // != All,None
1261 FindDirection deltaV = delta.y > 0 ? Down : Up;
1268 // Z-axis checking (only find Actors to the [dirZ] of actualPosition)
1269 if(dirZ > All) // != All,None
1271 FindDirection deltaV = delta.y > 0 ? In : Out;
1278 // compare child to closest child in terms of distance.
1279 float distance2 = 0.0f;
1281 // distance2 = the Square of the relevant dimensions of delta
1284 distance2 += delta.x * delta.x;
1289 distance2 += delta.y * delta.y;
1294 distance2 += delta.z * delta.z;
1297 if(closestChild) // Next time.
1299 if(distance2 < closestDistance2)
1301 closestChild = child;
1302 closestDistance2 = distance2;
1307 closestChild = child;
1308 closestDistance2 = distance2;
1312 return closestChild;
1315 bool ScrollView::ScrollToSnapPoint()
1317 Vector2 stationaryVelocity = Vector2(0.0f, 0.0f);
1318 return SnapWithVelocity( stationaryVelocity );
1321 void ScrollView::ScaleTo(const Vector3& scale)
1323 ScaleTo(scale, mSnapDuration);
1326 void ScrollView::ScaleTo(const Vector3& scale, float duration)
1328 TransformTo(mScrollPostPosition, scale, mScrollPostRotation, duration);
1332 // TODO: In situations where axes are different (X snap, Y free)
1333 // Each axis should really have their own independent animation (time and equation)
1334 // Consider, X axis snapping to nearest grid point (EaseOut over fixed time)
1335 // Consider, Y axis simulating physics to arrive at a point (Physics equation over variable time)
1336 // Currently, the axes have been split however, they both use the same EaseOut equation.
1337 bool ScrollView::SnapWithVelocity(Vector2 velocity)
1339 // Animator takes over now, touches are assumed not to interfere.
1340 // And if touches do interfere, then we'll stop animation, update PrePosition
1341 // to current mScroll's properties, and then resume.
1342 // Note: For Flicking this may work a bit different...
1344 float angle = atan2(velocity.y, velocity.x);
1345 float speed2 = velocity.LengthSquared();
1346 AlphaFunction alphaFunction = mSnapAlphaFunction;
1347 Vector3 positionDuration = Vector3::ONE * mSnapDuration;
1348 Vector3 scaleDuration = Vector3::ONE * mSnapDuration;
1349 float rotationDuration = mSnapDuration;
1352 FindDirection horizontal = None;
1353 FindDirection vertical = None;
1355 // orthoAngleRange = Angle tolerance within the Exact N,E,S,W direction
1356 // that will be accepted as a general N,E,S,W flick direction.
1358 const float orthoAngleRange = FLICK_ORTHO_ANGLE_RANGE * M_PI / 180.0f;
1359 const float flickSpeedThreshold2 = FLICK_SPEED_THRESHOLD*FLICK_SPEED_THRESHOLD;
1361 Vector3 positionSnap = mScrollPostPosition;
1363 // Flick logic X Axis
1365 if(mRulerX->IsEnabled())
1369 if( speed2 > flickSpeedThreshold2 || // exceeds flick threshold
1370 mInAccessibilityPan ) // With AccessibilityPan its easier to move between snap positions
1372 if((angle >= -orthoAngleRange) && (angle < orthoAngleRange)) // Swiping East
1374 biasX = 0.0f, horizontal = Left;
1376 // This guards against an error where no movement occurs, due to the flick finishing
1377 // before the update-thread has advanced mScrollPostPosition past the the previous snap point.
1378 positionSnap.x += 1.0f;
1380 else if((angle >= M_PI-orthoAngleRange) || (angle < -M_PI+orthoAngleRange)) // Swiping West
1382 biasX = 1.0f, horizontal = Right;
1384 // This guards against an error where no movement occurs, due to the flick finishing
1385 // before the update-thread has advanced mScrollPostPosition past the the previous snap point.
1386 positionSnap.x -= 1.0f;
1391 // Flick logic Y Axis
1393 if(mRulerY->IsEnabled())
1397 if( speed2 > flickSpeedThreshold2 || // exceeds flick threshold
1398 mInAccessibilityPan ) // With AccessibilityPan its easier to move between snap positions
1400 if((angle >= M_PI_2-orthoAngleRange) && (angle < M_PI_2+orthoAngleRange)) // Swiping South
1402 biasY = 0.0f, vertical = Up;
1404 else if((angle >= -M_PI_2-orthoAngleRange) && (angle < -M_PI_2+orthoAngleRange)) // Swiping North
1406 biasY = 1.0f, vertical = Down;
1411 // isFlick: Whether this gesture is a flick or not.
1412 bool isFlick = (horizontal != All || vertical != All);
1413 // isFreeFlick: Whether this gesture is a flick under free panning criteria.
1414 bool isFreeFlick = velocity.LengthSquared() > (FREE_FLICK_SPEED_THRESHOLD*FREE_FLICK_SPEED_THRESHOLD);
1416 if(isFlick || isFreeFlick)
1418 positionDuration = Vector3::ONE * mFlickDuration;
1419 alphaFunction = mFlickAlphaFunction;
1422 // Calculate next positionSnap ////////////////////////////////////////////////////////////
1424 if(mActorAutoSnapEnabled)
1426 Vector3 size = Self().GetCurrentSize();
1428 Actor child = FindClosestActorToPosition( Vector3(size.width * 0.5f,size.height * 0.5f,0.0f), horizontal, vertical );
1430 if(!child && isFlick )
1432 // If we conducted a direction limited search and found no actor, then just snap to the closest actor.
1433 child = FindClosestActorToPosition( Vector3(size.width * 0.5f,size.height * 0.5f,0.0f) );
1438 Vector3 position = Self().GetProperty<Vector3>(mPropertyPosition);
1440 // Get center-point of the Actor.
1441 Vector3 childPosition = GetPositionOfAnchor(child, AnchorPoint::CENTER);
1443 if(mRulerX->IsEnabled())
1445 positionSnap.x = position.x - childPosition.x + size.width * 0.5f;
1447 if(mRulerY->IsEnabled())
1449 positionSnap.y = position.y - childPosition.y + size.height * 0.5f;
1454 Vector3 startPosition = positionSnap;
1455 positionSnap.x = -mRulerX->Snap(-positionSnap.x, biasX); // NOTE: X & Y rulers think in -ve coordinate system.
1456 positionSnap.y = -mRulerY->Snap(-positionSnap.y, biasY); // That is scrolling RIGHT (e.g. 100.0, 0.0) means moving LEFT.
1458 Vector3 clampDelta(Vector3::ZERO);
1459 ClampPosition(positionSnap);
1461 if( (mRulerX->GetType() == Ruler::Free || mRulerY->GetType() == Ruler::Free)
1462 && isFreeFlick && !mActorAutoSnapEnabled)
1464 // Calculate target position based on velocity of flick.
1466 // a = Deceleration (Set to diagonal stage length * friction coefficient)
1467 // u = Initial Velocity (Flick velocity)
1468 // v = 0 (Final Velocity)
1469 // t = Time (Velocity / Deceleration)
1470 Vector2 stageSize = Stage::GetCurrent().GetSize();
1471 float stageLength = Vector3(stageSize.x, stageSize.y, 0.0f).Length();
1472 float a = (stageLength * mFrictionCoefficient);
1473 Vector3 u = Vector3(velocity.x, velocity.y, 0.0f) * mFlickSpeedCoefficient;
1474 float speed = u.Length();
1477 // TODO: Change this to a decay function. (faster you flick, the slower it should be)
1478 speed = std::min(speed, stageLength * mMaxFlickSpeed );
1480 alphaFunction = ConstantDecelerationAlphaFunction;
1482 float t = speed / a;
1484 if(mRulerX->IsEnabled() && mRulerX->GetType() == Ruler::Free)
1486 positionSnap.x += t*u.x*0.5f;
1489 if(mRulerY->IsEnabled() && mRulerY->GetType() == Ruler::Free)
1491 positionSnap.y += t*u.y*0.5f;
1494 clampDelta = positionSnap;
1495 ClampPosition(positionSnap);
1496 if((positionSnap - startPosition).LengthSquared() > Math::MACHINE_EPSILON_0)
1498 clampDelta -= positionSnap;
1499 clampDelta.x = clampDelta.x > 0.0f ? std::min(clampDelta.x, mMaxOvershoot.x) : std::max(clampDelta.x, -mMaxOvershoot.x);
1500 clampDelta.y = clampDelta.y > 0.0f ? std::min(clampDelta.y, mMaxOvershoot.y) : std::max(clampDelta.y, -mMaxOvershoot.y);
1504 clampDelta = Vector3::ZERO;
1507 // If Axis is Free and has velocity, then calculate time taken
1508 // to reach target based on velocity in axis.
1509 if(mRulerX->IsEnabled() && mRulerX->GetType() == Ruler::Free)
1511 float deltaX = fabsf(startPosition.x - positionSnap.x);
1513 if(fabsf(u.x) > Math::MACHINE_EPSILON_1)
1515 positionDuration.x = fabsf(deltaX / u.x);
1519 positionDuration.x = 0;
1523 if(mRulerY->IsEnabled() && mRulerY->GetType() == Ruler::Free)
1525 float deltaY = fabsf(startPosition.y - positionSnap.y);
1527 if(fabsf(u.y) > Math::MACHINE_EPSILON_1)
1529 positionDuration.y = fabsf(deltaY / u.y);
1533 positionDuration.y = 0;
1537 positionSnap += clampDelta;
1539 // Scale Snap ///////////////////////////////////////////////////////////////
1540 Vector3 scaleSnap = mScrollPostScale;
1542 scaleSnap.x = mRulerScaleX->Snap(scaleSnap.x);
1543 scaleSnap.y = mRulerScaleY->Snap(scaleSnap.y);
1545 ClampScale(scaleSnap);
1547 // Rotation Snap ////////////////////////////////////////////////////////////
1548 float rotationSnap = mScrollPostRotation;
1549 // TODO: implement rotation snap
1551 bool animating = AnimateTo(positionSnap, positionDuration,
1552 scaleSnap, scaleDuration,
1553 rotationSnap, rotationDuration,
1554 alphaFunction, false,
1555 DirectionBiasNone, DirectionBiasNone,
1556 isFlick || isFreeFlick ? Flick : Snap);
1560 AnimateOvershootToOrigin(positionDuration.x, positionDuration.y);
1566 void ScrollView::StopAnimation(void)
1568 // Clear Snap animation if exists.
1571 mSnapAnimation.Stop();
1572 mSnapAnimation.FinishedSignal().Disconnect(this, &ScrollView::OnSnapAnimationFinished);
1573 mSnapAnimation.Clear();
1574 mSnapAnimation = NULL;
1578 mSnapXAnimation.Stop();
1579 mSnapXAnimation.FinishedSignal().Disconnect(this, &ScrollView::OnSnapXAnimationFinished);
1580 mSnapXAnimation.Clear();
1581 mSnapXAnimation = NULL;
1585 mSnapYAnimation.Stop();
1586 mSnapYAnimation.FinishedSignal().Disconnect(this, &ScrollView::OnSnapYAnimationFinished);
1587 mSnapYAnimation.Clear();
1588 mSnapYAnimation = NULL;
1590 if(mSnapOvershootAnimation)
1592 mSnapOvershootAnimation.FinishedSignal().Disconnect(this, &ScrollView::OnSnapOvershootAnimationFinished);
1593 mSnapOvershootAnimation.Stop();
1594 mSnapOvershootAnimation.Clear();
1595 mSnapOvershootAnimation = NULL;
1597 HandleStoppedAnimation();
1600 bool ScrollView::AnimateTo(const Vector3& position, const Vector3& positionDuration,
1601 const Vector3& scale, const Vector3& scaleDuration,
1602 float rotation, float rotationDuration,
1603 AlphaFunction alpha, bool findShortcuts,
1604 DirectionBias horizontalBias, DirectionBias verticalBias,
1607 // Here we perform an animation on a number of properties (depending on which have changed)
1608 // The animation is applied to all ScrollBases
1609 Actor self = Self();
1610 bool startAnimation = false;
1611 Vector3 positionTransformed = position;
1612 float totalDuration = 0.0f;
1614 bool positionChanged = (positionTransformed != mScrollPostPosition);
1615 bool scaleChanged = (scale != mScrollPostScale);
1616 bool rotationChanged = fabsf(rotation - mScrollPostRotation) > Math::MACHINE_EPSILON_0;
1620 totalDuration = std::max(totalDuration, positionDuration.x);
1621 totalDuration = std::max(totalDuration, positionDuration.y);
1626 totalDuration = std::max(totalDuration, scaleDuration.x);
1627 totalDuration = std::max(totalDuration, scaleDuration.y);
1632 totalDuration = std::max(totalDuration, rotationDuration);
1635 if(totalDuration > Math::MACHINE_EPSILON_1)
1638 mSnapAnimation = Animation::New(totalDuration);
1639 mSnapAnimation.FinishedSignal().Connect(this, &ScrollView::OnSnapAnimationFinished);
1640 mSnapXAnimation = Animation::New(positionDuration.x);
1641 mSnapXAnimation.FinishedSignal().Connect(this, &ScrollView::OnSnapXAnimationFinished);
1642 mSnapYAnimation = Animation::New(positionDuration.y);
1643 mSnapYAnimation.FinishedSignal().Connect(this, &ScrollView::OnSnapYAnimationFinished);
1644 startAnimation = true;
1646 // Position Delta ///////////////////////////////////////////////////////
1649 if(mWrapMode && findShortcuts)
1651 // In Wrap Mode, the shortest distance is a little less intuitive...
1652 const RulerDomain rulerDomainX = mRulerX->GetDomain();
1653 const RulerDomain rulerDomainY = mRulerY->GetDomain();
1655 if(mRulerX->IsEnabled())
1657 float dir = VectorInDomain(-mScrollPostPosition.x, -positionTransformed.x, rulerDomainX.min, rulerDomainX.max, horizontalBias);
1658 positionTransformed.x = mScrollPostPosition.x + -dir;
1661 if(mRulerY->IsEnabled())
1663 float dir = VectorInDomain(-mScrollPostPosition.y, -positionTransformed.y, rulerDomainY.min, rulerDomainY.max, verticalBias);
1664 positionTransformed.y = mScrollPostPosition.y + -dir;
1668 // note we have two separate animations for X & Y, this deals with sliding diagonally and hitting
1669 // a horizonal/vertical wall.delay
1670 mSnapXAnimation.AnimateTo( Property(self, mPropertyX), positionTransformed.x, alpha, TimePeriod(0.0f, positionDuration.x));
1671 mSnapYAnimation.AnimateTo( Property(self, mPropertyY), positionTransformed.y, alpha, TimePeriod(0.0f, positionDuration.y));
1674 // Scale Delta ///////////////////////////////////////////////////////
1677 // TODO: for non-uniform scaling to different bounds e.g. scaling a square to a 4:3 aspect ratio screen with a velocity
1678 // the height will hit first, and then the width, so that would require two different animation times just like position.
1679 mSnapAnimation.AnimateTo( Property(self, mPropertyScale), scale, alpha, TimePeriod(0.0f, scaleDuration.x));
1682 mSnapAnimation.AnimateTo( Property(self, mPropertyTime), totalDuration, AlphaFunctions::Linear );
1684 mSnapAnimation.Play();
1685 mSnapXAnimation.Play();
1686 mSnapYAnimation.Play();
1687 StartRefreshTimer();
1688 } // end if(totalDuration > Math::MACHINE_EPSILON_1)
1689 else // totalDuration == 0
1691 // instantly set transform.
1694 self.SetProperty(mPropertyX, positionTransformed.x);
1695 self.SetProperty(mPropertyY, positionTransformed.y);
1697 mScrollPrePosition = mScrollPostPosition = positionTransformed;
1702 self.SetProperty(mPropertyScale, scale);
1704 mScrollPreScale = mScrollPostScale = scale;
1708 // Always send a snap event when AnimateTo is called.
1709 Toolkit::ScrollView::SnapEvent snapEvent;
1710 snapEvent.type = snapType;
1711 snapEvent.position = positionTransformed;
1712 snapEvent.scale = scale;
1713 snapEvent.rotation = rotation;
1714 snapEvent.duration = totalDuration;
1716 mSnapStartedSignalV2.Emit( snapEvent );
1718 return startAnimation;
1721 void ScrollView::SetOvershootEnabled(bool enabled)
1723 if(enabled && !mOvershootIndicator)
1725 mOvershootIndicator = ScrollOvershootIndicator::New(*this);
1727 mOvershootIndicator->Enable(enabled);
1730 void ScrollView::AddOverlay(Actor actor)
1732 mInternalActor.Add( actor );
1735 void ScrollView::RemoveOverlay(Actor actor)
1737 mInternalActor.Remove( actor );
1740 void ScrollView::SetScrollingDirection( Radian direction, Radian threshold )
1742 PanGestureDetector panGesture( GetPanGestureDetector() );
1744 // First remove just in case we have some set, then add.
1745 panGesture.RemoveDirection( direction );
1746 panGesture.AddDirection( direction, threshold );
1749 void ScrollView::RemoveScrollingDirection( Radian direction )
1751 PanGestureDetector panGesture( GetPanGestureDetector() );
1752 panGesture.RemoveDirection( direction );
1755 Toolkit::ScrollView::SnapStartedSignalV2& ScrollView::SnapStartedSignal()
1757 return mSnapStartedSignalV2;
1760 void ScrollView::FindAndUnbindActor(Actor child)
1765 Vector3 ScrollView::GetPropertyPrePosition() const
1767 Vector3 position(Self().GetProperty<float>(mPropertyX), Self().GetProperty<float>(mPropertyY), 0.0f);
1768 WrapPosition(position);
1773 Vector3 ScrollView::GetPropertyPosition() const
1775 Vector3 position = Self().GetProperty<Vector3>(mPropertyPosition);
1776 WrapPosition(position);
1781 Vector3 ScrollView::GetPropertyScale() const
1783 return Self().GetProperty<Vector3>(mPropertyScale);
1786 void ScrollView::HandleStoppedAnimation()
1788 // Animation has stopped, so stop sending the scroll-update signal.
1789 CancelRefreshTimer();
1791 // cement transform now, and allow interactivity to resume.
1792 mScrollPostPosition = GetPropertyPosition();
1794 mScrollPostScale = GetPropertyScale();
1796 // Update Actor position with this wrapped value.
1798 Self().SetProperty(mPropertyX, mScrollPostPosition.x);
1799 Self().SetProperty(mPropertyY, mScrollPostPosition.y);
1802 mScrollPrePosition = mScrollPostPosition;
1803 mScrollPreScale = mScrollPostScale;
1804 mScrollPreRotation = mScrollPostRotation;
1807 void ScrollView::HandleSnapAnimationFinished()
1809 // Emit Signal that scrolling has completed.
1811 Self().SetProperty(mPropertyScrolling, false);
1813 Vector3 deltaPosition(Self().GetProperty<float>(mPropertyX),
1814 Self().GetProperty<float>(mPropertyY),
1817 Vector3 currentScrollPosition = GetCurrentScrollPosition();
1818 mScrollCompletedSignalV2.Emit( currentScrollPosition );
1820 mDomainOffset += deltaPosition - mScrollPostPosition;
1821 Self().SetProperty(mPropertyDomainOffset, mDomainOffset);
1822 HandleStoppedAnimation();
1825 bool ScrollView::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
1827 Dali::BaseHandle handle( object );
1829 bool connected( true );
1830 Toolkit::ScrollView view = Toolkit::ScrollView::DownCast( handle );
1832 if( Toolkit::ScrollView::SIGNAL_SNAP_STARTED == signalName )
1834 view.SnapStartedSignal().Connect( tracker, functor );
1838 // signalName does not match any signal
1845 void ScrollView::OnSizeAnimation(Animation& animation, const Vector3& targetSize)
1847 // need to update domain properties for new size
1848 UpdatePropertyDomain(targetSize);
1851 void ScrollView::OnControlSizeSet( const Vector3& size )
1853 // need to update domain properties for new size
1854 if( mDefaultMaxOvershoot )
1856 mMaxOvershoot.x = size.x * 0.5f;
1857 mMaxOvershoot.y = size.y * 0.5f;
1859 UpdatePropertyDomain(size);
1860 UpdateMainInternalConstraint();
1861 if( IsScrollComponentEnabled(Toolkit::Scrollable::OvershootIndicator) )
1863 mOvershootIndicator->Reset();
1867 void ScrollView::OnChildAdd(Actor& child)
1875 void ScrollView::OnChildRemove(Actor& child)
1877 // TODO: Actor needs a RemoveConstraint method to take out an individual constraint.
1881 bool ScrollView::OnTouchEvent(const TouchEvent& event)
1885 // Ignore this touch event, if scrollview is insensitive.
1889 // Ignore events with multiple-touch points
1890 if (event.GetPointCount() != 1)
1895 if (event.GetPoint(0).state == TouchPoint::Down)
1897 mTouchDownTime = event.time;
1898 mTouchDownReceived = true;
1899 mTouchDownPosition = event.GetPoint(0).local;
1901 if( mSnapAnimation || mSnapXAnimation || mSnapYAnimation || mSnapOvershootAnimation )
1903 mScrollInterrupted = true;
1907 if(mScrolling) // are we interrupting a current scroll?
1909 // reset domain offset as scrolling from original plane.
1910 mDomainOffset = Vector3::ZERO;
1911 Self().SetProperty(mPropertyDomainOffset, Vector3::ZERO);
1914 Vector3 currentScrollPosition = GetCurrentScrollPosition();
1915 mScrollCompletedSignalV2.Emit( currentScrollPosition );
1918 else if(event.GetPoint(0).state == TouchPoint::Up)
1920 // if the user touches and releases without enough movement to go
1921 // into a gesture state, then we should snap to nearest point.
1922 // otherwise our scroll could be stopped (interrupted) half way through an animation.
1923 if(mGestureStackDepth==0 && mTouchDownReceived)
1925 unsigned timeDelta( event.time - mTouchDownTime );
1926 if ( timeDelta >= MINIMUM_TIME_BETWEEN_DOWN_AND_UP_FOR_RESET )
1928 // Reset the velocity only if down was received a while ago
1929 mLastVelocity = Vector2( 0.0f, 0.0f );
1933 Vector2 positionDelta( mTouchDownPosition - event.GetPoint(0).local );
1934 mLastVelocity = positionDelta / timeDelta;
1937 // Only finish the transform if scrolling was interrupted on down or if we are scrolling
1938 if ( mSnapAnimation || mSnapXAnimation || mSnapYAnimation || mSnapOvershootAnimation || mScrollInterrupted || mScrolling )
1943 mTouchDownReceived = false;
1944 mScrollInterrupted = false;
1947 return true; // consume since we're potentially scrolling
1950 bool ScrollView::OnMouseWheelEvent(const MouseWheelEvent& event)
1954 // Ignore this mouse wheel event, if scrollview is insensitive.
1958 Vector3 targetScrollPosition = GetPropertyPosition();
1960 if(mRulerX->IsEnabled() && !mRulerY->IsEnabled())
1962 // If only the ruler in the X axis is enabled, scroll in the X axis.
1963 if(mRulerX->GetType() == Ruler::Free)
1965 // Free panning mode
1966 targetScrollPosition.x -= event.z * mMouseWheelScrollDistanceStep.x;
1967 ClampPosition(targetScrollPosition);
1968 ScrollTo(-targetScrollPosition);
1970 else if(!mScrolling)
1972 // Snap mode, only respond to the event when the previous snap animation is finished.
1973 ScrollTo(GetCurrentPage() + event.z);
1978 // If the ruler in the Y axis is enabled, scroll in the Y axis.
1979 if(mRulerY->GetType() == Ruler::Free)
1981 // Free panning mode
1982 targetScrollPosition.y -= event.z * mMouseWheelScrollDistanceStep.y;
1983 ClampPosition(targetScrollPosition);
1984 ScrollTo(-targetScrollPosition);
1986 else if(!mScrolling)
1988 // Snap mode, only respond to the event when the previous snap animation is finished.
1989 ScrollTo(GetCurrentPage() + event.z * mRulerX->GetTotalPages());
1996 void ScrollView::OnSnapAnimationFinished( Animation& source )
1998 mSnapAnimation.FinishedSignal().Disconnect( this, &ScrollView::OnSnapAnimationFinished );
1999 mSnapAnimation = NULL;
2002 void ScrollView::OnSnapXAnimationFinished( Animation& source )
2004 // Guard against destruction during signal emission
2005 // Note that ScrollCompletedSignal is emitted from HandleSnapAnimationFinished()
2006 Toolkit::ScrollView handle( GetOwner() );
2008 if(!mSnapYAnimation)
2010 HandleSnapAnimationFinished();
2012 if(mScrollMainInternalOvershootXConstraint)
2014 Self().RemoveConstraint(mScrollMainInternalOvershootXConstraint);
2015 mScrollMainInternalOvershootXConstraint.Reset();
2016 mScrollMainInternalOvershootXConstraint = 0;
2018 mSnapXAnimation.FinishedSignal().Disconnect(this, &ScrollView::OnSnapXAnimationFinished);
2019 mSnapXAnimation.Reset();
2020 mSnapXAnimation = NULL;
2021 if( IsScrollComponentEnabled(Toolkit::Scrollable::OvershootIndicator) )
2023 // kick start animation to 0
2024 Self().SetProperty(mPropertyOvershootX, 0.0f);
2028 void ScrollView::OnSnapYAnimationFinished( Animation& source )
2030 // Guard against destruction during signal emission
2031 // Note that ScrollCompletedSignal is emitted from HandleSnapAnimationFinished()
2032 Toolkit::ScrollView handle( GetOwner() );
2034 if(!mSnapXAnimation)
2036 HandleSnapAnimationFinished();
2038 if(mScrollMainInternalOvershootYConstraint)
2040 Self().RemoveConstraint(mScrollMainInternalOvershootYConstraint);
2041 mScrollMainInternalOvershootYConstraint.Reset();
2042 mScrollMainInternalOvershootYConstraint = 0;
2044 mSnapYAnimation.FinishedSignal().Disconnect(this, &ScrollView::OnSnapYAnimationFinished);
2045 mSnapYAnimation.Reset();
2046 mSnapYAnimation = NULL;
2047 if( IsScrollComponentEnabled(Toolkit::Scrollable::OvershootIndicator) )
2049 // kick start animation to 0
2050 Self().SetProperty(mPropertyOvershootY, 0.0f);
2054 void ScrollView::GestureStarted()
2056 // we handle the first gesture.
2057 // if we're currently doing a gesture and receive another
2058 // we continue and combine the effects of the gesture instead of reseting.
2059 if(mGestureStackDepth++==0)
2062 mPanDelta = Vector3::ZERO;
2063 mScaleDelta = Vector3::ONE;
2064 mRotationDelta = 0.0f;
2065 mLastVelocity = Vector2(0.0f, 0.0f);
2066 mLockAxis = LockPossible;
2068 if(mScrolling) // are we interrupting a current scroll?
2070 // set mScrolling to false, in case user has code that interrogates mScrolling Getter() in complete.
2072 Vector3 currentScrollPosition = GetCurrentScrollPosition();
2073 mScrollCompletedSignalV2.Emit( currentScrollPosition );
2078 void ScrollView::GestureContinuing(Vector2 panDelta, Vector2 scaleDelta, float rotationDelta)
2080 mPanDelta.x+= panDelta.x;
2081 mPanDelta.y+= panDelta.y;
2082 mScaleDelta.x*= scaleDelta.x;
2083 mScaleDelta.y*= scaleDelta.y;
2084 mRotationDelta+= rotationDelta;
2086 // Save the velocity, there is a bug in PanGesture
2087 // Whereby the Gesture::Finished's velocity is either:
2088 // NaN (due to time delta of zero between the last two events)
2089 // or 0 (due to position being the same between the last two events)
2091 // Axis Auto Lock - locks the panning to the horizontal or vertical axis if the pan
2092 // appears mostly horizontal or mostly vertical respectively.
2095 if(mPanDelta.LengthSquared() > AUTOLOCK_AXIS_MINIMUM_DISTANCE2 &&
2096 mLockAxis == LockPossible)
2098 float dx = fabsf(mPanDelta.x);
2099 float dy = fabsf(mPanDelta.y);
2100 if(dx * mAxisAutoLockGradient >= dy)
2102 // 0.36:1 gradient to the horizontal (deviate < 20 degrees)
2103 mLockAxis = LockVertical;
2105 else if(dy * mAxisAutoLockGradient > dx)
2107 // 0.36:1 gradient to the vertical (deviate < 20 degrees)
2108 mLockAxis = LockHorizontal;
2112 mLockAxis = LockNone;
2115 } // end if mAxisAutoLock
2118 // TODO: Upgrade to use a more powerful gesture detector (one that supports multiple touches on pan - so works as pan and flick gesture)
2119 // TODO: Reimplement Scaling (pinching 2+ points)
2120 // TODO: Reimplment Rotation (pinching 2+ points)
2121 // BUG: Gesture::Finished doesn't always return velocity on release (due to
2122 // timeDelta between last two events being 0 sometimes, or posiiton being the same)
2123 void ScrollView::OnPan(PanGesture gesture)
2125 // Guard against destruction during signal emission
2126 // Note that Emit() methods are called indirectly e.g. from within ScrollView::OnGestureEx()
2127 Actor self( Self() );
2131 // If another callback on the same original signal disables sensitivity,
2132 // this callback will still be called, so we must suppress it.
2136 // translate Gesture input to get useful data...
2137 switch(gesture.state)
2139 case Gesture::Started:
2142 self.SetProperty( mPropertyPanning, true );
2143 self.SetProperty( mPropertyScrollStartPagePosition, GetCurrentScrollPosition() );
2145 // Update property: X & Y = Position (only when in panning mode - in snapping mode, X & Y are animated).
2146 if( ! mScrollMainInternalXConstraint )
2148 Constraint constraint = Constraint::New<float>( mPropertyX,
2149 LocalSource( mPropertyPosition ),
2150 Source( self, mPropertyPanning ),
2151 InternalXConstraint );
2152 mScrollMainInternalXConstraint = self.ApplyConstraint( constraint );
2154 if( ! mScrollMainInternalYConstraint )
2156 Constraint constraint = Constraint::New<float>( mPropertyY,
2157 LocalSource( mPropertyPosition ),
2158 Source( self, mPropertyPanning ),
2159 InternalYConstraint );
2160 mScrollMainInternalYConstraint = self.ApplyConstraint( constraint );
2163 // When panning we want to make sure overshoot values are affected by pre position and post position
2164 SetOvershootConstraintsEnabled(true);
2168 case Gesture::Continuing:
2170 // Nothing to do, handled in constraint.
2174 case Gesture::Finished:
2175 case Gesture::Cancelled:
2177 mLastVelocity = gesture.velocity;
2178 self.SetProperty( mPropertyPanning, false );
2180 // Remove X & Y position constraints as they are not required when we are not panning.
2181 self.RemoveConstraint(mScrollMainInternalXConstraint);
2182 self.RemoveConstraint(mScrollMainInternalYConstraint);
2183 mScrollMainInternalXConstraint.Reset();
2184 mScrollMainInternalYConstraint.Reset();
2188 case Gesture::Possible:
2189 case Gesture::Clear:
2191 // Nothing to do, not needed.
2195 } // end switch(gesture.state)
2197 OnGestureEx(gesture.state);
2200 void ScrollView::OnGestureEx(Gesture::State state)
2202 // call necessary signals for application developer
2204 if(state == Gesture::Started)
2206 Vector3 currentScrollPosition = GetCurrentScrollPosition();
2207 Self().SetProperty(mPropertyScrolling, true);
2209 mScrollStartedSignalV2.Emit( currentScrollPosition );
2211 else if( (state == Gesture::Finished) ||
2212 (state == Gesture::Cancelled) ) // Finished/default
2214 // when all the gestures have finished, we finish the transform.
2215 // so if a user decides to pan (1 gesture), and then pan+zoom (2 gestures)
2216 // then stop panning (back to 1 gesture), and then stop zooming (0 gestures).
2217 // this is the point we end, and perform necessary snapping.
2218 mGestureStackDepth--;
2219 if(mGestureStackDepth==0)
2226 void ScrollView::UpdateTransform()
2228 // TODO: notify clamps using property notifications (or see if we need this, can deprecate it)
2231 void ScrollView::FinishTransform()
2233 const Vector3& scrollPosition = Self().GetProperty<Vector3>(mPropertyPosition);
2235 mScrollPostPosition.x = scrollPosition.x;
2236 mScrollPostPosition.y = scrollPosition.y;
2238 Vector3 deltaPosition(mScrollPostPosition);
2239 // Cement PRE transform (PRE = POST), and Begin Snap Animation if necessary.
2240 WrapPosition(mScrollPostPosition);
2242 mDomainOffset += deltaPosition - mScrollPostPosition;
2243 Self().SetProperty(mPropertyDomainOffset, mDomainOffset);
2245 bool animating = SnapWithVelocity(mLastVelocity * 1000.0f);
2249 AnimateOvershootToOrigin(0.0f, 0.0f);
2250 // if not animating, then this pan has completed right now.
2252 Self().SetProperty(mPropertyScrolling, false);
2253 Vector3 currentScrollPosition = GetCurrentScrollPosition();
2254 mScrollCompletedSignalV2.Emit( currentScrollPosition );
2258 Vector3 ScrollView::GetOvershoot(Vector3& position) const
2260 Vector3 size = Self().GetCurrentSize();
2263 const RulerDomain rulerDomainX = mRulerX->GetDomain();
2264 const RulerDomain rulerDomainY = mRulerY->GetDomain();
2266 if(mRulerX->IsEnabled() && rulerDomainX.enabled)
2268 const float left = rulerDomainX.min - position.x;
2269 const float right = size.width - rulerDomainX.max - position.x;
2276 overshoot.x = right;
2280 if(mRulerY->IsEnabled() && rulerDomainY.enabled)
2282 const float top = rulerDomainY.min - position.y;
2283 const float bottom = size.height - rulerDomainY.max - position.y;
2290 overshoot.y = bottom;
2297 bool ScrollView::OnAccessibilityPan(PanGesture gesture)
2299 // Keep track of whether this is an AccessibilityPan
2300 mInAccessibilityPan = true;
2302 mInAccessibilityPan = false;
2307 void ScrollView::ClampPosition(Vector3& position) const
2309 ClampState3 clamped;
2310 ClampPosition(position, clamped);
2313 void ScrollView::ClampPosition(Vector3& position, ClampState3 &clamped) const
2315 Vector3 size = Self().GetCurrentSize();
2317 // determine size of viewport relative to current scaled size.
2318 // e.g. if you're zoomed in 200%, then each pixel on screen is only 0.5 pixels on subject.
2319 if(fabsf(mScrollPostScale.x) > Math::MACHINE_EPSILON_0)
2321 size.x /= mScrollPostScale.x;
2324 if(fabsf(mScrollPostScale.y) > Math::MACHINE_EPSILON_0)
2326 size.y /= mScrollPostScale.y;
2329 position.x = -mRulerX->Clamp(-position.x, size.width, 1.0f, clamped.x); // NOTE: X & Y rulers think in -ve coordinate system.
2330 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.
2332 clamped.z = NotClamped;
2335 void ScrollView::WrapPosition(Vector3& position) const
2339 const RulerDomain rulerDomainX = mRulerX->GetDomain();
2340 const RulerDomain rulerDomainY = mRulerY->GetDomain();
2342 if(mRulerX->IsEnabled())
2344 position.x = -WrapInDomain(-position.x, rulerDomainX.min, rulerDomainX.max);
2347 if(mRulerY->IsEnabled())
2349 position.y = -WrapInDomain(-position.y, rulerDomainY.min, rulerDomainY.max);
2354 void ScrollView::ClampScale(Vector3& scale) const
2356 ClampState3 clamped;
2357 ClampScale(scale, clamped);
2360 void ScrollView::ClampScale(Vector3& scale, ClampState3 &clamped) const
2362 scale.x = mRulerScaleX->Clamp(scale.x, 0.0f, 1.0f, clamped.x);
2363 scale.y = mRulerScaleY->Clamp(scale.y, 0.0f, 1.0f, clamped.y);
2364 clamped.z = NotClamped;
2367 void ScrollView::UpdateMainInternalConstraint()
2369 // TODO: Only update the constraints which have changed, rather than remove all and add all again.
2370 // Requires a dali-core ApplyConstraintAt, or a ReplaceConstraint. The former is probably more flexible.
2371 Actor self = Self();
2372 PanGestureDetector detector( GetPanGestureDetector() );
2374 if(mScrollMainInternalPrePositionConstraint)
2376 self.RemoveConstraint(mScrollMainInternalPrePositionConstraint);
2377 self.RemoveConstraint(mScrollMainInternalPositionConstraint);
2378 self.RemoveConstraint(mScrollMainInternalDeltaConstraint);
2379 self.RemoveConstraint(mScrollMainInternalFinalConstraint);
2380 self.RemoveConstraint(mScrollMainInternalRelativeConstraint);
2383 // TODO: It's probably better to use a local displacement value as this will give a displacement when scrolling just commences
2384 // but we need to make sure than the gesture system gives displacement since last frame (60Hz), not displacement since last touch event (90Hz).
2386 // 1. First calculate the pre-position (this is the scroll position if no clamping has taken place)
2387 Vector2 initialPanMask = Vector2(mRulerX->IsEnabled() ? 1.0f : 0.0f, mRulerY->IsEnabled() ? 1.0f : 0.0f);
2389 Constraint constraint = Constraint::New<Vector3>( mPropertyPrePosition,
2390 Source( detector, PanGestureDetector::LOCAL_POSITION ),
2391 Source( detector, PanGestureDetector::LOCAL_DISPLACEMENT ),
2392 LocalSource( mPropertyX ),
2393 LocalSource( mPropertyY ),
2394 Source( self, mPropertyPanning ),
2395 InternalPrePositionConstraint( initialPanMask, mAxisAutoLock, mAxisAutoLockGradient ) );
2396 mScrollMainInternalPrePositionConstraint = self.ApplyConstraint(constraint);
2398 // 2. Second calculate the clamped position (actual position)
2399 constraint = Constraint::New<Vector3>( mPropertyPosition,
2400 LocalSource( mPropertyPrePosition ),
2401 Source( self, Actor::SIZE ),
2402 InternalPositionConstraint( mRulerX->GetDomain(),
2403 mRulerY->GetDomain()) );
2404 mScrollMainInternalPositionConstraint = self.ApplyConstraint(constraint);
2406 constraint = Constraint::New<Vector3>( mPropertyPositionDelta,
2407 LocalSource( mPropertyPosition ),
2408 LocalSource( mPropertyDomainOffset ),
2409 InternalPositionDeltaConstraint );
2410 mScrollMainInternalDeltaConstraint = self.ApplyConstraint(constraint);
2412 constraint = Constraint::New<Vector3>( mPropertyFinal,
2413 LocalSource( mPropertyPosition ),
2414 LocalSource( mPropertyOvershootX ),
2415 LocalSource( mPropertyOvershootY ),
2416 InternalFinalConstraint( FinalDefaultAlphaFunction,
2417 FinalDefaultAlphaFunction ) );
2418 mScrollMainInternalFinalConstraint = self.ApplyConstraint(constraint);
2420 constraint = Constraint::New<Vector3>( mPropertyRelativePosition,
2421 LocalSource( mPropertyPosition ),
2422 LocalSource( mPropertyPositionMin ),
2423 LocalSource( mPropertyPositionMax ),
2424 LocalSource( Actor::SIZE ),
2425 InternalRelativePositionConstraint );
2426 mScrollMainInternalRelativeConstraint = self.ApplyConstraint(constraint);
2428 if(mScrollMainInternalOvershootXConstraint)
2430 // reset these constraints in correct order
2431 self.RemoveConstraint(mScrollMainInternalOvershootXConstraint);
2432 mScrollMainInternalOvershootXConstraint.Reset();
2434 Constraint constraint = Constraint::New<float>( mPropertyOvershootX,
2435 LocalSource( mPropertyPrePosition ),
2436 LocalSource( mPropertyPosition ),
2437 OvershootXConstraint(mMaxOvershoot.x) );
2438 mScrollMainInternalOvershootXConstraint = self.ApplyConstraint(constraint);
2441 if(mScrollMainInternalOvershootYConstraint)
2443 // reset these constraints in correct order
2444 self.RemoveConstraint(mScrollMainInternalOvershootYConstraint);
2445 mScrollMainInternalOvershootYConstraint.Reset();
2447 Constraint constraint = Constraint::New<float>( mPropertyOvershootY,
2448 LocalSource( mPropertyPrePosition ),
2449 LocalSource( mPropertyPosition ),
2450 OvershootXConstraint(mMaxOvershoot.y) );
2451 mScrollMainInternalOvershootYConstraint = self.ApplyConstraint(constraint);
2455 void ScrollView::SetOvershootConstraintsEnabled(bool enabled)
2457 Actor self( Self() );
2458 // remove and reset, it may now be in wrong order with the main internal constraints
2459 if(mScrollMainInternalOvershootXConstraint)
2461 self.RemoveConstraint(mScrollMainInternalOvershootXConstraint);
2462 mScrollMainInternalOvershootXConstraint.Reset();
2464 if(mScrollMainInternalOvershootYConstraint)
2466 self.RemoveConstraint(mScrollMainInternalOvershootYConstraint);
2467 mScrollMainInternalOvershootYConstraint.Reset();
2471 Constraint constraint = Constraint::New<float>( mPropertyOvershootX,
2472 LocalSource( mPropertyPrePosition ),
2473 LocalSource( mPropertyPosition ),
2474 OvershootXConstraint(mMaxOvershoot.x) );
2475 mScrollMainInternalOvershootXConstraint = self.ApplyConstraint(constraint);
2476 constraint = Constraint::New<float>( mPropertyOvershootY,
2477 LocalSource( mPropertyPrePosition ),
2478 LocalSource( mPropertyPosition ),
2479 OvershootYConstraint(mMaxOvershoot.y) );
2480 mScrollMainInternalOvershootYConstraint = self.ApplyConstraint(constraint);
2484 void ScrollView::SetInternalConstraints()
2486 // Internal constraints (applied to target ScrollBase Actor itself) /////////
2487 UpdateMainInternalConstraint();
2489 // User definable constraints to apply to all child actors //////////////////
2490 Actor self = Self();
2492 // LocalSource - The Actors to be moved.
2493 // self - The ScrollView
2495 // Apply some default constraints to ScrollView.
2496 // Movement + Scaling + Wrap function
2498 Constraint constraint;
2500 // MoveScaledActor (scrolling/zooming)
2501 constraint = Constraint::New<Vector3>( Actor::POSITION,
2502 Source( self, mPropertyPosition ),
2503 Source( self, mPropertyScale ),
2504 MoveScaledActorConstraint );
2505 constraint.SetRemoveAction(Constraint::Discard);
2506 ApplyConstraintToBoundActors(constraint);
2508 // ScaleActor (scrolling/zooming)
2509 constraint = Constraint::New<Vector3>( Actor::SCALE,
2510 Source( self, mPropertyScale ),
2511 ScaleActorConstraint );
2512 constraint.SetRemoveAction(Constraint::Discard);
2513 ApplyConstraintToBoundActors(constraint);
2515 // WrapActor (wrap functionality)
2516 constraint = Constraint::New<Vector3>( Actor::POSITION,
2517 LocalSource( Actor::SCALE ),
2518 LocalSource( Actor::ANCHOR_POINT ),
2519 LocalSource( Actor::SIZE ),
2520 Source( self, mPropertyPositionMin ),
2521 Source( self, mPropertyPositionMax ),
2522 Source( self, mPropertyWrap ),
2523 WrapActorConstraint );
2524 constraint.SetRemoveAction(Constraint::Discard);
2525 ApplyConstraintToBoundActors(constraint);
2528 void ScrollView::SetOvershootToOrigin()
2530 // Clear Snap animation if exists.
2531 if(mSnapOvershootAnimation)
2533 mSnapOvershootAnimation.FinishedSignal().Disconnect(this, &ScrollView::OnSnapOvershootAnimationFinished);
2534 mSnapOvershootAnimation.Stop();
2535 mSnapOvershootAnimation.Clear();
2536 mSnapOvershootAnimation = NULL;
2538 SetOvershootConstraintsEnabled(false);
2539 Self().SetProperty(mPropertyOvershootX, 0.0f);
2540 Self().SetProperty(mPropertyOvershootY, 0.0f);
2543 void ScrollView::AnimateOvershootToOrigin(float xDelay, float yDelay)
2545 if( IsScrollComponentEnabled(Toolkit::Scrollable::OvershootIndicator) )
2547 if(xDelay < Math::MACHINE_EPSILON_1)
2549 // kick start animation to 0
2550 Self().SetProperty(mPropertyOvershootX, 0.0f);
2552 if(yDelay < Math::MACHINE_EPSILON_1)
2554 // kick start animation to 0
2555 Self().SetProperty(mPropertyOvershootY, 0.0f);
2559 // When we need to animate overshoot to 0
2560 if(mSnapOvershootDuration > Math::MACHINE_EPSILON_1)
2562 Actor self = Self();
2563 // Clear Snap animation if exists.
2564 if(mSnapOvershootAnimation)
2566 mSnapOvershootAnimation.FinishedSignal().Disconnect( this, &ScrollView::OnSnapOvershootAnimationFinished );
2567 mSnapOvershootAnimation.Stop();
2568 mSnapOvershootAnimation.Clear();
2569 mSnapOvershootAnimation = NULL;
2571 if(!mSnapXAnimation && mScrollMainInternalOvershootXConstraint)
2573 // need to remove the x overshoot constraint now or it will override animation to 0
2574 Self().RemoveConstraint(mScrollMainInternalOvershootXConstraint);
2575 mScrollMainInternalOvershootXConstraint.Reset();
2576 mScrollMainInternalOvershootXConstraint = 0;
2578 if(!mSnapYAnimation && mScrollMainInternalOvershootYConstraint)
2580 // need to remove the y overshoot constraint now or it will override animation to 0
2581 Self().RemoveConstraint(mScrollMainInternalOvershootYConstraint);
2582 mScrollMainInternalOvershootYConstraint.Reset();
2583 mScrollMainInternalOvershootYConstraint = 0;
2585 // setup the new overshoot to 0 animation
2586 float totalDuration = (xDelay > yDelay ? xDelay : yDelay) + mSnapOvershootDuration;
2587 mSnapOvershootAnimation = Animation::New(totalDuration);
2588 mSnapOvershootAnimation.FinishedSignal().Connect( this, &ScrollView::OnSnapOvershootAnimationFinished );
2590 mSnapOvershootAnimation.AnimateTo( Property(self, mPropertyOvershootX), 0.0f, mSnapOvershootAlphaFunction, TimePeriod(xDelay, mSnapOvershootDuration) );
2591 mSnapOvershootAnimation.AnimateTo( Property(self, mPropertyOvershootY), 0.0f, mSnapOvershootAlphaFunction, TimePeriod(yDelay, mSnapOvershootDuration) );
2593 mSnapOvershootAnimation.SetDuration(totalDuration);
2594 mSnapOvershootAnimation.Play();
2598 SetOvershootToOrigin();
2602 void ScrollView::OnSnapOvershootAnimationFinished( Animation& source )
2604 mSnapOvershootAnimation = NULL;
2607 void ScrollView::StartRefreshTimer()
2609 if(mRefreshIntervalMilliseconds > 0)
2613 mRefreshTimer = Timer::New( mRefreshIntervalMilliseconds );
2614 mRefreshTimer.TickSignal().Connect( this, &ScrollView::OnRefreshTick );
2617 if (!mRefreshTimer.IsRunning())
2619 mRefreshTimer.Start();
2624 void ScrollView::CancelRefreshTimer()
2628 mRefreshTimer.Stop();
2632 bool ScrollView::OnRefreshTick()
2634 // Guard against destruction during signal emission
2635 Toolkit::ScrollView handle( GetOwner() );
2637 Vector3 currentScrollPosition = GetCurrentScrollPosition();
2638 mScrollUpdatedSignalV2.Emit( currentScrollPosition );
2643 } // namespace Internal
2645 } // namespace Toolkit