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/internal/controls/scrollable/scroll-view/scroll-view-impl.h>
21 #include <dali-toolkit/public-api/controls/scrollable/scroll-view/scroll-view-constraints.h>
22 #include <dali-toolkit/internal/controls/scrollable/scroll-view/scroll-view-effect-impl.h>
23 #include <dali-toolkit/internal/controls/scroll-component/scroll-component-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)
545 SetRequiresMouseWheelEvents(true);
548 void ScrollView::OnInitialize()
551 self.SetLeaveRequired(true);
553 // Internal Actor, used to hide actors from enumerations.
554 // Also actors added to Internal actor appear as overlays e.g. ScrollBar components.
555 mInternalActor = Actor::New();
556 mInternalActor.SetDrawMode(DrawMode::OVERLAY);
557 self.Add(mInternalActor);
558 mInternalActor.ApplyConstraint( Constraint::New<Vector3>( Actor::SIZE, ParentSource( Actor::SIZE ), EqualToConstraint() ) );
559 mInternalActor.SetParentOrigin(ParentOrigin::CENTER);
560 mInternalActor.SetAnchorPoint(AnchorPoint::CENTER);
564 // Register Scroll Properties.
565 RegisterProperties();
567 mScrollPostPosition = mScrollPrePosition = Vector3::ZERO;
568 mScrollPostScale = mScrollPreScale = Vector3::ONE;
569 mScrollPostRotation = mScrollPreRotation = 0.0f;
571 mMouseWheelScrollDistanceStep = Stage::GetCurrent().GetSize() * DEFAULT_MOUSE_WHEEL_SCROLL_DISTANCE_STEP_PROPORTION;
575 mGestureStackDepth = 0;
577 EnableGestureDetection( Gesture::Type( Gesture::Pan | Gesture::Pinch ) );
579 // For pan, default to only 1 touch required, ignoring touches outside this range.
580 SetTouchesRequiredForPanning(1, 1, false);
582 // By default we'll allow the user to freely drag the scroll view,
583 // while disabling the other rulers.
584 RulerPtr ruler = new DefaultRuler();
585 RulerPtr rulerDisabled = new DefaultRuler();
586 rulerDisabled->Disable();
589 mRulerScaleX = rulerDisabled;
590 mRulerScaleY = rulerDisabled;
591 mRulerRotation = rulerDisabled;
593 EnableScrollComponent(Toolkit::Scrollable::OvershootIndicator);
595 Vector3 size = GetControlSize();
596 UpdatePropertyDomain(size);
597 SetInternalConstraints();
600 void ScrollView::OnControlStageConnection()
604 SetScrollSensitive( false );
605 SetScrollSensitive( true );
607 if(IsScrollComponentEnabled(Toolkit::Scrollable::OvershootIndicator))
609 // try and make sure property notifications are set
610 EnableScrollComponent(Toolkit::Scrollable::OvershootIndicator);
614 void ScrollView::OnControlStageDisconnection()
616 if ( mSnapOvershootAnimation )
618 SetOvershootToOrigin();
624 ScrollView::~ScrollView()
628 AlphaFunction ScrollView::GetScrollSnapAlphaFunction() const
630 return mSnapAlphaFunction;
633 void ScrollView::SetScrollSnapAlphaFunction(AlphaFunction alpha)
635 mSnapAlphaFunction = alpha;
638 AlphaFunction ScrollView::GetScrollFlickAlphaFunction() const
640 return mFlickAlphaFunction;
643 void ScrollView::SetScrollFlickAlphaFunction(AlphaFunction alpha)
645 mFlickAlphaFunction = alpha;
648 float ScrollView::GetScrollSnapDuration() const
650 return mSnapDuration;
653 void ScrollView::SetScrollSnapDuration(float time)
655 mSnapDuration = time;
658 float ScrollView::GetScrollFlickDuration() const
660 return mFlickDuration;
663 void ScrollView::SetScrollFlickDuration(float time)
665 mFlickDuration = time;
668 void ScrollView::ApplyEffect(Toolkit::ScrollViewEffect effect)
670 Dali::Toolkit::ScrollView self = Dali::Toolkit::ScrollView::DownCast(Self());
672 // Assertion check to ensure effect doesn't already exist in this scrollview
673 bool effectAlreadyExistsInScrollView(false);
674 for (ScrollViewEffectIter iter = mEffects.begin(); iter != mEffects.end(); ++iter)
678 effectAlreadyExistsInScrollView = true;
683 DALI_ASSERT_ALWAYS(!effectAlreadyExistsInScrollView);
685 // add effect to effects list
686 mEffects.push_back(effect);
688 // invoke Attachment request to ScrollView first
689 GetImpl(effect).Attach(self);
692 Toolkit::ScrollViewEffect ScrollView::ApplyEffect(Toolkit::ScrollView::PageEffect effect)
694 Toolkit::ScrollViewEffect scrollEffect;
697 case Toolkit::ScrollView::PageEffectNone:
701 case Toolkit::ScrollView::PageEffectOuterCube:
703 Toolkit::ScrollViewCustomEffect customEffect;
704 scrollEffect = customEffect = Toolkit::ScrollViewCustomEffect::New();
705 Vector2 pageSize = Stage::GetCurrent().GetSize();
706 // 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
707 // 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)
708 // the page moving off screen will slowly build a spacing from 0.0f to 20.0f
709 // the spacing from each page is added together for the final spacing between the two pages.
710 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));
711 customEffect.SetSwingAngleOut(ANGLE_CUSTOM_CUBE_SWING.x, Vector3(0.0f, -1.0f, 0.0f));
712 customEffect.SetSwingAnchor(AnchorPoint::CENTER, AnchorPoint::CENTER_LEFT);
713 customEffect.SetOpacityThreshold(0.7f);
716 case Toolkit::ScrollView::PageEffectDepth:
718 Toolkit::ScrollViewCustomEffect customEffect;
719 scrollEffect = customEffect = Toolkit::ScrollViewCustomEffect::New();
722 case Toolkit::ScrollView::PageEffectInnerCube:
724 Toolkit::ScrollViewCustomEffect customEffect;
725 scrollEffect = customEffect = Toolkit::ScrollViewCustomEffect::New();
726 customEffect.SetPageSpacing(Vector2(30.0f, 30.0f));
727 customEffect.SetAngledOriginPageRotation(ANGLE_CUBE_PAGE_ROTATE);
728 customEffect.SetSwingAngle(ANGLE_CUBE_PAGE_ROTATE.x, Vector3(0,-1,0));
729 customEffect.SetOpacityThreshold(0.5f);
732 case Toolkit::ScrollView::PageEffectCarousel:
734 Toolkit::ScrollViewCustomEffect customEffect;
735 scrollEffect = customEffect = Toolkit::ScrollViewCustomEffect::New();
736 customEffect.SetPageTranslation(Vector3(0,0,0), Vector3(-30, 0, 0));
737 customEffect.SetPageSpacing(Vector2(60.0f, 60.0f));
738 customEffect.SetAngledOriginPageRotation(-ANGLE_CUBE_PAGE_ROTATE);
739 customEffect.SetOpacityThreshold(0.2f, 0.6f);
742 case Toolkit::ScrollView::PageEffectSpiral:
744 Toolkit::ScrollViewCustomEffect customEffect;
745 scrollEffect = customEffect = Toolkit::ScrollViewCustomEffect::New();
747 Vector2 pageSize = Stage::GetCurrent().GetSize();
748 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));
749 //customEffect.SetSwingAngleAlphaFunctionOut(AlphaFunctions::EaseOut);
750 customEffect.SetSwingAnchor(AnchorPoint::CENTER_RIGHT);
751 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);
752 //customEffect.SetPageTranslateAlphaFunctionOut(AlphaFunctions::EaseOut);
753 customEffect.SetOpacityThreshold(0.75f, 0.6f);
754 customEffect.SetOpacityAlphaFunctionIn(AlphaFunctions::EaseInOut);
759 DALI_ASSERT_DEBUG(0 && "unknown scroll view effect");
762 RemoveConstraintsFromChildren();
765 ApplyEffect(scrollEffect);
770 void ScrollView::RemoveEffect(Toolkit::ScrollViewEffect effect)
772 Dali::Toolkit::ScrollView self = Dali::Toolkit::ScrollView::DownCast(Self());
774 // remove effect from effects list
775 bool effectExistedInScrollView(false);
776 for (ScrollViewEffectIter iter = mEffects.begin(); iter != mEffects.end(); ++iter)
780 mEffects.erase(iter);
781 effectExistedInScrollView = true;
786 // Assertion check to ensure effect existed.
787 DALI_ASSERT_ALWAYS(effectExistedInScrollView);
789 // invoke Detachment request to ScrollView last
790 GetImpl(effect).Detach(self);
793 void ScrollView::RemoveAllEffects()
795 Dali::Toolkit::ScrollView self = Dali::Toolkit::ScrollView::DownCast(Self());
797 for (ScrollViewEffectIter effectIter = mEffects.begin(); effectIter != mEffects.end(); ++effectIter)
799 Toolkit::ScrollViewEffect effect = *effectIter;
801 // invoke Detachment request to ScrollView last
802 GetImpl(effect).Detach(self);
808 void ScrollView::ApplyConstraintToChildren(Constraint constraint)
810 ApplyConstraintToBoundActors(constraint);
813 void ScrollView::RemoveConstraintsFromChildren()
815 RemoveConstraintsFromBoundActors();
818 const RulerPtr ScrollView::GetRulerX() const
823 const RulerPtr ScrollView::GetRulerY() const
828 void ScrollView::SetRulerX(RulerPtr ruler)
832 Vector3 size = GetControlSize();
833 UpdatePropertyDomain(size);
834 UpdateMainInternalConstraint();
837 void ScrollView::SetRulerY(RulerPtr ruler)
841 Vector3 size = GetControlSize();
842 UpdatePropertyDomain(size);
843 UpdateMainInternalConstraint();
846 void ScrollView::UpdatePropertyDomain(const Vector3& size)
851 bool canScrollVertical = false;
852 bool canScrollHorizontal = false;
854 if(mRulerX->IsEnabled())
856 const Toolkit::RulerDomain& rulerDomain = mRulerX->GetDomain();
857 min.x = rulerDomain.min;
858 max.x = rulerDomain.max;
860 // make sure new scroll value is within new domain
861 float newScroll = min.x;
862 int scrollXPropertyIndex = self.GetPropertyIndex(Toolkit::ScrollView::SCROLL_X_PROPERTY_NAME);
863 if((fabsf(max.x - min.x) - size.x) > Math::MACHINE_EPSILON_1)
865 canScrollHorizontal = true;
866 float currentScroll = self.GetProperty<float>(scrollXPropertyIndex);
867 newScroll = Clamp(currentScroll, -(max.x - size.x), -min.x);
869 self.SetProperty(scrollXPropertyIndex, newScroll);
872 if(mRulerY->IsEnabled())
874 const Toolkit::RulerDomain& rulerDomain = mRulerY->GetDomain();
875 min.y = rulerDomain.min;
876 max.y = rulerDomain.max;
878 // make sure new scroll value is within new domain
879 float newScroll = min.y;
880 int scrollYPropertyIndex = self.GetPropertyIndex(Toolkit::ScrollView::SCROLL_Y_PROPERTY_NAME);
881 if((fabsf(max.y - min.y) - size.y) > Math::MACHINE_EPSILON_1)
883 canScrollVertical = true;
884 float currentScroll = self.GetProperty<float>(scrollYPropertyIndex);
885 newScroll = Clamp(currentScroll, -(max.y - size.y), -min.y);
887 self.SetProperty(scrollYPropertyIndex, newScroll);
889 self.SetProperty(mPropertyCanScrollVertical, canScrollVertical);
890 self.SetProperty(mPropertyCanScrollHorizontal, canScrollHorizontal);
892 self.SetProperty(mPropertyPositionMin, min );
893 self.SetProperty(mPropertyPositionMax, max );
896 void ScrollView::SetRulerScaleX(RulerPtr ruler)
898 mRulerScaleX = ruler;
899 UpdateMainInternalConstraint();
902 void ScrollView::SetRulerScaleY(RulerPtr ruler)
904 mRulerScaleY = ruler;
905 UpdateMainInternalConstraint();
908 void ScrollView::SetRulerRotation(RulerPtr ruler)
910 mRulerRotation = ruler;
911 UpdateMainInternalConstraint();
914 void ScrollView::SetScrollSensitive(bool sensitive)
917 PanGestureDetector panGesture( GetPanGestureDetector() );
918 PinchGestureDetector pinchGesture( GetPinchGestureDetector() );
920 if((!mSensitive) && (sensitive))
922 mSensitive = sensitive;
923 panGesture.Attach(self);
924 pinchGesture.Attach(self);
926 else if((mSensitive) && (!sensitive))
928 mSensitive = sensitive;
929 panGesture.Detach(self);
930 pinchGesture.Detach(self);
932 mGestureStackDepth = 0;
933 self.SetProperty(mPropertyPanning, false);
935 // Remove X & Y position constraints as they are not required when we are not panning.
936 self.RemoveConstraint(mScrollMainInternalXConstraint);
937 self.RemoveConstraint(mScrollMainInternalYConstraint);
941 void ScrollView::SetMaxOvershoot(float overshootX, float overshootY)
943 mMaxOvershoot.x = overshootX;
944 mMaxOvershoot.y = overshootY;
945 mDefaultMaxOvershoot = false;
946 UpdateMainInternalConstraint();
949 void ScrollView::SetSnapOvershootAlphaFunction(AlphaFunction alpha)
951 mSnapOvershootAlphaFunction = alpha;
954 void ScrollView::SetSnapOvershootDuration(float duration)
956 mSnapOvershootDuration = duration;
959 void ScrollView::SetTouchesRequiredForPanning(unsigned int minTouches, unsigned int maxTouches, bool endOutside)
961 PanGestureDetector panGesture( GetPanGestureDetector() );
963 mMinTouchesForPanning = minTouches;
964 mMaxTouchesForPanning = maxTouches;
968 panGesture.SetMinimumTouchesRequired(minTouches);
969 panGesture.SetMaximumTouchesRequired(maxTouches);
973 panGesture.SetMinimumTouchesRequired(1);
974 panGesture.SetMaximumTouchesRequired(UINT_MAX);
978 void ScrollView::SetActorAutoSnap(bool enable)
980 mActorAutoSnapEnabled = enable;
983 void ScrollView::SetAutoResize(bool enable)
985 mAutoResizeContainerEnabled = enable;
986 // TODO: This needs a lot of issues to be addressed before working.
989 bool ScrollView::GetWrapMode() const
994 void ScrollView::SetWrapMode(bool enable)
997 Self().SetProperty(mPropertyWrap, enable);
1000 int ScrollView::GetRefreshInterval() const
1002 return mRefreshIntervalMilliseconds;
1005 void ScrollView::SetRefreshInterval(int milliseconds)
1007 mRefreshIntervalMilliseconds = milliseconds;
1010 bool ScrollView::GetAxisAutoLock() const
1012 return mAxisAutoLock;
1015 void ScrollView::SetAxisAutoLock(bool enable)
1017 mAxisAutoLock = enable;
1018 UpdateMainInternalConstraint();
1021 float ScrollView::GetAxisAutoLockGradient() const
1023 return mAxisAutoLockGradient;
1026 void ScrollView::SetAxisAutoLockGradient(float gradient)
1028 DALI_ASSERT_DEBUG( gradient >= 0.0f && gradient <= 1.0f );
1029 mAxisAutoLockGradient = gradient;
1030 UpdateMainInternalConstraint();
1033 float ScrollView::GetFrictionCoefficient() const
1035 return mFrictionCoefficient;
1038 void ScrollView::SetFrictionCoefficient(float friction)
1040 DALI_ASSERT_DEBUG( friction > 0.0f );
1041 mFrictionCoefficient = friction;
1044 float ScrollView::GetFlickSpeedCoefficient() const
1046 return mFlickSpeedCoefficient;
1049 void ScrollView::SetFlickSpeedCoefficient(float speed)
1051 mFlickSpeedCoefficient = speed;
1054 float ScrollView::GetMaxFlickSpeed() const
1056 return mMaxFlickSpeed;
1059 void ScrollView::SetMaxFlickSpeed(float speed)
1061 mMaxFlickSpeed = speed;
1064 void ScrollView::SetMouseWheelScrollDistanceStep(Vector2 step)
1066 mMouseWheelScrollDistanceStep = step;
1069 Vector2 ScrollView::GetMouseWheelScrollDistanceStep() const
1071 return mMouseWheelScrollDistanceStep;
1074 unsigned int ScrollView::GetCurrentPage() const
1076 // in case animation is currently taking place.
1077 Vector3 position = GetPropertyPrePosition();
1079 Actor self = Self();
1080 unsigned int page = 0;
1081 unsigned int pagesPerVolume = 1;
1082 unsigned int volume = 0;
1084 // if rulerX is enabled, then get page count (columns)
1085 page = mRulerX->GetPageFromPosition(-position.x, mWrapMode);
1086 volume = mRulerY->GetPageFromPosition(-position.y, mWrapMode);
1087 pagesPerVolume = mRulerX->GetTotalPages();
1089 return volume * pagesPerVolume + page;
1092 Vector3 ScrollView::GetCurrentScrollPosition() const
1094 // in case animation is currently taking place.
1095 return -GetPropertyPrePosition();
1098 Vector3 ScrollView::GetCurrentScrollScale() const
1100 // in case animation is currently taking place.
1101 return GetPropertyScale();
1104 Vector3 ScrollView::GetDomainSize() const
1106 Vector3 size = Self().GetCurrentSize();
1108 const RulerDomain& xDomain = GetRulerX()->GetDomain();
1109 const RulerDomain& yDomain = GetRulerY()->GetDomain();
1111 Vector3 domainSize = Vector3( xDomain.max - xDomain.min, yDomain.max - yDomain.min, 0.0f ) - size;
1115 void ScrollView::TransformTo(const Vector3& position, const Vector3& scale, float rotation,
1116 DirectionBias horizontalBias, DirectionBias verticalBias)
1118 TransformTo(position, scale, rotation, mSnapDuration, horizontalBias, verticalBias);
1121 void ScrollView::TransformTo(const Vector3& position, const Vector3& scale, float rotation, float duration,
1122 DirectionBias horizontalBias, DirectionBias verticalBias)
1124 // Guard against destruction during signal emission
1125 // Note that Emit() methods are called indirectly e.g. from within ScrollView::AnimateTo()
1126 Toolkit::ScrollView handle( GetOwner() );
1128 Vector3 currentScrollPosition = GetCurrentScrollPosition();
1129 Self().SetProperty( mPropertyScrollStartPagePosition, currentScrollPosition );
1131 if(mScrolling) // are we interrupting a current scroll?
1133 // set mScrolling to false, in case user has code that interrogates mScrolling Getter() in complete.
1135 mScrollCompletedSignalV2.Emit( currentScrollPosition );
1138 Self().SetProperty(mPropertyScrolling, true);
1140 mScrollStartedSignalV2.Emit( currentScrollPosition );
1141 bool animating = AnimateTo(-position,
1142 Vector3::ONE * duration,
1144 Vector3::ONE * duration,
1155 // if not animating, then this pan has completed right now.
1156 Self().SetProperty(mPropertyScrolling, false);
1158 mScrollCompletedSignalV2.Emit( currentScrollPosition );
1162 void ScrollView::ScrollTo(const Vector3& position)
1164 ScrollTo(position, mSnapDuration );
1167 void ScrollView::ScrollTo(const Vector3& position, float duration)
1169 ScrollTo(position, duration, DirectionBiasNone, DirectionBiasNone);
1172 void ScrollView::ScrollTo(const Vector3& position, float duration,
1173 DirectionBias horizontalBias, DirectionBias verticalBias)
1175 TransformTo(position, mScrollPostScale, mScrollPostRotation, duration, horizontalBias, verticalBias);
1178 void ScrollView::ScrollTo(unsigned int page)
1180 ScrollTo(page, mSnapDuration);
1183 void ScrollView::ScrollTo(unsigned int page, float duration, DirectionBias bias)
1186 unsigned int volume;
1187 unsigned int libraries;
1189 // The position to scroll to is continuous and linear
1190 // unless a domain has been enabled on the X axis.
1191 // or if WrapMode has been enabled.
1192 bool carryX = mRulerX->GetDomain().enabled | mWrapMode;
1193 bool carryY = mRulerY->GetDomain().enabled | mWrapMode;
1195 position.x = mRulerX->GetPositionFromPage(page, volume, carryX);
1196 position.y = mRulerY->GetPositionFromPage(volume, libraries, carryY);
1198 ScrollTo(position, duration, bias, bias);
1201 void ScrollView::ScrollTo(Actor &actor)
1203 ScrollTo(actor, mSnapDuration);
1206 void ScrollView::ScrollTo(Actor &actor, float duration)
1208 DALI_ASSERT_ALWAYS(actor.GetParent() == Self());
1210 Actor self = Self();
1211 Vector3 size = self.GetCurrentSize();
1212 Vector3 position = actor.GetCurrentPosition();
1213 position -= GetPropertyPrePosition();
1215 ScrollTo(Vector3(position.x - size.width * 0.5f, position.y - size.height * 0.5f, 0.0f), duration);
1218 Actor ScrollView::FindClosestActor()
1220 Actor self = Self();
1221 Vector3 size = self.GetCurrentSize();
1223 return FindClosestActorToPosition(Vector3(size.width * 0.5f,size.height * 0.5f,0.0f));
1226 Actor ScrollView::FindClosestActorToPosition(const Vector3& position, FindDirection dirX, FindDirection dirY, FindDirection dirZ)
1229 float closestDistance2 = 0.0f;
1230 Vector3 actualPosition = position;
1232 unsigned int numChildren = Self().GetChildCount();
1234 for(unsigned int i = 0; i < numChildren; ++i)
1236 Actor child = Self().GetChildAt(i);
1238 if(mInternalActor == child) // ignore internal actor.
1243 Vector3 childPosition = GetPositionOfAnchor(child, AnchorPoint::CENTER);
1245 Vector3 delta = childPosition - actualPosition;
1247 // X-axis checking (only find Actors to the [dirX] of actualPosition)
1248 if(dirX > All) // != All,None
1250 FindDirection deltaH = delta.x > 0 ? Right : Left;
1257 // Y-axis checking (only find Actors to the [dirY] of actualPosition)
1258 if(dirY > All) // != All,None
1260 FindDirection deltaV = delta.y > 0 ? Down : Up;
1267 // Z-axis checking (only find Actors to the [dirZ] of actualPosition)
1268 if(dirZ > All) // != All,None
1270 FindDirection deltaV = delta.y > 0 ? In : Out;
1277 // compare child to closest child in terms of distance.
1278 float distance2 = 0.0f;
1280 // distance2 = the Square of the relevant dimensions of delta
1283 distance2 += delta.x * delta.x;
1288 distance2 += delta.y * delta.y;
1293 distance2 += delta.z * delta.z;
1296 if(closestChild) // Next time.
1298 if(distance2 < closestDistance2)
1300 closestChild = child;
1301 closestDistance2 = distance2;
1306 closestChild = child;
1307 closestDistance2 = distance2;
1311 return closestChild;
1314 bool ScrollView::ScrollToSnapPoint()
1316 Vector2 stationaryVelocity = Vector2(0.0f, 0.0f);
1317 return SnapWithVelocity( stationaryVelocity );
1320 void ScrollView::ScaleTo(const Vector3& scale)
1322 ScaleTo(scale, mSnapDuration);
1325 void ScrollView::ScaleTo(const Vector3& scale, float duration)
1327 TransformTo(mScrollPostPosition, scale, mScrollPostRotation, duration);
1331 // TODO: In situations where axes are different (X snap, Y free)
1332 // Each axis should really have their own independent animation (time and equation)
1333 // Consider, X axis snapping to nearest grid point (EaseOut over fixed time)
1334 // Consider, Y axis simulating physics to arrive at a point (Physics equation over variable time)
1335 // Currently, the axes have been split however, they both use the same EaseOut equation.
1336 bool ScrollView::SnapWithVelocity(Vector2 velocity)
1338 // Animator takes over now, touches are assumed not to interfere.
1339 // And if touches do interfere, then we'll stop animation, update PrePosition
1340 // to current mScroll's properties, and then resume.
1341 // Note: For Flicking this may work a bit different...
1343 float angle = atan2(velocity.y, velocity.x);
1344 float speed2 = velocity.LengthSquared();
1345 AlphaFunction alphaFunction = mSnapAlphaFunction;
1346 Vector3 positionDuration = Vector3::ONE * mSnapDuration;
1347 Vector3 scaleDuration = Vector3::ONE * mSnapDuration;
1348 float rotationDuration = mSnapDuration;
1351 FindDirection horizontal = None;
1352 FindDirection vertical = None;
1354 // orthoAngleRange = Angle tolerance within the Exact N,E,S,W direction
1355 // that will be accepted as a general N,E,S,W flick direction.
1357 const float orthoAngleRange = FLICK_ORTHO_ANGLE_RANGE * M_PI / 180.0f;
1358 const float flickSpeedThreshold2 = FLICK_SPEED_THRESHOLD*FLICK_SPEED_THRESHOLD;
1360 // Flick logic X Axis
1362 if(mRulerX->IsEnabled())
1366 if(speed2 > flickSpeedThreshold2) // exceeds flick threshold
1368 if((angle >= -orthoAngleRange) && (angle < orthoAngleRange)) // Swiping East
1370 biasX = 0.0f, horizontal = Left;
1372 else if((angle >= M_PI-orthoAngleRange) || (angle < -M_PI+orthoAngleRange)) // Swiping West
1374 biasX = 1.0f, horizontal = Right;
1379 // Flick logic Y Axis
1381 if(mRulerY->IsEnabled())
1385 if(speed2 > flickSpeedThreshold2) // exceeds flick threshold
1387 if((angle >= M_PI_2-orthoAngleRange) && (angle < M_PI_2+orthoAngleRange)) // Swiping South
1389 biasY = 0.0f, vertical = Up;
1391 else if((angle >= -M_PI_2-orthoAngleRange) && (angle < -M_PI_2+orthoAngleRange)) // Swiping North
1393 biasY = 1.0f, vertical = Down;
1398 // isFlick: Whether this gesture is a flick or not.
1399 bool isFlick = (horizontal != All || vertical != All);
1400 // isFreeFlick: Whether this gesture is a flick under free panning criteria.
1401 bool isFreeFlick = velocity.LengthSquared() > (FREE_FLICK_SPEED_THRESHOLD*FREE_FLICK_SPEED_THRESHOLD);
1403 if(isFlick || isFreeFlick)
1405 positionDuration = Vector3::ONE * mFlickDuration;
1406 alphaFunction = mFlickAlphaFunction;
1409 // Position Snap ////////////////////////////////////////////////////////////
1410 Vector3 positionSnap = mScrollPostPosition;
1412 if(mActorAutoSnapEnabled)
1414 Vector3 size = Self().GetCurrentSize();
1416 Actor child = FindClosestActorToPosition( Vector3(size.width * 0.5f,size.height * 0.5f,0.0f), horizontal, vertical );
1418 if(!child && isFlick )
1420 // If we conducted a direction limited search and found no actor, then just snap to the closest actor.
1421 child = FindClosestActorToPosition( Vector3(size.width * 0.5f,size.height * 0.5f,0.0f) );
1426 Vector3 position = Self().GetProperty<Vector3>(mPropertyPosition);
1428 // Get center-point of the Actor.
1429 Vector3 childPosition = GetPositionOfAnchor(child, AnchorPoint::CENTER);
1431 if(mRulerX->IsEnabled())
1433 positionSnap.x = position.x - childPosition.x + size.width * 0.5f;
1435 if(mRulerY->IsEnabled())
1437 positionSnap.y = position.y - childPosition.y + size.height * 0.5f;
1442 Vector3 startPosition = positionSnap;
1443 positionSnap.x = -mRulerX->Snap(-positionSnap.x, biasX); // NOTE: X & Y rulers think in -ve coordinate system.
1444 positionSnap.y = -mRulerY->Snap(-positionSnap.y, biasY); // That is scrolling RIGHT (e.g. 100.0, 0.0) means moving LEFT.
1446 Vector3 clampDelta(Vector3::ZERO);
1447 ClampPosition(positionSnap);
1449 if( (mRulerX->GetType() == Ruler::Free || mRulerY->GetType() == Ruler::Free)
1450 && isFreeFlick && !mActorAutoSnapEnabled)
1452 // Calculate target position based on velocity of flick.
1454 // a = Deceleration (Set to diagonal stage length * friction coefficient)
1455 // u = Initial Velocity (Flick velocity)
1456 // v = 0 (Final Velocity)
1457 // t = Time (Velocity / Deceleration)
1458 Vector2 stageSize = Stage::GetCurrent().GetSize();
1459 float stageLength = Vector3(stageSize.x, stageSize.y, 0.0f).Length();
1460 float a = (stageLength * mFrictionCoefficient);
1461 Vector3 u = Vector3(velocity.x, velocity.y, 0.0f) * mFlickSpeedCoefficient;
1462 float speed = u.Length();
1465 // TODO: Change this to a decay function. (faster you flick, the slower it should be)
1466 speed = std::min(speed, stageLength * mMaxFlickSpeed );
1468 alphaFunction = ConstantDecelerationAlphaFunction;
1470 float t = speed / a;
1472 if(mRulerX->IsEnabled() && mRulerX->GetType() == Ruler::Free)
1474 positionSnap.x += t*u.x*0.5f;
1477 if(mRulerY->IsEnabled() && mRulerY->GetType() == Ruler::Free)
1479 positionSnap.y += t*u.y*0.5f;
1482 clampDelta = positionSnap;
1483 ClampPosition(positionSnap);
1484 if((positionSnap - startPosition).LengthSquared() > Math::MACHINE_EPSILON_0)
1486 clampDelta -= positionSnap;
1487 clampDelta.x = clampDelta.x > 0.0f ? std::min(clampDelta.x, mMaxOvershoot.x) : std::max(clampDelta.x, -mMaxOvershoot.x);
1488 clampDelta.y = clampDelta.y > 0.0f ? std::min(clampDelta.y, mMaxOvershoot.y) : std::max(clampDelta.y, -mMaxOvershoot.y);
1492 clampDelta = Vector3::ZERO;
1495 // If Axis is Free and has velocity, then calculate time taken
1496 // to reach target based on velocity in axis.
1497 if(mRulerX->IsEnabled() && mRulerX->GetType() == Ruler::Free)
1499 float deltaX = fabsf(startPosition.x - positionSnap.x);
1501 if(fabsf(u.x) > Math::MACHINE_EPSILON_1)
1503 positionDuration.x = fabsf(deltaX / u.x);
1507 positionDuration.x = 0;
1511 if(mRulerY->IsEnabled() && mRulerY->GetType() == Ruler::Free)
1513 float deltaY = fabsf(startPosition.y - positionSnap.y);
1515 if(fabsf(u.y) > Math::MACHINE_EPSILON_1)
1517 positionDuration.y = fabsf(deltaY / u.y);
1521 positionDuration.y = 0;
1525 positionSnap += clampDelta;
1527 // Scale Snap ///////////////////////////////////////////////////////////////
1528 Vector3 scaleSnap = mScrollPostScale;
1530 scaleSnap.x = mRulerScaleX->Snap(scaleSnap.x);
1531 scaleSnap.y = mRulerScaleY->Snap(scaleSnap.y);
1533 ClampScale(scaleSnap);
1535 // Rotation Snap ////////////////////////////////////////////////////////////
1536 float rotationSnap = mScrollPostRotation;
1537 // TODO: implement rotation snap
1539 bool animating = AnimateTo(positionSnap, positionDuration,
1540 scaleSnap, scaleDuration,
1541 rotationSnap, rotationDuration,
1542 alphaFunction, false,
1543 DirectionBiasNone, DirectionBiasNone,
1544 isFlick || isFreeFlick ? Flick : Snap);
1548 AnimateOvershootToOrigin(positionDuration.x, positionDuration.y);
1554 void ScrollView::StopAnimation(void)
1556 // Clear Snap animation if exists.
1559 mSnapAnimation.Stop();
1560 mSnapAnimation.FinishedSignal().Disconnect(this, &ScrollView::OnSnapAnimationFinished);
1561 mSnapAnimation.Clear();
1562 mSnapAnimation = NULL;
1566 mSnapXAnimation.Stop();
1567 mSnapXAnimation.FinishedSignal().Disconnect(this, &ScrollView::OnSnapXAnimationFinished);
1568 mSnapXAnimation.Clear();
1569 mSnapXAnimation = NULL;
1573 mSnapYAnimation.Stop();
1574 mSnapYAnimation.FinishedSignal().Disconnect(this, &ScrollView::OnSnapYAnimationFinished);
1575 mSnapYAnimation.Clear();
1576 mSnapYAnimation = NULL;
1578 if(mSnapOvershootAnimation)
1580 mSnapOvershootAnimation.FinishedSignal().Disconnect(this, &ScrollView::OnSnapOvershootAnimationFinished);
1581 mSnapOvershootAnimation.Stop();
1582 mSnapOvershootAnimation.Clear();
1583 mSnapOvershootAnimation = NULL;
1585 HandleStoppedAnimation();
1588 bool ScrollView::AnimateTo(const Vector3& position, const Vector3& positionDuration,
1589 const Vector3& scale, const Vector3& scaleDuration,
1590 float rotation, float rotationDuration,
1591 AlphaFunction alpha, bool findShortcuts,
1592 DirectionBias horizontalBias, DirectionBias verticalBias,
1595 // Here we perform an animation on a number of properties (depending on which have changed)
1596 // The animation is applied to all ScrollBases
1597 Actor self = Self();
1598 bool startAnimation = false;
1599 Vector3 positionTransformed = position;
1600 float totalDuration = 0.0f;
1602 bool positionChanged = (positionTransformed != mScrollPostPosition);
1603 bool scaleChanged = (scale != mScrollPostScale);
1604 bool rotationChanged = fabsf(rotation - mScrollPostRotation) > Math::MACHINE_EPSILON_0;
1608 totalDuration = std::max(totalDuration, positionDuration.x);
1609 totalDuration = std::max(totalDuration, positionDuration.y);
1614 totalDuration = std::max(totalDuration, scaleDuration.x);
1615 totalDuration = std::max(totalDuration, scaleDuration.y);
1620 totalDuration = std::max(totalDuration, rotationDuration);
1623 if(totalDuration > Math::MACHINE_EPSILON_1)
1626 mSnapAnimation = Animation::New(totalDuration);
1627 mSnapAnimation.FinishedSignal().Connect(this, &ScrollView::OnSnapAnimationFinished);
1628 mSnapXAnimation = Animation::New(positionDuration.x);
1629 mSnapXAnimation.FinishedSignal().Connect(this, &ScrollView::OnSnapXAnimationFinished);
1630 mSnapYAnimation = Animation::New(positionDuration.y);
1631 mSnapYAnimation.FinishedSignal().Connect(this, &ScrollView::OnSnapYAnimationFinished);
1632 startAnimation = true;
1634 // Position Delta ///////////////////////////////////////////////////////
1637 if(mWrapMode && findShortcuts)
1639 // In Wrap Mode, the shortest distance is a little less intuitive...
1640 const RulerDomain rulerDomainX = mRulerX->GetDomain();
1641 const RulerDomain rulerDomainY = mRulerY->GetDomain();
1643 if(mRulerX->IsEnabled())
1645 float dir = VectorInDomain(-mScrollPostPosition.x, -positionTransformed.x, rulerDomainX.min, rulerDomainX.max, horizontalBias);
1646 positionTransformed.x = mScrollPostPosition.x + -dir;
1649 if(mRulerY->IsEnabled())
1651 float dir = VectorInDomain(-mScrollPostPosition.y, -positionTransformed.y, rulerDomainY.min, rulerDomainY.max, verticalBias);
1652 positionTransformed.y = mScrollPostPosition.y + -dir;
1656 // note we have two separate animations for X & Y, this deals with sliding diagonally and hitting
1657 // a horizonal/vertical wall.delay
1658 mSnapXAnimation.AnimateTo( Property(self, mPropertyX), positionTransformed.x, alpha, TimePeriod(0.0f, positionDuration.x));
1659 mSnapYAnimation.AnimateTo( Property(self, mPropertyY), positionTransformed.y, alpha, TimePeriod(0.0f, positionDuration.y));
1662 // Scale Delta ///////////////////////////////////////////////////////
1665 // TODO: for non-uniform scaling to different bounds e.g. scaling a square to a 4:3 aspect ratio screen with a velocity
1666 // the height will hit first, and then the width, so that would require two different animation times just like position.
1667 mSnapAnimation.AnimateTo( Property(self, mPropertyScale), scale, alpha, TimePeriod(0.0f, scaleDuration.x));
1670 mSnapAnimation.AnimateTo( Property(self, mPropertyTime), totalDuration, AlphaFunctions::Linear );
1672 mSnapAnimation.Play();
1673 mSnapXAnimation.Play();
1674 mSnapYAnimation.Play();
1675 StartRefreshTimer();
1676 } // end if(totalDuration > Math::MACHINE_EPSILON_1)
1677 else // totalDuration == 0
1679 // instantly set transform.
1682 self.SetProperty(mPropertyX, positionTransformed.x);
1683 self.SetProperty(mPropertyY, positionTransformed.y);
1685 mScrollPrePosition = mScrollPostPosition = positionTransformed;
1690 self.SetProperty(mPropertyScale, scale);
1692 mScrollPreScale = mScrollPostScale = scale;
1696 // Always send a snap event when AnimateTo is called.
1697 Toolkit::ScrollView::SnapEvent snapEvent;
1698 snapEvent.type = snapType;
1699 snapEvent.position = positionTransformed;
1700 snapEvent.scale = scale;
1701 snapEvent.rotation = rotation;
1702 snapEvent.duration = totalDuration;
1704 mSnapStartedSignalV2.Emit( snapEvent );
1706 return startAnimation;
1709 void ScrollView::SetOvershootEnabled(bool enabled)
1711 if(enabled && !mOvershootIndicator)
1713 mOvershootIndicator = ScrollOvershootIndicator::New(*this);
1715 mOvershootIndicator->Enable(enabled);
1718 void ScrollView::AddOverlay(Actor actor)
1720 mInternalActor.Add( actor );
1723 void ScrollView::RemoveOverlay(Actor actor)
1725 mInternalActor.Remove( actor );
1728 void ScrollView::SetScrollingDirection( Radian direction, Radian threshold )
1730 PanGestureDetector panGesture( GetPanGestureDetector() );
1732 // First remove just in case we have some set, then add.
1733 panGesture.RemoveDirection( direction );
1734 panGesture.AddDirection( direction, threshold );
1737 void ScrollView::RemoveScrollingDirection( Radian direction )
1739 PanGestureDetector panGesture( GetPanGestureDetector() );
1740 panGesture.RemoveDirection( direction );
1743 Toolkit::ScrollView::SnapStartedSignalV2& ScrollView::SnapStartedSignal()
1745 return mSnapStartedSignalV2;
1748 void ScrollView::FindAndUnbindActor(Actor child)
1753 Vector3 ScrollView::GetPropertyPrePosition() const
1755 Vector3 position(Self().GetProperty<float>(mPropertyX), Self().GetProperty<float>(mPropertyY), 0.0f);
1756 WrapPosition(position);
1761 Vector3 ScrollView::GetPropertyPosition() const
1763 Vector3 position = Self().GetProperty<Vector3>(mPropertyPosition);
1764 WrapPosition(position);
1769 Vector3 ScrollView::GetPropertyScale() const
1771 return Self().GetProperty<Vector3>(mPropertyScale);
1774 void ScrollView::HandleStoppedAnimation()
1776 // Animation has stopped, so stop sending the scroll-update signal.
1777 CancelRefreshTimer();
1779 // cement transform now, and allow interactivity to resume.
1780 mScrollPostPosition = GetPropertyPosition();
1782 mScrollPostScale = GetPropertyScale();
1784 // Update Actor position with this wrapped value.
1786 Self().SetProperty(mPropertyX, mScrollPostPosition.x);
1787 Self().SetProperty(mPropertyY, mScrollPostPosition.y);
1790 mScrollPrePosition = mScrollPostPosition;
1791 mScrollPreScale = mScrollPostScale;
1792 mScrollPreRotation = mScrollPostRotation;
1795 void ScrollView::HandleSnapAnimationFinished()
1797 // Emit Signal that scrolling has completed.
1799 Self().SetProperty(mPropertyScrolling, false);
1801 Vector3 deltaPosition(Self().GetProperty<float>(mPropertyX),
1802 Self().GetProperty<float>(mPropertyY),
1805 Vector3 currentScrollPosition = GetCurrentScrollPosition();
1806 mScrollCompletedSignalV2.Emit( currentScrollPosition );
1808 mDomainOffset += deltaPosition - mScrollPostPosition;
1809 Self().SetProperty(mPropertyDomainOffset, mDomainOffset);
1810 HandleStoppedAnimation();
1813 bool ScrollView::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
1815 Dali::BaseHandle handle( object );
1817 bool connected( true );
1818 Toolkit::ScrollView view = Toolkit::ScrollView::DownCast( handle );
1820 if( Toolkit::ScrollView::SIGNAL_SNAP_STARTED == signalName )
1822 view.SnapStartedSignal().Connect( tracker, functor );
1826 // signalName does not match any signal
1833 void ScrollView::OnSizeAnimation(Animation& animation, const Vector3& targetSize)
1835 // need to update domain properties for new size
1836 UpdatePropertyDomain(targetSize);
1839 void ScrollView::OnControlSizeSet( const Vector3& size )
1841 // need to update domain properties for new size
1842 if( mDefaultMaxOvershoot )
1844 mMaxOvershoot.x = size.x * 0.5f;
1845 mMaxOvershoot.y = size.y * 0.5f;
1847 UpdatePropertyDomain(size);
1848 UpdateMainInternalConstraint();
1849 if( IsScrollComponentEnabled(Toolkit::Scrollable::OvershootIndicator) )
1851 mOvershootIndicator->Reset();
1855 void ScrollView::OnChildAdd(Actor& child)
1863 void ScrollView::OnChildRemove(Actor& child)
1865 // TODO: Actor needs a RemoveConstraint method to take out an individual constraint.
1869 bool ScrollView::OnTouchEvent(const TouchEvent& event)
1873 // Ignore this touch event, if scrollview is insensitive.
1877 // Ignore events with multiple-touch points
1878 if (event.GetPointCount() != 1)
1883 if (event.GetPoint(0).state == TouchPoint::Down)
1885 mTouchDownTime = event.time;
1886 mTouchDownReceived = true;
1887 mTouchDownPosition = event.GetPoint(0).local;
1889 if( mSnapAnimation || mSnapXAnimation || mSnapYAnimation || mSnapOvershootAnimation )
1891 mScrollInterrupted = true;
1895 if(mScrolling) // are we interrupting a current scroll?
1897 // reset domain offset as scrolling from original plane.
1898 mDomainOffset = Vector3::ZERO;
1899 Self().SetProperty(mPropertyDomainOffset, Vector3::ZERO);
1902 Vector3 currentScrollPosition = GetCurrentScrollPosition();
1903 mScrollCompletedSignalV2.Emit( currentScrollPosition );
1906 else if(event.GetPoint(0).state == TouchPoint::Up)
1908 // if the user touches and releases without enough movement to go
1909 // into a gesture state, then we should snap to nearest point.
1910 // otherwise our scroll could be stopped (interrupted) half way through an animation.
1911 if(mGestureStackDepth==0 && mTouchDownReceived)
1913 unsigned timeDelta( event.time - mTouchDownTime );
1914 if ( timeDelta >= MINIMUM_TIME_BETWEEN_DOWN_AND_UP_FOR_RESET )
1916 // Reset the velocity only if down was received a while ago
1917 mLastVelocity = Vector2( 0.0f, 0.0f );
1921 Vector2 positionDelta( mTouchDownPosition - event.GetPoint(0).local );
1922 mLastVelocity = positionDelta / timeDelta;
1925 // Only finish the transform if scrolling was interrupted on down or if we are scrolling
1926 if ( mSnapAnimation || mSnapXAnimation || mSnapYAnimation || mSnapOvershootAnimation || mScrollInterrupted || mScrolling )
1931 mTouchDownReceived = false;
1932 mScrollInterrupted = false;
1935 return true; // consume since we're potentially scrolling
1938 bool ScrollView::OnMouseWheelEvent(const MouseWheelEvent& event)
1942 // Ignore this mouse wheel event, if scrollview is insensitive.
1946 Vector3 targetScrollPosition = GetPropertyPosition();
1948 if(mRulerX->IsEnabled() && !mRulerY->IsEnabled())
1950 // If only the ruler in the X axis is enabled, scroll in the X axis.
1951 if(mRulerX->GetType() == Ruler::Free)
1953 // Free panning mode
1954 targetScrollPosition.x -= event.z * mMouseWheelScrollDistanceStep.x;
1955 ClampPosition(targetScrollPosition);
1956 ScrollTo(-targetScrollPosition);
1958 else if(!mScrolling)
1960 // Snap mode, only respond to the event when the previous snap animation is finished.
1961 ScrollTo(GetCurrentPage() + event.z);
1966 // If the ruler in the Y axis is enabled, scroll in the Y axis.
1967 if(mRulerY->GetType() == Ruler::Free)
1969 // Free panning mode
1970 targetScrollPosition.y -= event.z * mMouseWheelScrollDistanceStep.y;
1971 ClampPosition(targetScrollPosition);
1972 ScrollTo(-targetScrollPosition);
1974 else if(!mScrolling)
1976 // Snap mode, only respond to the event when the previous snap animation is finished.
1977 ScrollTo(GetCurrentPage() + event.z * mRulerX->GetTotalPages());
1984 void ScrollView::OnSnapAnimationFinished( Animation& source )
1986 mSnapAnimation.FinishedSignal().Disconnect( this, &ScrollView::OnSnapAnimationFinished );
1987 mSnapAnimation = NULL;
1990 void ScrollView::OnSnapXAnimationFinished( Animation& source )
1992 // Guard against destruction during signal emission
1993 // Note that ScrollCompletedSignal is emitted from HandleSnapAnimationFinished()
1994 Toolkit::ScrollView handle( GetOwner() );
1996 if(!mSnapYAnimation)
1998 HandleSnapAnimationFinished();
2000 if(mScrollMainInternalOvershootXConstraint)
2002 Self().RemoveConstraint(mScrollMainInternalOvershootXConstraint);
2003 mScrollMainInternalOvershootXConstraint.Reset();
2004 mScrollMainInternalOvershootXConstraint = 0;
2006 mSnapXAnimation.FinishedSignal().Disconnect(this, &ScrollView::OnSnapXAnimationFinished);
2007 mSnapXAnimation.Reset();
2008 mSnapXAnimation = NULL;
2009 if( IsScrollComponentEnabled(Toolkit::Scrollable::OvershootIndicator) )
2011 // kick start animation to 0
2012 Self().SetProperty(mPropertyOvershootX, 0.0f);
2016 void ScrollView::OnSnapYAnimationFinished( Animation& source )
2018 // Guard against destruction during signal emission
2019 // Note that ScrollCompletedSignal is emitted from HandleSnapAnimationFinished()
2020 Toolkit::ScrollView handle( GetOwner() );
2022 if(!mSnapXAnimation)
2024 HandleSnapAnimationFinished();
2026 if(mScrollMainInternalOvershootYConstraint)
2028 Self().RemoveConstraint(mScrollMainInternalOvershootYConstraint);
2029 mScrollMainInternalOvershootYConstraint.Reset();
2030 mScrollMainInternalOvershootYConstraint = 0;
2032 mSnapYAnimation.FinishedSignal().Disconnect(this, &ScrollView::OnSnapYAnimationFinished);
2033 mSnapYAnimation.Reset();
2034 mSnapYAnimation = NULL;
2035 if( IsScrollComponentEnabled(Toolkit::Scrollable::OvershootIndicator) )
2037 // kick start animation to 0
2038 Self().SetProperty(mPropertyOvershootY, 0.0f);
2042 void ScrollView::GestureStarted()
2044 // we handle the first gesture.
2045 // if we're currently doing a gesture and receive another
2046 // we continue and combine the effects of the gesture instead of reseting.
2047 if(mGestureStackDepth++==0)
2050 mPanDelta = Vector3::ZERO;
2051 mScaleDelta = Vector3::ONE;
2052 mRotationDelta = 0.0f;
2053 mLastVelocity = Vector2(0.0f, 0.0f);
2054 mLockAxis = LockPossible;
2056 if(mScrolling) // are we interrupting a current scroll?
2058 // set mScrolling to false, in case user has code that interrogates mScrolling Getter() in complete.
2060 Vector3 currentScrollPosition = GetCurrentScrollPosition();
2061 mScrollCompletedSignalV2.Emit( currentScrollPosition );
2066 void ScrollView::GestureContinuing(Vector2 panDelta, Vector2 scaleDelta, float rotationDelta)
2068 mPanDelta.x+= panDelta.x;
2069 mPanDelta.y+= panDelta.y;
2070 mScaleDelta.x*= scaleDelta.x;
2071 mScaleDelta.y*= scaleDelta.y;
2072 mRotationDelta+= rotationDelta;
2074 // Save the velocity, there is a bug in PanGesture
2075 // Whereby the Gesture::Finished's velocity is either:
2076 // NaN (due to time delta of zero between the last two events)
2077 // or 0 (due to position being the same between the last two events)
2079 // Axis Auto Lock - locks the panning to the horizontal or vertical axis if the pan
2080 // appears mostly horizontal or mostly vertical respectively.
2083 if(mPanDelta.LengthSquared() > AUTOLOCK_AXIS_MINIMUM_DISTANCE2 &&
2084 mLockAxis == LockPossible)
2086 float dx = fabsf(mPanDelta.x);
2087 float dy = fabsf(mPanDelta.y);
2088 if(dx * mAxisAutoLockGradient >= dy)
2090 // 0.36:1 gradient to the horizontal (deviate < 20 degrees)
2091 mLockAxis = LockVertical;
2093 else if(dy * mAxisAutoLockGradient > dx)
2095 // 0.36:1 gradient to the vertical (deviate < 20 degrees)
2096 mLockAxis = LockHorizontal;
2100 mLockAxis = LockNone;
2103 } // end if mAxisAutoLock
2106 // TODO: Upgrade to use a more powerful gesture detector (one that supports multiple touches on pan - so works as pan and flick gesture)
2107 // TODO: Reimplement Scaling (pinching 2+ points)
2108 // TODO: Reimplment Rotation (pinching 2+ points)
2109 // BUG: Gesture::Finished doesn't always return velocity on release (due to
2110 // timeDelta between last two events being 0 sometimes, or posiiton being the same)
2111 void ScrollView::OnPan(PanGesture gesture)
2113 // Guard against destruction during signal emission
2114 // Note that Emit() methods are called indirectly e.g. from within ScrollView::OnGestureEx()
2115 Actor self( Self() );
2119 // If another callback on the same original signal disables sensitivity,
2120 // this callback will still be called, so we must suppress it.
2124 // translate Gesture input to get useful data...
2125 switch(gesture.state)
2127 case Gesture::Started:
2130 self.SetProperty( mPropertyPanning, true );
2131 self.SetProperty( mPropertyScrollStartPagePosition, GetCurrentScrollPosition() );
2133 // Update property: X & Y = Position (only when in panning mode - in snapping mode, X & Y are animated).
2134 Constraint constraint = Constraint::New<float>( mPropertyX,
2135 LocalSource( mPropertyPosition ),
2136 Source( self, mPropertyPanning ),
2137 InternalXConstraint );
2138 mScrollMainInternalXConstraint = self.ApplyConstraint(constraint);
2140 constraint = Constraint::New<float>( mPropertyY,
2141 LocalSource( mPropertyPosition ),
2142 Source( self, mPropertyPanning ),
2143 InternalYConstraint );
2144 mScrollMainInternalYConstraint = self.ApplyConstraint(constraint);
2145 // When panning we want to make sure overshoot values are affected by pre position and post position
2146 SetOvershootConstraintsEnabled(true);
2150 case Gesture::Continuing:
2152 // Nothing to do, handled in constraint.
2156 case Gesture::Finished:
2157 case Gesture::Cancelled:
2159 mLastVelocity = gesture.velocity;
2160 self.SetProperty( mPropertyPanning, false );
2162 // Remove X & Y position constraints as they are not required when we are not panning.
2163 self.RemoveConstraint(mScrollMainInternalXConstraint);
2164 self.RemoveConstraint(mScrollMainInternalYConstraint);
2168 case Gesture::Possible:
2169 case Gesture::Clear:
2171 // Nothing to do, not needed.
2175 } // end switch(gesture.state)
2177 OnGestureEx(gesture.state);
2180 void ScrollView::OnPinch(PinchGesture gesture)
2182 // TODO: Reintroduce the pinch functionality for scaling.
2185 void ScrollView::OnGestureEx(Gesture::State state)
2187 // call necessary signals for application developer
2189 if(state == Gesture::Started)
2191 Vector3 currentScrollPosition = GetCurrentScrollPosition();
2192 Self().SetProperty(mPropertyScrolling, true);
2194 mScrollStartedSignalV2.Emit( currentScrollPosition );
2196 else if( (state == Gesture::Finished) ||
2197 (state == Gesture::Cancelled) ) // Finished/default
2199 // when all the gestures have finished, we finish the transform.
2200 // so if a user decides to pan (1 gesture), and then pan+zoom (2 gestures)
2201 // then stop panning (back to 1 gesture), and then stop zooming (0 gestures).
2202 // this is the point we end, and perform necessary snapping.
2203 mGestureStackDepth--;
2204 if(mGestureStackDepth==0)
2211 void ScrollView::UpdateTransform()
2213 // TODO: notify clamps using property notifications (or see if we need this, can deprecate it)
2216 void ScrollView::FinishTransform()
2218 const Vector3& scrollPosition = Self().GetProperty<Vector3>(mPropertyPosition);
2220 mScrollPostPosition.x = scrollPosition.x;
2221 mScrollPostPosition.y = scrollPosition.y;
2223 Vector3 deltaPosition(mScrollPostPosition);
2224 // Cement PRE transform (PRE = POST), and Begin Snap Animation if necessary.
2225 WrapPosition(mScrollPostPosition);
2227 mDomainOffset += deltaPosition - mScrollPostPosition;
2228 Self().SetProperty(mPropertyDomainOffset, mDomainOffset);
2230 bool animating = SnapWithVelocity(mLastVelocity * 1000.0f);
2234 AnimateOvershootToOrigin(0.0f, 0.0f);
2235 // if not animating, then this pan has completed right now.
2237 Self().SetProperty(mPropertyScrolling, false);
2238 Vector3 currentScrollPosition = GetCurrentScrollPosition();
2239 mScrollCompletedSignalV2.Emit( currentScrollPosition );
2243 Vector3 ScrollView::GetOvershoot(Vector3& position) const
2245 Vector3 size = Self().GetCurrentSize();
2248 const RulerDomain rulerDomainX = mRulerX->GetDomain();
2249 const RulerDomain rulerDomainY = mRulerY->GetDomain();
2251 if(mRulerX->IsEnabled() && rulerDomainX.enabled)
2253 const float left = rulerDomainX.min - position.x;
2254 const float right = size.width - rulerDomainX.max - position.x;
2261 overshoot.x = right;
2265 if(mRulerY->IsEnabled() && rulerDomainY.enabled)
2267 const float top = rulerDomainY.min - position.y;
2268 const float bottom = size.height - rulerDomainY.max - position.y;
2275 overshoot.y = bottom;
2282 bool ScrollView::OnAccessibilityPan(PanGesture gesture)
2288 void ScrollView::ClampPosition(Vector3& position) const
2290 ClampState3 clamped;
2291 ClampPosition(position, clamped);
2294 void ScrollView::ClampPosition(Vector3& position, ClampState3 &clamped) const
2296 Vector3 size = Self().GetCurrentSize();
2298 // determine size of viewport relative to current scaled size.
2299 // e.g. if you're zoomed in 200%, then each pixel on screen is only 0.5 pixels on subject.
2300 if(fabsf(mScrollPostScale.x) > Math::MACHINE_EPSILON_0)
2302 size.x /= mScrollPostScale.x;
2305 if(fabsf(mScrollPostScale.y) > Math::MACHINE_EPSILON_0)
2307 size.y /= mScrollPostScale.y;
2310 position.x = -mRulerX->Clamp(-position.x, size.width, 1.0f, clamped.x); // NOTE: X & Y rulers think in -ve coordinate system.
2311 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.
2313 clamped.z = NotClamped;
2316 void ScrollView::WrapPosition(Vector3& position) const
2320 const RulerDomain rulerDomainX = mRulerX->GetDomain();
2321 const RulerDomain rulerDomainY = mRulerY->GetDomain();
2323 if(mRulerX->IsEnabled())
2325 position.x = -WrapInDomain(-position.x, rulerDomainX.min, rulerDomainX.max);
2328 if(mRulerY->IsEnabled())
2330 position.y = -WrapInDomain(-position.y, rulerDomainY.min, rulerDomainY.max);
2335 void ScrollView::ClampScale(Vector3& scale) const
2337 ClampState3 clamped;
2338 ClampScale(scale, clamped);
2341 void ScrollView::ClampScale(Vector3& scale, ClampState3 &clamped) const
2343 scale.x = mRulerScaleX->Clamp(scale.x, 0.0f, 1.0f, clamped.x);
2344 scale.y = mRulerScaleY->Clamp(scale.y, 0.0f, 1.0f, clamped.y);
2345 clamped.z = NotClamped;
2348 void ScrollView::UpdateMainInternalConstraint()
2350 // TODO: Only update the constraints which have changed, rather than remove all and add all again.
2351 // Requires a dali-core ApplyConstraintAt, or a ReplaceConstraint. The former is probably more flexible.
2352 Actor self = Self();
2353 PanGestureDetector detector( GetPanGestureDetector() );
2355 if(mScrollMainInternalPrePositionConstraint)
2357 self.RemoveConstraint(mScrollMainInternalPrePositionConstraint);
2358 self.RemoveConstraint(mScrollMainInternalPositionConstraint);
2359 self.RemoveConstraint(mScrollMainInternalDeltaConstraint);
2360 self.RemoveConstraint(mScrollMainInternalFinalConstraint);
2361 self.RemoveConstraint(mScrollMainInternalRelativeConstraint);
2364 // TODO: It's probably better to use a local displacement value as this will give a displacement when scrolling just commences
2365 // but we need to make sure than the gesture system gives displacement since last frame (60Hz), not displacement since last touch event (90Hz).
2367 // 1. First calculate the pre-position (this is the scroll position if no clamping has taken place)
2368 Vector2 initialPanMask = Vector2(mRulerX->IsEnabled() ? 1.0f : 0.0f, mRulerY->IsEnabled() ? 1.0f : 0.0f);
2370 Constraint constraint = Constraint::New<Vector3>( mPropertyPrePosition,
2371 Source( detector, PanGestureDetector::LOCAL_POSITION ),
2372 Source( detector, PanGestureDetector::LOCAL_DISPLACEMENT ),
2373 LocalSource( mPropertyX ),
2374 LocalSource( mPropertyY ),
2375 Source( self, mPropertyPanning ),
2376 InternalPrePositionConstraint( initialPanMask, mAxisAutoLock, mAxisAutoLockGradient ) );
2377 mScrollMainInternalPrePositionConstraint = self.ApplyConstraint(constraint);
2379 // 2. Second calculate the clamped position (actual position)
2380 constraint = Constraint::New<Vector3>( mPropertyPosition,
2381 LocalSource( mPropertyPrePosition ),
2382 Source( self, Actor::SIZE ),
2383 InternalPositionConstraint( mRulerX->GetDomain(),
2384 mRulerY->GetDomain()) );
2385 mScrollMainInternalPositionConstraint = self.ApplyConstraint(constraint);
2387 constraint = Constraint::New<Vector3>( mPropertyPositionDelta,
2388 LocalSource( mPropertyPosition ),
2389 LocalSource( mPropertyDomainOffset ),
2390 InternalPositionDeltaConstraint );
2391 mScrollMainInternalDeltaConstraint = self.ApplyConstraint(constraint);
2393 constraint = Constraint::New<Vector3>( mPropertyFinal,
2394 LocalSource( mPropertyPosition ),
2395 LocalSource( mPropertyOvershootX ),
2396 LocalSource( mPropertyOvershootY ),
2397 InternalFinalConstraint( FinalDefaultAlphaFunction,
2398 FinalDefaultAlphaFunction ) );
2399 mScrollMainInternalFinalConstraint = self.ApplyConstraint(constraint);
2401 constraint = Constraint::New<Vector3>( mPropertyRelativePosition,
2402 LocalSource( mPropertyPosition ),
2403 LocalSource( mPropertyPositionMin ),
2404 LocalSource( mPropertyPositionMax ),
2405 LocalSource( Actor::SIZE ),
2406 InternalRelativePositionConstraint );
2407 mScrollMainInternalRelativeConstraint = self.ApplyConstraint(constraint);
2409 if(mScrollMainInternalOvershootXConstraint)
2411 // reset these constraints in correct order
2412 self.RemoveConstraint(mScrollMainInternalOvershootXConstraint);
2413 mScrollMainInternalOvershootXConstraint.Reset();
2415 Constraint constraint = Constraint::New<float>( mPropertyOvershootX,
2416 LocalSource( mPropertyPrePosition ),
2417 LocalSource( mPropertyPosition ),
2418 OvershootXConstraint(mMaxOvershoot.x) );
2419 mScrollMainInternalOvershootXConstraint = self.ApplyConstraint(constraint);
2422 if(mScrollMainInternalOvershootYConstraint)
2424 // reset these constraints in correct order
2425 self.RemoveConstraint(mScrollMainInternalOvershootYConstraint);
2426 mScrollMainInternalOvershootYConstraint.Reset();
2428 Constraint constraint = Constraint::New<float>( mPropertyOvershootY,
2429 LocalSource( mPropertyPrePosition ),
2430 LocalSource( mPropertyPosition ),
2431 OvershootXConstraint(mMaxOvershoot.y) );
2432 mScrollMainInternalOvershootYConstraint = self.ApplyConstraint(constraint);
2436 void ScrollView::SetOvershootConstraintsEnabled(bool enabled)
2438 Actor self( Self() );
2439 // remove and reset, it may now be in wrong order with the main internal constraints
2440 if(mScrollMainInternalOvershootXConstraint)
2442 self.RemoveConstraint(mScrollMainInternalOvershootXConstraint);
2443 mScrollMainInternalOvershootXConstraint.Reset();
2445 if(mScrollMainInternalOvershootYConstraint)
2447 self.RemoveConstraint(mScrollMainInternalOvershootYConstraint);
2448 mScrollMainInternalOvershootYConstraint.Reset();
2452 Constraint constraint = Constraint::New<float>( mPropertyOvershootX,
2453 LocalSource( mPropertyPrePosition ),
2454 LocalSource( mPropertyPosition ),
2455 OvershootXConstraint(mMaxOvershoot.x) );
2456 mScrollMainInternalOvershootXConstraint = self.ApplyConstraint(constraint);
2457 constraint = Constraint::New<float>( mPropertyOvershootY,
2458 LocalSource( mPropertyPrePosition ),
2459 LocalSource( mPropertyPosition ),
2460 OvershootYConstraint(mMaxOvershoot.y) );
2461 mScrollMainInternalOvershootYConstraint = self.ApplyConstraint(constraint);
2465 void ScrollView::SetInternalConstraints()
2467 // Internal constraints (applied to target ScrollBase Actor itself) /////////
2468 UpdateMainInternalConstraint();
2470 // User definable constraints to apply to all child actors //////////////////
2471 Actor self = Self();
2473 // LocalSource - The Actors to be moved.
2474 // self - The ScrollView
2476 // Apply some default constraints to ScrollView.
2477 // Movement + Scaling + Wrap function
2479 Constraint constraint;
2481 // MoveScaledActor (scrolling/zooming)
2482 constraint = Constraint::New<Vector3>( Actor::POSITION,
2483 Source( self, mPropertyPosition ),
2484 Source( self, mPropertyScale ),
2485 MoveScaledActorConstraint );
2486 constraint.SetRemoveAction(Constraint::Discard);
2487 ApplyConstraintToBoundActors(constraint);
2489 // ScaleActor (scrolling/zooming)
2490 constraint = Constraint::New<Vector3>( Actor::SCALE,
2491 Source( self, mPropertyScale ),
2492 ScaleActorConstraint );
2493 constraint.SetRemoveAction(Constraint::Discard);
2494 ApplyConstraintToBoundActors(constraint);
2496 // WrapActor (wrap functionality)
2497 constraint = Constraint::New<Vector3>( Actor::POSITION,
2498 LocalSource( Actor::SCALE ),
2499 LocalSource( Actor::ANCHOR_POINT ),
2500 LocalSource( Actor::SIZE ),
2501 Source( self, mPropertyPositionMin ),
2502 Source( self, mPropertyPositionMax ),
2503 Source( self, mPropertyWrap ),
2504 WrapActorConstraint );
2505 constraint.SetRemoveAction(Constraint::Discard);
2506 ApplyConstraintToBoundActors(constraint);
2509 void ScrollView::SetOvershootToOrigin()
2511 // Clear Snap animation if exists.
2512 if(mSnapOvershootAnimation)
2514 mSnapOvershootAnimation.FinishedSignal().Disconnect(this, &ScrollView::OnSnapOvershootAnimationFinished);
2515 mSnapOvershootAnimation.Stop();
2516 mSnapOvershootAnimation.Clear();
2517 mSnapOvershootAnimation = NULL;
2519 SetOvershootConstraintsEnabled(false);
2520 Self().SetProperty(mPropertyOvershootX, 0.0f);
2521 Self().SetProperty(mPropertyOvershootY, 0.0f);
2524 void ScrollView::AnimateOvershootToOrigin(float xDelay, float yDelay)
2526 if( IsScrollComponentEnabled(Toolkit::Scrollable::OvershootIndicator) )
2528 if(xDelay < Math::MACHINE_EPSILON_1)
2530 // kick start animation to 0
2531 Self().SetProperty(mPropertyOvershootX, 0.0f);
2533 if(yDelay < Math::MACHINE_EPSILON_1)
2535 // kick start animation to 0
2536 Self().SetProperty(mPropertyOvershootY, 0.0f);
2540 // When we need to animate overshoot to 0
2541 if(mSnapOvershootDuration > Math::MACHINE_EPSILON_1)
2543 Actor self = Self();
2544 // Clear Snap animation if exists.
2545 if(mSnapOvershootAnimation)
2547 mSnapOvershootAnimation.FinishedSignal().Disconnect( this, &ScrollView::OnSnapOvershootAnimationFinished );
2548 mSnapOvershootAnimation.Stop();
2549 mSnapOvershootAnimation.Clear();
2550 mSnapOvershootAnimation = NULL;
2552 if(!mSnapXAnimation && mScrollMainInternalOvershootXConstraint)
2554 // need to remove the x overshoot constraint now or it will override animation to 0
2555 Self().RemoveConstraint(mScrollMainInternalOvershootXConstraint);
2556 mScrollMainInternalOvershootXConstraint.Reset();
2557 mScrollMainInternalOvershootXConstraint = 0;
2559 if(!mSnapYAnimation && mScrollMainInternalOvershootYConstraint)
2561 // need to remove the y overshoot constraint now or it will override animation to 0
2562 Self().RemoveConstraint(mScrollMainInternalOvershootYConstraint);
2563 mScrollMainInternalOvershootYConstraint.Reset();
2564 mScrollMainInternalOvershootYConstraint = 0;
2566 // setup the new overshoot to 0 animation
2567 float totalDuration = (xDelay > yDelay ? xDelay : yDelay) + mSnapOvershootDuration;
2568 mSnapOvershootAnimation = Animation::New(totalDuration);
2569 mSnapOvershootAnimation.FinishedSignal().Connect( this, &ScrollView::OnSnapOvershootAnimationFinished );
2571 mSnapOvershootAnimation.AnimateTo( Property(self, mPropertyOvershootX), 0.0f, mSnapOvershootAlphaFunction, TimePeriod(xDelay, mSnapOvershootDuration) );
2572 mSnapOvershootAnimation.AnimateTo( Property(self, mPropertyOvershootY), 0.0f, mSnapOvershootAlphaFunction, TimePeriod(yDelay, mSnapOvershootDuration) );
2574 mSnapOvershootAnimation.SetDuration(totalDuration);
2575 mSnapOvershootAnimation.Play();
2579 SetOvershootToOrigin();
2583 void ScrollView::OnSnapOvershootAnimationFinished( Animation& source )
2585 mSnapOvershootAnimation = NULL;
2588 void ScrollView::StartRefreshTimer()
2590 if(mRefreshIntervalMilliseconds > 0)
2594 mRefreshTimer = Timer::New( mRefreshIntervalMilliseconds );
2595 mRefreshTimer.TickSignal().Connect( this, &ScrollView::OnRefreshTick );
2598 if (!mRefreshTimer.IsRunning())
2600 mRefreshTimer.Start();
2605 void ScrollView::CancelRefreshTimer()
2609 mRefreshTimer.Stop();
2613 bool ScrollView::OnRefreshTick()
2615 // Guard against destruction during signal emission
2616 Toolkit::ScrollView handle( GetOwner() );
2618 Vector3 currentScrollPosition = GetCurrentScrollPosition();
2619 mScrollUpdatedSignalV2.Emit( currentScrollPosition );
2624 } // namespace Internal
2626 } // namespace Toolkit