2 * Copyright (c) 2014 Samsung Electronics Co., Ltd.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 #include <dali/public-api/events/mouse-wheel-event.h>
21 #include <dali-toolkit/public-api/controls/scrollable/scroll-view/scroll-view-constraints.h>
22 #include <dali-toolkit/public-api/controls/scrollable/scroll-component-impl.h>
23 #include <dali-toolkit/internal/controls/scrollable/scroll-view/scroll-view-impl.h>
24 #include <dali-toolkit/internal/controls/scrollable/scroll-view/scroll-view-effect-impl.h>
25 #include <dali-toolkit/internal/controls/scrollable/scroll-view/scroll-overshoot-indicator-impl.h>
26 #include <dali/integration-api/debug.h>
28 // TODO: Change to two class system:
29 // 1. DraggableActor (is an actor which can be dragged anywhere/scaled/rotated, can be set to range using the ruler)
30 // 2. ScrollView (contains a draggable actor that can a) be dragged in the negative X, and Y domain, b) has a hitArea for touches)
32 // TODO: Asymetrical scaling
33 // TODO: external components (page and status overlays).
35 // TODO: upgrade Vector2/3 to support returning Unit vectors, normals, & cross product (dot product is already provided)
42 const int DEFAULT_REFRESH_INTERVAL_MILLISECONDS = 50; ///< Refresh rate TODO: Animation should have an update signal (and see item-view-impl)
43 const float FLICK_SPEED_THRESHOLD = 500.0f; ///< Flick threshold in pixels/ms
44 const float FREE_FLICK_SPEED_THRESHOLD = 200.0f; ///< Free-Flick threshold in pixels/ms
45 const float AUTOLOCK_AXIS_MINIMUM_DISTANCE2 = 100.0f; ///< Auto-lock axis after minimum distance squared.
46 const float FLICK_ORTHO_ANGLE_RANGE = 60.0f; ///< degrees. (if >45, then supports diagonal flicking)
47 const unsigned int MAXIMUM_NUMBER_OF_VALUES = 5; ///< Number of values to use for weighted pan calculation.
48 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.
49 const unsigned long MINIMUM_TIME_BETWEEN_DOWN_AND_UP_FOR_RESET( 150u );
50 const float DEFAULT_OVERSHOOT_ANIMATION_DURATION = 0.35f; // time in seconds
51 const Vector2 OVERSCROLL_CLAMP(1.0f, 1.0f); // maximum overscroll allowed in pixels when overshoot indicator is being used
52 const float TOUCH_DOWN_TIMER_INTERVAL = 100.0f;
54 // predefined effect values
55 const Vector3 ANGLE_CAROUSEL_ROTATE(Math::PI * 0.5f, Math::PI * 0.5f, 0.0f);
56 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
57 const Vector2 ANGLE_CUSTOM_CUBE_SWING(-Math::PI * 0.45f, -Math::PI * 0.45f); ///< outer cube pages swing 90 degrees as they pan offscreen
58 const Vector2 ANGLE_SPIRAL_SWING_IN(Math::PI * 0.5f, Math::PI * 0.5f);
59 const Vector2 ANGLE_SPIRAL_SWING_OUT(Math::PI * 0.35f, Math::PI * 0.35f);
60 const Vector2 ANGLE_OUTER_CUBE_SWING(Math::PI * 0.5f, Math::PI * 0.5f); ///< outer cube pages swing 90 degrees as they pan offscreen
62 // Helpers ////////////////////////////////////////////////////////////////////////////////////////
64 // TODO: GetAngle for Vector2 can be moved.
65 // GetAngle for Vector3 needs to be measured against a normal/plane.
68 * @param[in] vector The 3D vector to be measured
69 * @return angle in radians from 0 to 2PI
71 float GetAngle(const Vector3& vector)
73 return atan2(vector.y, vector.x) + Math::PI;
77 * @param[in] vector The 2D vector to be measured
78 * @return angle in radians from 0 to 2PI
80 float GetAngle(const Vector2& vector)
82 return atan2(vector.y, vector.x) + Math::PI;
86 * Find the vector (distance) from (a) to (b)
87 * in domain (start) to (end)
88 * (\ / start) (\ / end)
91 * @note assumes both (a) and (b) are already with the domain
94 * @param[in] a the current point
95 * @param[in] b the target point
96 * @param[in] start the start of the domain
97 * @param[in] end the end of the domain
98 * @param[in] bias whether to only take the right direction or the left direction,
99 * or the shortest direction.
100 * @return the shortest direction and distance
102 float VectorInDomain(float a, float b, float start, float end, Dali::Toolkit::DirectionBias bias)
104 if(bias == Dali::Toolkit::DirectionBiasNone)
106 return ShortestDistanceInDomain( a, b, start, end );
109 float size = end-start;
115 if(bias == Dali::Toolkit::DirectionBiasRight) // going right, take the vector.
121 float aRight = a+size;
128 if(bias == Dali::Toolkit::DirectionBiasLeft) // going left, take the vector.
134 float aLeft = a-size;
141 * Returns the position of the anchor within actor
143 * @param actor The Actor
144 * @param anchor The Anchor point of interest.
145 * @return The position of the Anchor
147 Vector3 GetPositionOfAnchor(Actor &actor, const Vector3 &anchor)
149 Vector3 childPosition = actor.GetCurrentPosition();
150 Vector3 childAnchor = - actor.GetCurrentAnchorPoint() + anchor;
151 Vector3 childSize = actor.GetCurrentSize();
153 return childPosition + childAnchor * childSize;
156 // AlphaFunctions /////////////////////////////////////////////////////////////////////////////////
158 float FinalDefaultAlphaFunction(float offset)
160 return offset * 0.5f;
164 * ConstantDecelerationAlphaFunction
165 * Newtoninan distance for constant deceleration
166 * v = 1 - t, s = t - 1/2 t^2
167 * when t = 0, s = 0.0 (min distance)
168 * when t = 1, s = 0.5 (max distance)
169 * progress = s / (max-min) = 2t - t^2
171 * @param[in] offset The input progress
172 * @return The output progress
174 float ConstantDecelerationAlphaFunction(float progress)
176 return progress * 2.0f - progress * progress;
179 // Internal Constraints ///////////////////////////////////////////////////////////////////////////
182 * Internal Relative position Constraint
183 * Generates the relative position value of the scroll view
184 * based on the absolute position, and it's relation to the
185 * scroll domain. This is a value from 0.0f to 1.0f in each
186 * scroll position axis.
188 Vector3 InternalRelativePositionConstraint(const Vector3& current,
189 const PropertyInput& scrollPositionProperty,
190 const PropertyInput& scrollMinProperty,
191 const PropertyInput& scrollMaxProperty,
192 const PropertyInput& scrollSizeProperty)
194 Vector3 position = -scrollPositionProperty.GetVector3();
195 const Vector3& min = scrollMinProperty.GetVector3();
196 const Vector3& max = scrollMaxProperty.GetVector3();
197 const Vector3& size = scrollSizeProperty.GetVector3();
199 position.x = WrapInDomain(position.x, min.x, max.x);
200 position.y = WrapInDomain(position.y, min.y, max.y);
202 Vector3 relativePosition;
203 Vector3 domainSize = (max - min) - size;
205 relativePosition.x = domainSize.x > Math::MACHINE_EPSILON_1 ? fabsf((position.x - min.x) / domainSize.x) : 0.0f;
206 relativePosition.y = domainSize.y > Math::MACHINE_EPSILON_1 ? fabsf((position.y - min.y) / domainSize.y) : 0.0f;
208 return relativePosition;
211 } // unnamed namespace
226 * Returns whether to lock scrolling to a particular axis
228 * @param[in] panDelta Distance panned since gesture started
229 * @param[in] currentLockAxis The current lock axis value
230 * @param[in] lockGradient How quickly to lock to a particular axis
232 * @return The new axis lock state
234 ScrollView::LockAxis GetLockAxis(const Vector2& panDelta, ScrollView::LockAxis currentLockAxis, float lockGradient)
236 if(panDelta.LengthSquared() > AUTOLOCK_AXIS_MINIMUM_DISTANCE2 &&
237 currentLockAxis == ScrollView::LockPossible)
239 float dx = fabsf(panDelta.x);
240 float dy = fabsf(panDelta.y);
241 if(dx * lockGradient >= dy)
243 // 0.36:1 gradient to the horizontal (deviate < 20 degrees)
244 currentLockAxis = ScrollView::LockVertical;
246 else if(dy * lockGradient > dx)
248 // 0.36:1 gradient to the vertical (deviate < 20 degrees)
249 currentLockAxis = ScrollView::LockHorizontal;
253 currentLockAxis = ScrollView::LockNone;
256 return currentLockAxis;
260 * Internal Pre-Position Property Constraint.
262 * Generates position property based on current position + gesture displacement.
263 * Or generates position property based on positionX/Y.
264 * Note: This is the position prior to any clamping at scroll boundaries.
265 * TODO: Scale & Rotation Transforms.
267 struct InternalPrePositionConstraint
269 InternalPrePositionConstraint(const Vector2& initialPanMask,
271 float axisAutoLockGradient,
272 ScrollView::LockAxis initialLockAxis,
273 const Vector2& maxOvershoot,
274 const RulerDomain& domainX, const RulerDomain& domainY)
275 : mInitialPanMask(initialPanMask),
276 mDomainMin( -domainX.min, -domainY.min ),
277 mDomainMax( -domainX.max, -domainY.max ),
278 mMaxOvershoot(maxOvershoot),
279 mAxisAutoLockGradient(axisAutoLockGradient),
280 mLockAxis(initialLockAxis),
281 mAxisAutoLock(axisAutoLock),
283 mClampX( domainX.enabled ),
284 mClampY( domainY.enabled )
288 Vector3 operator()(const Vector3& current,
289 const PropertyInput& gesturePositionProperty,
290 const PropertyInput& gestureDisplacementProperty,
291 const PropertyInput& sizeProperty)
293 Vector3 scrollPostPosition = current;
294 Vector2 panPosition = gesturePositionProperty.GetVector2();
298 mLocalStart = gesturePositionProperty.GetVector2() - gestureDisplacementProperty.GetVector2();
299 mPrePosition = current;
300 mCurrentPanMask = mInitialPanMask;
304 // Calculate Deltas...
305 Vector2 currentPosition = gesturePositionProperty.GetVector2();
306 Vector2 panDelta( currentPosition - mLocalStart );
308 // Axis Auto Lock - locks the panning to the horizontal or vertical axis if the pan
309 // appears mostly horizontal or mostly vertical respectively...
312 mLockAxis = GetLockAxis(panDelta, mLockAxis, mAxisAutoLockGradient);
313 if( mLockAxis == ScrollView::LockVertical )
315 mCurrentPanMask.y = 0.0f;
317 else if( mLockAxis == ScrollView::LockHorizontal )
319 mCurrentPanMask.x = 0.0f;
323 // Restrict deltas based on ruler enable/disable and axis-lock state...
324 panDelta *= mCurrentPanMask;
326 // Perform Position transform based on input deltas...
327 scrollPostPosition = mPrePosition;
328 scrollPostPosition.GetVectorXY() += panDelta;
330 // if no wrapping then clamp preposition to maximum overshoot amount
331 const Vector3& size = sizeProperty.GetVector3();
334 float newXPosition = Clamp(scrollPostPosition.x, (mDomainMax.x + size.x) - mMaxOvershoot.x, mDomainMin.x + mMaxOvershoot.x );
335 if( (newXPosition < scrollPostPosition.x - Math::MACHINE_EPSILON_1)
336 || (newXPosition > scrollPostPosition.x + Math::MACHINE_EPSILON_1) )
338 mPrePosition.x = newXPosition;
339 mLocalStart.x = panPosition.x;
341 scrollPostPosition.x = newXPosition;
345 float newYPosition = Clamp(scrollPostPosition.y, (mDomainMax.y + size.y) - mMaxOvershoot.y, mDomainMin.y + mMaxOvershoot.y );
346 if( (newYPosition < scrollPostPosition.y - Math::MACHINE_EPSILON_1)
347 || (newYPosition > scrollPostPosition.y + Math::MACHINE_EPSILON_1) )
349 mPrePosition.y = newYPosition;
350 mLocalStart.y = panPosition.y;
352 scrollPostPosition.y = newYPosition;
355 return scrollPostPosition;
358 Vector3 mPrePosition;
360 Vector2 mInitialPanMask; ///< Initial pan mask (based on ruler settings)
361 Vector2 mCurrentPanMask; ///< Current pan mask that can be altered by axis lock mode.
364 Vector2 mMaxOvershoot;
366 float mAxisAutoLockGradient; ///< Set by ScrollView
367 ScrollView::LockAxis mLockAxis;
369 bool mAxisAutoLock:1; ///< Set by ScrollView
376 * Internal Position Property Constraint.
378 * Generates position property based on pre-position
379 * Note: This is the position after clamping.
380 * (uses result of InternalPrePositionConstraint)
382 struct InternalPositionConstraint
384 InternalPositionConstraint(const RulerDomain& domainX, const RulerDomain& domainY, bool wrap)
385 : mDomainMin( -domainX.min, -domainY.min ),
386 mDomainMax( -domainX.max, -domainY.max ),
387 mClampX( domainX.enabled ),
388 mClampY( domainY.enabled ),
393 Vector3 operator()(const Vector3& current,
394 const PropertyInput& scrollPositionProperty,
395 const PropertyInput& scrollMinProperty,
396 const PropertyInput& scrollMaxProperty,
397 const PropertyInput& scrollSizeProperty)
399 Vector3 position = scrollPositionProperty.GetVector3();
400 const Vector2& size = scrollSizeProperty.GetVector3().GetVectorXY();
401 const Vector3& min = scrollMinProperty.GetVector3();
402 const Vector3& max = scrollMaxProperty.GetVector3();
406 position.x = -WrapInDomain(-position.x, min.x, max.x);
407 position.y = -WrapInDomain(-position.y, min.y, max.y);
411 // clamp post position to domain
412 position.x = mClampX ? Clamp(position.x, mDomainMax.x + size.x, mDomainMin.x ) : position.x;
413 position.y = mClampY ? Clamp(position.y, mDomainMax.y + size.y, mDomainMin.y ) : position.y;
428 * This constraint updates the X overshoot property using the difference
429 * mPropertyPrePosition.x and mPropertyPosition.x, returning a relative value between 0.0f and 1.0f
431 struct OvershootXConstraint
433 OvershootXConstraint(float maxOvershoot) : mMaxOvershoot(maxOvershoot) {}
435 float operator()(const float& current,
436 const PropertyInput& scrollPrePositionProperty,
437 const PropertyInput& scrollPostPositionProperty,
438 const PropertyInput& canScrollProperty)
440 if( canScrollProperty.GetBoolean() )
442 const Vector3& scrollPrePosition = scrollPrePositionProperty.GetVector3();
443 const Vector3& scrollPostPosition = scrollPostPositionProperty.GetVector3();
444 float newOvershoot = scrollPrePosition.x - scrollPostPosition.x;
445 return (newOvershoot > 0.0f ? std::min(newOvershoot, mMaxOvershoot) : std::max(newOvershoot, -mMaxOvershoot)) / mMaxOvershoot;
454 * This constraint updates the Y overshoot property using the difference
455 * mPropertyPrePosition.y and mPropertyPosition.y, returning a relative value between 0.0f and 1.0f
457 struct OvershootYConstraint
459 OvershootYConstraint(float maxOvershoot) : mMaxOvershoot(maxOvershoot) {}
461 float operator()(const float& current,
462 const PropertyInput& scrollPrePositionProperty,
463 const PropertyInput& scrollPostPositionProperty,
464 const PropertyInput& canScrollProperty)
466 if( canScrollProperty.GetBoolean() )
468 const Vector3& scrollPrePosition = scrollPrePositionProperty.GetVector3();
469 const Vector3& scrollPostPosition = scrollPostPositionProperty.GetVector3();
470 float newOvershoot = scrollPrePosition.y - scrollPostPosition.y;
471 return (newOvershoot > 0.0f ? std::min(newOvershoot, mMaxOvershoot) : std::max(newOvershoot, -mMaxOvershoot)) / mMaxOvershoot;
480 * When panning, this constraint updates the X property, otherwise
481 * it has no effect on the X property.
483 float InternalXConstraint(const float& current,
484 const PropertyInput& scrollPosition)
486 return scrollPosition.GetVector3().x;
490 * When panning, this constraint updates the Y property, otherwise
491 * it has no effect on the Y property.
493 float InternalYConstraint(const float& current,
494 const PropertyInput& scrollPosition)
496 return scrollPosition.GetVector3().y;
500 * Internal Position-Delta Property Constraint.
502 * Generates position-delta property based on scroll-position + scroll-offset properties.
504 Vector3 InternalPositionDeltaConstraint(const Vector3& current,
505 const PropertyInput& scrollPositionProperty,
506 const PropertyInput& scrollOffsetProperty)
508 const Vector3& scrollPosition = scrollPositionProperty.GetVector3();
509 const Vector3& scrollOffset = scrollOffsetProperty.GetVector3();
511 return scrollPosition + scrollOffset;
515 * Internal Final Position Constraint
516 * The position of content is:
517 * of scroll-position + f(scroll-overshoot)
518 * where f(...) function defines how overshoot
519 * should affect final-position.
521 struct InternalFinalConstraint
523 InternalFinalConstraint(AlphaFunction functionX,
524 AlphaFunction functionY)
525 : mFunctionX(functionX),
526 mFunctionY(functionY)
530 Vector3 operator()(const Vector3& current,
531 const PropertyInput& scrollPositionProperty,
532 const PropertyInput& scrollOvershootXProperty,
533 const PropertyInput& scrollOvershootYProperty)
535 const float& overshootx = scrollOvershootXProperty.GetFloat();
536 const float& overshooty = scrollOvershootYProperty.GetFloat();
537 Vector3 offset( mFunctionX(overshootx),
538 mFunctionY(overshooty),
541 return scrollPositionProperty.GetVector3() - offset;
544 AlphaFunction mFunctionX;
545 AlphaFunction mFunctionY;
551 return Toolkit::ScrollView::New();
554 TypeRegistration typeRegistration( typeid(Toolkit::ScrollView), typeid(Toolkit::Scrollable), Create );
556 SignalConnectorType signalConnector1( typeRegistration, Toolkit::ScrollView::SIGNAL_SNAP_STARTED, &ScrollView::DoConnectSignal );
561 ///////////////////////////////////////////////////////////////////////////////////////////////////
563 ///////////////////////////////////////////////////////////////////////////////////////////////////
565 Dali::Toolkit::ScrollView ScrollView::New()
567 // Create the implementation
568 ScrollViewPtr scrollView(new ScrollView());
570 // Pass ownership to CustomActor via derived handle
571 Dali::Toolkit::ScrollView handle(*scrollView);
573 // Second-phase init of the implementation
574 // This can only be done after the CustomActor connection has been made...
575 scrollView->Initialize();
580 ScrollView::ScrollView()
583 mGestureStackDepth(0),
584 mRotationDelta(0.0f),
585 mScrollStateFlags(0),
586 mScrollPreRotation(0.0f),
587 mScrollPostRotation(0.0f),
588 mMinTouchesForPanning(1),
589 mMaxTouchesForPanning(1),
590 mLockAxis(LockPossible),
591 mRefreshIntervalMilliseconds(DEFAULT_REFRESH_INTERVAL_MILLISECONDS),
592 mOvershootDelay(1.0f),
593 mMaxOvershoot(Toolkit::ScrollView::DEFAULT_MAX_OVERSHOOT, Toolkit::ScrollView::DEFAULT_MAX_OVERSHOOT),
594 mUserMaxOvershoot(Toolkit::ScrollView::DEFAULT_MAX_OVERSHOOT, Toolkit::ScrollView::DEFAULT_MAX_OVERSHOOT),
595 mSnapOvershootDuration(Toolkit::ScrollView::DEFAULT_SNAP_OVERSHOOT_DURATION),
596 mSnapOvershootAlphaFunction(AlphaFunctions::EaseOut),
597 mSnapDuration(Toolkit::ScrollView::DEFAULT_SLOW_SNAP_ANIMATION_DURATION),
598 mSnapAlphaFunction(AlphaFunctions::EaseOut),
599 mFlickDuration(Toolkit::ScrollView::DEFAULT_FAST_SNAP_ANIMATION_DURATION),
600 mFlickAlphaFunction(AlphaFunctions::EaseOut),
601 mAxisAutoLockGradient(Toolkit::ScrollView::DEFAULT_AXIS_AUTO_LOCK_GRADIENT),
602 mFrictionCoefficient(Toolkit::ScrollView::DEFAULT_FRICTION_COEFFICIENT),
603 mFlickSpeedCoefficient(Toolkit::ScrollView::DEFAULT_FLICK_SPEED_COEFFICIENT),
604 mMaxFlickSpeed(Toolkit::ScrollView::DEFAULT_MAX_FLICK_SPEED),
605 mInAccessibilityPan(false),
608 mScrollInterrupted(false),
611 mTouchDownTimeoutReached(false),
612 mActorAutoSnapEnabled(false),
613 mAutoResizeContainerEnabled(false),
615 mAxisAutoLock(false),
617 mDefaultMaxOvershoot(true)
619 SetRequiresMouseWheelEvents(true);
622 void ScrollView::OnInitialize()
626 // Internal Actor, used to hide actors from enumerations.
627 // Also actors added to Internal actor appear as overlays e.g. ScrollBar components.
628 mInternalActor = Actor::New();
629 mInternalActor.SetDrawMode(DrawMode::OVERLAY);
630 self.Add(mInternalActor);
631 mInternalActor.ApplyConstraint( Constraint::New<Vector3>( Actor::SIZE, ParentSource( Actor::SIZE ), EqualToConstraint() ) );
632 mInternalActor.SetParentOrigin(ParentOrigin::CENTER);
633 mInternalActor.SetAnchorPoint(AnchorPoint::CENTER);
637 // Register Scroll Properties.
638 RegisterProperties();
640 mScrollPostPosition = mScrollPrePosition = Vector3::ZERO;
641 mScrollPostScale = mScrollPreScale = Vector3::ONE;
642 mScrollPostRotation = mScrollPreRotation = 0.0f;
644 mMouseWheelScrollDistanceStep = Stage::GetCurrent().GetSize() * DEFAULT_MOUSE_WHEEL_SCROLL_DISTANCE_STEP_PROPORTION;
648 mGestureStackDepth = 0;
650 EnableGestureDetection( Gesture::Type( Gesture::Pan ) );
652 // For pan, default to only 1 touch required, ignoring touches outside this range.
653 SetTouchesRequiredForPanning(1, 1, false);
655 // By default we'll allow the user to freely drag the scroll view,
656 // while disabling the other rulers.
657 RulerPtr ruler = new DefaultRuler();
658 RulerPtr rulerDisabled = new DefaultRuler();
659 rulerDisabled->Disable();
662 mRulerScaleX = rulerDisabled;
663 mRulerScaleY = rulerDisabled;
664 mRulerRotation = rulerDisabled;
666 EnableScrollComponent(Toolkit::Scrollable::OvershootIndicator);
668 Vector3 size = GetControlSize();
669 UpdatePropertyDomain(size);
670 SetInternalConstraints();
673 void ScrollView::OnControlStageConnection()
677 SetScrollSensitive( false );
678 SetScrollSensitive( true );
680 if(IsScrollComponentEnabled(Toolkit::Scrollable::OvershootIndicator))
682 // try and make sure property notifications are set
683 EnableScrollComponent(Toolkit::Scrollable::OvershootIndicator);
687 void ScrollView::OnControlStageDisconnection()
692 ScrollView::~ScrollView()
696 AlphaFunction ScrollView::GetScrollSnapAlphaFunction() const
698 return mSnapAlphaFunction;
701 void ScrollView::SetScrollSnapAlphaFunction(AlphaFunction alpha)
703 mSnapAlphaFunction = alpha;
706 AlphaFunction ScrollView::GetScrollFlickAlphaFunction() const
708 return mFlickAlphaFunction;
711 void ScrollView::SetScrollFlickAlphaFunction(AlphaFunction alpha)
713 mFlickAlphaFunction = alpha;
716 float ScrollView::GetScrollSnapDuration() const
718 return mSnapDuration;
721 void ScrollView::SetScrollSnapDuration(float time)
723 mSnapDuration = time;
726 float ScrollView::GetScrollFlickDuration() const
728 return mFlickDuration;
731 void ScrollView::SetScrollFlickDuration(float time)
733 mFlickDuration = time;
736 void ScrollView::ApplyEffect(Toolkit::ScrollViewEffect effect)
738 Dali::Toolkit::ScrollView self = Dali::Toolkit::ScrollView::DownCast(Self());
740 // Assertion check to ensure effect doesn't already exist in this scrollview
741 bool effectAlreadyExistsInScrollView(false);
742 for (ScrollViewEffectIter iter = mEffects.begin(); iter != mEffects.end(); ++iter)
746 effectAlreadyExistsInScrollView = true;
751 DALI_ASSERT_ALWAYS(!effectAlreadyExistsInScrollView);
753 // add effect to effects list
754 mEffects.push_back(effect);
756 // invoke Attachment request to ScrollView first
757 GetImpl(effect).Attach(self);
760 Toolkit::ScrollViewEffect ScrollView::ApplyEffect(Toolkit::ScrollView::PageEffect effect)
762 Toolkit::ScrollViewEffect scrollEffect;
765 case Toolkit::ScrollView::PageEffectNone:
769 case Toolkit::ScrollView::PageEffectOuterCube:
771 Toolkit::ScrollViewCustomEffect customEffect;
772 scrollEffect = customEffect = Toolkit::ScrollViewCustomEffect::New();
773 Vector2 pageSize = Stage::GetCurrent().GetSize();
774 // 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
775 // 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)
776 // the page moving off screen will slowly build a spacing from 0.0f to 20.0f
777 // the spacing from each page is added together for the final spacing between the two pages.
778 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));
779 customEffect.SetSwingAngleOut(ANGLE_CUSTOM_CUBE_SWING.x, Vector3(0.0f, -1.0f, 0.0f));
780 customEffect.SetSwingAnchor(AnchorPoint::CENTER, AnchorPoint::CENTER_LEFT);
781 customEffect.SetOpacityThreshold(0.7f);
784 case Toolkit::ScrollView::PageEffectDepth:
786 Toolkit::ScrollViewCustomEffect customEffect;
787 scrollEffect = customEffect = Toolkit::ScrollViewCustomEffect::New();
790 case Toolkit::ScrollView::PageEffectInnerCube:
792 Toolkit::ScrollViewCustomEffect customEffect;
793 scrollEffect = customEffect = Toolkit::ScrollViewCustomEffect::New();
794 customEffect.SetPageSpacing(Vector2(30.0f, 30.0f));
795 customEffect.SetAngledOriginPageRotation(ANGLE_CUBE_PAGE_ROTATE);
796 customEffect.SetSwingAngle(ANGLE_CUBE_PAGE_ROTATE.x, Vector3(0,-1,0));
797 customEffect.SetOpacityThreshold(0.5f);
800 case Toolkit::ScrollView::PageEffectCarousel:
802 Toolkit::ScrollViewCustomEffect customEffect;
803 scrollEffect = customEffect = Toolkit::ScrollViewCustomEffect::New();
804 customEffect.SetPageTranslation(Vector3(0,0,0), Vector3(-30, 0, 0));
805 customEffect.SetPageSpacing(Vector2(60.0f, 60.0f));
806 customEffect.SetAngledOriginPageRotation(-ANGLE_CUBE_PAGE_ROTATE);
807 customEffect.SetOpacityThreshold(0.2f, 0.6f);
810 case Toolkit::ScrollView::PageEffectSpiral:
812 Toolkit::ScrollViewCustomEffect customEffect;
813 scrollEffect = customEffect = Toolkit::ScrollViewCustomEffect::New();
815 Vector2 pageSize = Stage::GetCurrent().GetSize();
816 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));
817 //customEffect.SetSwingAngleAlphaFunctionOut(AlphaFunctions::EaseOut);
818 customEffect.SetSwingAnchor(AnchorPoint::CENTER_RIGHT);
819 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);
820 //customEffect.SetPageTranslateAlphaFunctionOut(AlphaFunctions::EaseOut);
821 customEffect.SetOpacityThreshold(0.75f, 0.6f);
822 customEffect.SetOpacityAlphaFunctionIn(AlphaFunctions::EaseInOut);
827 DALI_ASSERT_DEBUG(0 && "unknown scroll view effect");
830 RemoveConstraintsFromChildren();
833 ApplyEffect(scrollEffect);
838 void ScrollView::RemoveEffect(Toolkit::ScrollViewEffect effect)
840 Dali::Toolkit::ScrollView self = Dali::Toolkit::ScrollView::DownCast(Self());
842 // remove effect from effects list
843 bool effectExistedInScrollView(false);
844 for (ScrollViewEffectIter iter = mEffects.begin(); iter != mEffects.end(); ++iter)
848 mEffects.erase(iter);
849 effectExistedInScrollView = true;
854 // Assertion check to ensure effect existed.
855 DALI_ASSERT_ALWAYS(effectExistedInScrollView);
857 // invoke Detachment request to ScrollView last
858 GetImpl(effect).Detach(self);
861 void ScrollView::RemoveAllEffects()
863 Dali::Toolkit::ScrollView self = Dali::Toolkit::ScrollView::DownCast(Self());
865 for (ScrollViewEffectIter effectIter = mEffects.begin(); effectIter != mEffects.end(); ++effectIter)
867 Toolkit::ScrollViewEffect effect = *effectIter;
869 // invoke Detachment request to ScrollView last
870 GetImpl(effect).Detach(self);
876 void ScrollView::ApplyConstraintToChildren(Constraint constraint)
878 ApplyConstraintToBoundActors(constraint);
881 void ScrollView::RemoveConstraintsFromChildren()
883 RemoveConstraintsFromBoundActors();
886 const RulerPtr ScrollView::GetRulerX() const
891 const RulerPtr ScrollView::GetRulerY() const
896 void ScrollView::SetRulerX(RulerPtr ruler)
900 Vector3 size = GetControlSize();
901 UpdatePropertyDomain(size);
902 UpdateMainInternalConstraint();
905 void ScrollView::SetRulerY(RulerPtr ruler)
909 Vector3 size = GetControlSize();
910 UpdatePropertyDomain(size);
911 UpdateMainInternalConstraint();
914 void ScrollView::UpdatePropertyDomain(const Vector3& size)
917 Vector3 min = self.GetProperty<Vector3>(mPropertyPositionMin);
918 Vector3 max = self.GetProperty<Vector3>(mPropertyPositionMax);
919 bool scrollPositionChanged = false;
920 bool domainChanged = false;
922 bool canScrollVertical = false;
923 bool canScrollHorizontal = false;
924 UpdateLocalScrollProperties();
925 if(mRulerX->IsEnabled())
927 const Toolkit::RulerDomain& rulerDomain = mRulerX->GetDomain();
928 if( fabsf(min.x - rulerDomain.min) > Math::MACHINE_EPSILON_10000
929 || fabsf(max.x - rulerDomain.max) > Math::MACHINE_EPSILON_10000 )
931 domainChanged = true;
932 min.x = rulerDomain.min;
933 max.x = rulerDomain.max;
935 // make sure new scroll value is within new domain
936 if( mScrollPrePosition.x < min.x
937 || mScrollPrePosition.x > max.x )
939 scrollPositionChanged = true;
940 mScrollPrePosition.x = Clamp(mScrollPrePosition.x, -(max.x - size.x), -min.x);
943 if( (fabsf(rulerDomain.max - rulerDomain.min) - size.x) > Math::MACHINE_EPSILON_10000 )
945 canScrollHorizontal = true;
949 if(mRulerY->IsEnabled())
951 const Toolkit::RulerDomain& rulerDomain = mRulerY->GetDomain();
952 if( fabsf(min.y - rulerDomain.min) > Math::MACHINE_EPSILON_10000
953 || fabsf(max.y - rulerDomain.max) > Math::MACHINE_EPSILON_10000 )
955 domainChanged = true;
956 min.y = rulerDomain.min;
957 max.y = rulerDomain.max;
959 // make sure new scroll value is within new domain
960 if( mScrollPrePosition.y < min.y
961 || mScrollPrePosition.y > max.y )
963 scrollPositionChanged = true;
964 mScrollPrePosition.y = Clamp(mScrollPrePosition.y, -(max.y - size.y), -min.y);
967 if( (fabsf(rulerDomain.max - rulerDomain.min) - size.y) > Math::MACHINE_EPSILON_10000 )
969 canScrollVertical = true;
972 // avoid setting properties if possible, otherwise this will cause an entire update as well as triggering constraints using each property we update
973 if( self.GetProperty<bool>(mPropertyCanScrollVertical) != canScrollVertical )
975 self.SetProperty(mPropertyCanScrollVertical, canScrollVertical);
977 if( self.GetProperty<bool>(mPropertyCanScrollHorizontal) != canScrollHorizontal )
979 self.SetProperty(mPropertyCanScrollHorizontal, canScrollHorizontal);
981 if( scrollPositionChanged )
983 self.SetProperty(mPropertyPrePosition, mScrollPrePosition);
987 self.SetProperty(mPropertyPositionMin, min );
988 self.SetProperty(mPropertyPositionMax, max );
992 void ScrollView::SetRulerScaleX(RulerPtr ruler)
994 mRulerScaleX = ruler;
995 UpdateMainInternalConstraint();
998 void ScrollView::SetRulerScaleY(RulerPtr ruler)
1000 mRulerScaleY = ruler;
1001 UpdateMainInternalConstraint();
1004 void ScrollView::SetRulerRotation(RulerPtr ruler)
1006 mRulerRotation = ruler;
1007 UpdateMainInternalConstraint();
1010 void ScrollView::SetScrollSensitive(bool sensitive)
1012 Actor self = Self();
1013 PanGestureDetector panGesture( GetPanGestureDetector() );
1015 if((!mSensitive) && (sensitive))
1017 mSensitive = sensitive;
1018 panGesture.Attach(self);
1020 else if((mSensitive) && (!sensitive))
1022 // while the scroll view is panning, the state needs to be reset.
1023 bool isPanning = self.GetProperty<bool>( mPropertyPanning );
1026 PanGesture cancelGesture( Gesture::Cancelled );
1027 OnPan( cancelGesture );
1030 panGesture.Detach(self);
1031 mSensitive = sensitive;
1033 mGestureStackDepth = 0;
1037 void ScrollView::SetMaxOvershoot(float overshootX, float overshootY)
1039 mMaxOvershoot.x = overshootX;
1040 mMaxOvershoot.y = overshootY;
1041 mUserMaxOvershoot = mMaxOvershoot;
1042 mDefaultMaxOvershoot = false;
1043 UpdateMainInternalConstraint();
1046 void ScrollView::SetSnapOvershootAlphaFunction(AlphaFunction alpha)
1048 mSnapOvershootAlphaFunction = alpha;
1051 void ScrollView::SetSnapOvershootDuration(float duration)
1053 mSnapOvershootDuration = duration;
1056 void ScrollView::SetTouchesRequiredForPanning(unsigned int minTouches, unsigned int maxTouches, bool endOutside)
1058 PanGestureDetector panGesture( GetPanGestureDetector() );
1060 mMinTouchesForPanning = minTouches;
1061 mMaxTouchesForPanning = maxTouches;
1065 panGesture.SetMinimumTouchesRequired(minTouches);
1066 panGesture.SetMaximumTouchesRequired(maxTouches);
1070 panGesture.SetMinimumTouchesRequired(1);
1071 panGesture.SetMaximumTouchesRequired(UINT_MAX);
1075 void ScrollView::SetActorAutoSnap(bool enable)
1077 mActorAutoSnapEnabled = enable;
1080 void ScrollView::SetAutoResize(bool enable)
1082 mAutoResizeContainerEnabled = enable;
1083 // TODO: This needs a lot of issues to be addressed before working.
1086 bool ScrollView::GetWrapMode() const
1091 void ScrollView::SetWrapMode(bool enable)
1094 Self().SetProperty(mPropertyWrap, enable);
1097 int ScrollView::GetRefreshInterval() const
1099 return mRefreshIntervalMilliseconds;
1102 void ScrollView::SetRefreshInterval(int milliseconds)
1104 mRefreshIntervalMilliseconds = milliseconds;
1107 bool ScrollView::GetAxisAutoLock() const
1109 return mAxisAutoLock;
1112 void ScrollView::SetAxisAutoLock(bool enable)
1114 mAxisAutoLock = enable;
1115 UpdateMainInternalConstraint();
1118 float ScrollView::GetAxisAutoLockGradient() const
1120 return mAxisAutoLockGradient;
1123 void ScrollView::SetAxisAutoLockGradient(float gradient)
1125 DALI_ASSERT_DEBUG( gradient >= 0.0f && gradient <= 1.0f );
1126 mAxisAutoLockGradient = gradient;
1127 UpdateMainInternalConstraint();
1130 float ScrollView::GetFrictionCoefficient() const
1132 return mFrictionCoefficient;
1135 void ScrollView::SetFrictionCoefficient(float friction)
1137 DALI_ASSERT_DEBUG( friction > 0.0f );
1138 mFrictionCoefficient = friction;
1141 float ScrollView::GetFlickSpeedCoefficient() const
1143 return mFlickSpeedCoefficient;
1146 void ScrollView::SetFlickSpeedCoefficient(float speed)
1148 mFlickSpeedCoefficient = speed;
1151 float ScrollView::GetMaxFlickSpeed() const
1153 return mMaxFlickSpeed;
1156 void ScrollView::SetMaxFlickSpeed(float speed)
1158 mMaxFlickSpeed = speed;
1161 void ScrollView::SetMouseWheelScrollDistanceStep(Vector2 step)
1163 mMouseWheelScrollDistanceStep = step;
1166 Vector2 ScrollView::GetMouseWheelScrollDistanceStep() const
1168 return mMouseWheelScrollDistanceStep;
1171 unsigned int ScrollView::GetCurrentPage() const
1173 // in case animation is currently taking place.
1174 Vector3 position = GetPropertyPosition();
1176 Actor self = Self();
1177 unsigned int page = 0;
1178 unsigned int pagesPerVolume = 1;
1179 unsigned int volume = 0;
1181 // if rulerX is enabled, then get page count (columns)
1182 page = mRulerX->GetPageFromPosition(-position.x, mWrapMode);
1183 volume = mRulerY->GetPageFromPosition(-position.y, mWrapMode);
1184 pagesPerVolume = mRulerX->GetTotalPages();
1186 return volume * pagesPerVolume + page;
1189 Vector3 ScrollView::GetCurrentScrollPosition() const
1191 return -GetPropertyPosition();
1194 void ScrollView::SetScrollPosition(const Vector3& position)
1196 mScrollPrePosition = position;
1199 Vector3 ScrollView::GetCurrentScrollScale() const
1201 // in case animation is currently taking place.
1202 return GetPropertyScale();
1205 Vector3 ScrollView::GetDomainSize() const
1207 Vector3 size = Self().GetCurrentSize();
1209 const RulerDomain& xDomain = GetRulerX()->GetDomain();
1210 const RulerDomain& yDomain = GetRulerY()->GetDomain();
1212 Vector3 domainSize = Vector3( xDomain.max - xDomain.min, yDomain.max - yDomain.min, 0.0f ) - size;
1216 void ScrollView::TransformTo(const Vector3& position, const Vector3& scale, float rotation,
1217 DirectionBias horizontalBias, DirectionBias verticalBias)
1219 TransformTo(position, scale, rotation, mSnapDuration, horizontalBias, verticalBias);
1222 void ScrollView::TransformTo(const Vector3& position, const Vector3& scale, float rotation, float duration,
1223 DirectionBias horizontalBias, DirectionBias verticalBias)
1225 // Guard against destruction during signal emission
1226 // Note that Emit() methods are called indirectly e.g. from within ScrollView::AnimateTo()
1227 Toolkit::ScrollView handle( GetOwner() );
1229 Vector3 currentScrollPosition = GetCurrentScrollPosition();
1230 Self().SetProperty( mPropertyScrollStartPagePosition, currentScrollPosition );
1232 if(mScrolling) // are we interrupting a current scroll?
1234 // set mScrolling to false, in case user has code that interrogates mScrolling Getter() in complete.
1236 mScrollCompletedSignalV2.Emit( currentScrollPosition );
1239 Self().SetProperty(mPropertyScrolling, true);
1241 mScrollStartedSignalV2.Emit( currentScrollPosition );
1242 bool animating = AnimateTo(-position,
1243 Vector3::ONE * duration,
1245 Vector3::ONE * duration,
1256 // if not animating, then this pan has completed right now.
1257 Self().SetProperty(mPropertyScrolling, false);
1259 mScrollCompletedSignalV2.Emit( currentScrollPosition );
1263 void ScrollView::ScrollTo(const Vector3& position)
1265 ScrollTo(position, mSnapDuration );
1268 void ScrollView::ScrollTo(const Vector3& position, float duration)
1270 ScrollTo(position, duration, DirectionBiasNone, DirectionBiasNone);
1273 void ScrollView::ScrollTo(const Vector3& position, float duration,
1274 DirectionBias horizontalBias, DirectionBias verticalBias)
1276 TransformTo(position, mScrollPostScale, mScrollPostRotation, duration, horizontalBias, verticalBias);
1279 void ScrollView::ScrollTo(unsigned int page)
1281 ScrollTo(page, mSnapDuration);
1284 void ScrollView::ScrollTo(unsigned int page, float duration, DirectionBias bias)
1287 unsigned int volume;
1288 unsigned int libraries;
1290 // The position to scroll to is continuous and linear
1291 // unless a domain has been enabled on the X axis.
1292 // or if WrapMode has been enabled.
1293 bool carryX = mRulerX->GetDomain().enabled | mWrapMode;
1294 bool carryY = mRulerY->GetDomain().enabled | mWrapMode;
1296 position.x = mRulerX->GetPositionFromPage(page, volume, carryX);
1297 position.y = mRulerY->GetPositionFromPage(volume, libraries, carryY);
1299 ScrollTo(position, duration, bias, bias);
1302 void ScrollView::ScrollTo(Actor &actor)
1304 ScrollTo(actor, mSnapDuration);
1307 void ScrollView::ScrollTo(Actor &actor, float duration)
1309 DALI_ASSERT_ALWAYS(actor.GetParent() == Self());
1311 Actor self = Self();
1312 Vector3 size = self.GetCurrentSize();
1313 Vector3 position = actor.GetCurrentPosition();
1314 position -= GetPropertyPrePosition();
1316 ScrollTo(Vector3(position.x - size.width * 0.5f, position.y - size.height * 0.5f, 0.0f), duration);
1319 Actor ScrollView::FindClosestActor()
1321 Actor self = Self();
1322 Vector3 size = self.GetCurrentSize();
1324 return FindClosestActorToPosition(Vector3(size.width * 0.5f,size.height * 0.5f,0.0f));
1327 Actor ScrollView::FindClosestActorToPosition(const Vector3& position, FindDirection dirX, FindDirection dirY, FindDirection dirZ)
1330 float closestDistance2 = 0.0f;
1331 Vector3 actualPosition = position;
1333 unsigned int numChildren = Self().GetChildCount();
1335 for(unsigned int i = 0; i < numChildren; ++i)
1337 Actor child = Self().GetChildAt(i);
1339 if(mInternalActor == child) // ignore internal actor.
1344 Vector3 childPosition = GetPositionOfAnchor(child, AnchorPoint::CENTER);
1346 Vector3 delta = childPosition - actualPosition;
1348 // X-axis checking (only find Actors to the [dirX] of actualPosition)
1349 if(dirX > All) // != All,None
1351 FindDirection deltaH = delta.x > 0 ? Right : Left;
1358 // Y-axis checking (only find Actors to the [dirY] of actualPosition)
1359 if(dirY > All) // != All,None
1361 FindDirection deltaV = delta.y > 0 ? Down : Up;
1368 // Z-axis checking (only find Actors to the [dirZ] of actualPosition)
1369 if(dirZ > All) // != All,None
1371 FindDirection deltaV = delta.y > 0 ? In : Out;
1378 // compare child to closest child in terms of distance.
1379 float distance2 = 0.0f;
1381 // distance2 = the Square of the relevant dimensions of delta
1384 distance2 += delta.x * delta.x;
1389 distance2 += delta.y * delta.y;
1394 distance2 += delta.z * delta.z;
1397 if(closestChild) // Next time.
1399 if(distance2 < closestDistance2)
1401 closestChild = child;
1402 closestDistance2 = distance2;
1407 closestChild = child;
1408 closestDistance2 = distance2;
1412 return closestChild;
1415 bool ScrollView::ScrollToSnapPoint()
1417 Vector2 stationaryVelocity = Vector2(0.0f, 0.0f);
1418 return SnapWithVelocity( stationaryVelocity );
1421 void ScrollView::ScaleTo(const Vector3& scale)
1423 ScaleTo(scale, mSnapDuration);
1426 void ScrollView::ScaleTo(const Vector3& scale, float duration)
1428 TransformTo(mScrollPostPosition, scale, mScrollPostRotation, duration);
1432 // TODO: In situations where axes are different (X snap, Y free)
1433 // Each axis should really have their own independent animation (time and equation)
1434 // Consider, X axis snapping to nearest grid point (EaseOut over fixed time)
1435 // Consider, Y axis simulating physics to arrive at a point (Physics equation over variable time)
1436 // Currently, the axes have been split however, they both use the same EaseOut equation.
1437 bool ScrollView::SnapWithVelocity(Vector2 velocity)
1439 // Animator takes over now, touches are assumed not to interfere.
1440 // And if touches do interfere, then we'll stop animation, update PrePosition
1441 // to current mScroll's properties, and then resume.
1442 // Note: For Flicking this may work a bit different...
1444 float angle = atan2(velocity.y, velocity.x);
1445 float speed2 = velocity.LengthSquared();
1446 AlphaFunction alphaFunction = mSnapAlphaFunction;
1447 Vector3 positionDuration = Vector3::ONE * mSnapDuration;
1448 Vector3 scaleDuration = Vector3::ONE * mSnapDuration;
1449 float rotationDuration = mSnapDuration;
1452 FindDirection horizontal = None;
1453 FindDirection vertical = None;
1455 // orthoAngleRange = Angle tolerance within the Exact N,E,S,W direction
1456 // that will be accepted as a general N,E,S,W flick direction.
1458 const float orthoAngleRange = FLICK_ORTHO_ANGLE_RANGE * M_PI / 180.0f;
1459 const float flickSpeedThreshold2 = FLICK_SPEED_THRESHOLD*FLICK_SPEED_THRESHOLD;
1461 Vector3 positionSnap = mScrollPrePosition;
1463 // Flick logic X Axis
1465 if(mRulerX->IsEnabled() && mLockAxis != LockHorizontal)
1469 if( speed2 > flickSpeedThreshold2 || // exceeds flick threshold
1470 mInAccessibilityPan ) // With AccessibilityPan its easier to move between snap positions
1472 if((angle >= -orthoAngleRange) && (angle < orthoAngleRange)) // Swiping East
1474 biasX = 0.0f, horizontal = Left;
1476 // This guards against an error where no movement occurs, due to the flick finishing
1477 // before the update-thread has advanced mScrollPostPosition past the the previous snap point.
1478 positionSnap.x += 1.0f;
1480 else if((angle >= M_PI-orthoAngleRange) || (angle < -M_PI+orthoAngleRange)) // Swiping West
1482 biasX = 1.0f, horizontal = Right;
1484 // This guards against an error where no movement occurs, due to the flick finishing
1485 // before the update-thread has advanced mScrollPostPosition past the the previous snap point.
1486 positionSnap.x -= 1.0f;
1491 // Flick logic Y Axis
1493 if(mRulerY->IsEnabled() && mLockAxis != LockVertical)
1497 if( speed2 > flickSpeedThreshold2 || // exceeds flick threshold
1498 mInAccessibilityPan ) // With AccessibilityPan its easier to move between snap positions
1500 if((angle >= M_PI_2-orthoAngleRange) && (angle < M_PI_2+orthoAngleRange)) // Swiping South
1502 biasY = 0.0f, vertical = Up;
1504 else if((angle >= -M_PI_2-orthoAngleRange) && (angle < -M_PI_2+orthoAngleRange)) // Swiping North
1506 biasY = 1.0f, vertical = Down;
1511 // isFlick: Whether this gesture is a flick or not.
1512 bool isFlick = (horizontal != All || vertical != All);
1513 // isFreeFlick: Whether this gesture is a flick under free panning criteria.
1514 bool isFreeFlick = velocity.LengthSquared() > (FREE_FLICK_SPEED_THRESHOLD*FREE_FLICK_SPEED_THRESHOLD);
1516 if(isFlick || isFreeFlick)
1518 positionDuration = Vector3::ONE * mFlickDuration;
1519 alphaFunction = mFlickAlphaFunction;
1522 // Calculate next positionSnap ////////////////////////////////////////////////////////////
1524 if(mActorAutoSnapEnabled)
1526 Vector3 size = Self().GetCurrentSize();
1528 Actor child = FindClosestActorToPosition( Vector3(size.width * 0.5f,size.height * 0.5f,0.0f), horizontal, vertical );
1530 if(!child && isFlick )
1532 // If we conducted a direction limited search and found no actor, then just snap to the closest actor.
1533 child = FindClosestActorToPosition( Vector3(size.width * 0.5f,size.height * 0.5f,0.0f) );
1538 Vector3 position = Self().GetProperty<Vector3>(mPropertyPosition);
1540 // Get center-point of the Actor.
1541 Vector3 childPosition = GetPositionOfAnchor(child, AnchorPoint::CENTER);
1543 if(mRulerX->IsEnabled())
1545 positionSnap.x = position.x - childPosition.x + size.width * 0.5f;
1547 if(mRulerY->IsEnabled())
1549 positionSnap.y = position.y - childPosition.y + size.height * 0.5f;
1554 Vector3 startPosition = positionSnap;
1555 positionSnap.x = -mRulerX->Snap(-positionSnap.x, biasX); // NOTE: X & Y rulers think in -ve coordinate system.
1556 positionSnap.y = -mRulerY->Snap(-positionSnap.y, biasY); // That is scrolling RIGHT (e.g. 100.0, 0.0) means moving LEFT.
1558 Vector3 clampDelta(Vector3::ZERO);
1559 ClampPosition(positionSnap);
1561 if( (mRulerX->GetType() == Ruler::Free || mRulerY->GetType() == Ruler::Free)
1562 && isFreeFlick && !mActorAutoSnapEnabled)
1564 // Calculate target position based on velocity of flick.
1566 // a = Deceleration (Set to diagonal stage length * friction coefficient)
1567 // u = Initial Velocity (Flick velocity)
1568 // v = 0 (Final Velocity)
1569 // t = Time (Velocity / Deceleration)
1570 Vector2 stageSize = Stage::GetCurrent().GetSize();
1571 float stageLength = Vector3(stageSize.x, stageSize.y, 0.0f).Length();
1572 float a = (stageLength * mFrictionCoefficient);
1573 Vector3 u = Vector3(velocity.x, velocity.y, 0.0f) * mFlickSpeedCoefficient;
1574 float speed = u.Length();
1577 // TODO: Change this to a decay function. (faster you flick, the slower it should be)
1578 speed = std::min(speed, stageLength * mMaxFlickSpeed );
1580 alphaFunction = ConstantDecelerationAlphaFunction;
1582 float t = speed / a;
1584 if(mRulerX->IsEnabled() && mRulerX->GetType() == Ruler::Free)
1586 positionSnap.x += t*u.x*0.5f;
1589 if(mRulerY->IsEnabled() && mRulerY->GetType() == Ruler::Free)
1591 positionSnap.y += t*u.y*0.5f;
1594 clampDelta = positionSnap;
1595 ClampPosition(positionSnap);
1596 if((positionSnap - startPosition).LengthSquared() > Math::MACHINE_EPSILON_0)
1598 clampDelta -= positionSnap;
1599 clampDelta.x = clampDelta.x > 0.0f ? std::min(clampDelta.x, mMaxOvershoot.x) : std::max(clampDelta.x, -mMaxOvershoot.x);
1600 clampDelta.y = clampDelta.y > 0.0f ? std::min(clampDelta.y, mMaxOvershoot.y) : std::max(clampDelta.y, -mMaxOvershoot.y);
1604 clampDelta = Vector3::ZERO;
1607 // If Axis is Free and has velocity, then calculate time taken
1608 // to reach target based on velocity in axis.
1609 if(mRulerX->IsEnabled() && mRulerX->GetType() == Ruler::Free)
1611 float deltaX = fabsf(startPosition.x - positionSnap.x);
1613 if(fabsf(u.x) > Math::MACHINE_EPSILON_1)
1615 positionDuration.x = fabsf(deltaX / u.x);
1619 positionDuration.x = 0;
1623 if(mRulerY->IsEnabled() && mRulerY->GetType() == Ruler::Free)
1625 float deltaY = fabsf(startPosition.y - positionSnap.y);
1627 if(fabsf(u.y) > Math::MACHINE_EPSILON_1)
1629 positionDuration.y = fabsf(deltaY / u.y);
1633 positionDuration.y = 0;
1637 positionSnap += clampDelta;
1639 // Scale Snap ///////////////////////////////////////////////////////////////
1640 Vector3 scaleSnap = mScrollPostScale;
1642 scaleSnap.x = mRulerScaleX->Snap(scaleSnap.x);
1643 scaleSnap.y = mRulerScaleY->Snap(scaleSnap.y);
1645 ClampScale(scaleSnap);
1647 // Rotation Snap ////////////////////////////////////////////////////////////
1648 float rotationSnap = mScrollPostRotation;
1649 // TODO: implement rotation snap
1651 bool animating = AnimateTo(positionSnap, positionDuration,
1652 scaleSnap, scaleDuration,
1653 rotationSnap, rotationDuration,
1654 alphaFunction, false,
1655 DirectionBiasNone, DirectionBiasNone,
1656 isFlick || isFreeFlick ? Flick : Snap);
1661 void ScrollView::StopAnimation(void)
1663 // Clear Snap animation if exists.
1664 StopAnimation(mSnapAnimation);
1665 StopAnimation(mInternalXAnimation);
1666 StopAnimation(mInternalYAnimation);
1667 mScrollStateFlags = 0;
1668 // remove scroll animation flags
1669 HandleStoppedAnimation();
1672 void ScrollView::StopAnimation(Animation& animation)
1681 bool ScrollView::AnimateTo(const Vector3& position, const Vector3& positionDuration,
1682 const Vector3& scale, const Vector3& scaleDuration,
1683 float rotation, float rotationDuration,
1684 AlphaFunction alpha, bool findShortcuts,
1685 DirectionBias horizontalBias, DirectionBias verticalBias,
1688 // Here we perform an animation on a number of properties (depending on which have changed)
1689 // The animation is applied to all ScrollBases
1690 Actor self = Self();
1691 mScrollTargetPosition = position;
1692 float totalDuration = 0.0f;
1694 bool positionChanged = (mScrollTargetPosition != mScrollPostPosition);
1695 bool scaleChanged = (scale != mScrollPostScale);
1696 bool rotationChanged = fabsf(rotation - mScrollPostRotation) > Math::MACHINE_EPSILON_0;
1700 totalDuration = std::max(totalDuration, positionDuration.x);
1701 totalDuration = std::max(totalDuration, positionDuration.y);
1705 // try to animate for a frame, on some occasions update will be changing scroll value while event side thinks it hasnt changed
1706 totalDuration = 0.01f;
1707 positionChanged = true;
1712 totalDuration = std::max(totalDuration, scaleDuration.x);
1713 totalDuration = std::max(totalDuration, scaleDuration.y);
1718 totalDuration = std::max(totalDuration, rotationDuration);
1722 // Position Delta ///////////////////////////////////////////////////////
1725 if(mWrapMode && findShortcuts)
1727 // In Wrap Mode, the shortest distance is a little less intuitive...
1728 const RulerDomain rulerDomainX = mRulerX->GetDomain();
1729 const RulerDomain rulerDomainY = mRulerY->GetDomain();
1731 if(mRulerX->IsEnabled())
1733 float dir = VectorInDomain(-mScrollPostPosition.x, -mScrollTargetPosition.x, rulerDomainX.min, rulerDomainX.max, horizontalBias);
1734 mScrollTargetPosition.x = mScrollPostPosition.x + -dir;
1737 if(mRulerY->IsEnabled())
1739 float dir = VectorInDomain(-mScrollPostPosition.y, -mScrollTargetPosition.y, rulerDomainY.min, rulerDomainY.max, verticalBias);
1740 mScrollTargetPosition.y = mScrollPostPosition.y + -dir;
1744 // note we have two separate animations for X & Y, this deals with sliding diagonally and hitting
1745 // a horizonal/vertical wall.delay
1746 AnimateInternalXTo(mScrollTargetPosition.x, positionDuration.x, alpha);
1747 AnimateInternalYTo(mScrollTargetPosition.y, positionDuration.y, alpha);
1749 if( !(mScrollStateFlags & SCROLL_ANIMATION_FLAGS) )
1751 self.SetProperty(mPropertyPrePosition, mScrollTargetPosition);
1752 mScrollPrePosition = mScrollTargetPosition;
1756 // Scale Delta ///////////////////////////////////////////////////////
1759 if(totalDuration > Math::MACHINE_EPSILON_1)
1761 mSnapAnimation = Animation::New(totalDuration);
1762 mSnapAnimation.FinishedSignal().Connect(this, &ScrollView::OnScrollAnimationFinished);
1763 // TODO: for non-uniform scaling to different bounds e.g. scaling a square to a 4:3 aspect ratio screen with a velocity
1764 // the height will hit first, and then the width, so that would require two different animation times just like position.
1765 mSnapAnimation.AnimateTo( Property(self, mPropertyScale), scale, alpha, TimePeriod(0.0f, scaleDuration.x));
1767 mSnapAnimation.AnimateTo( Property(self, mPropertyTime), totalDuration, AlphaFunctions::Linear );
1768 mSnapAnimation.Play();
1772 self.SetProperty(mPropertyScale, scale);
1774 mScrollPreScale = mScrollPostScale = scale;
1777 StartRefreshTimer();
1779 // Always send a snap event when AnimateTo is called.
1780 Toolkit::ScrollView::SnapEvent snapEvent;
1781 snapEvent.type = snapType;
1782 snapEvent.position = -mScrollTargetPosition;
1783 snapEvent.scale = scale;
1784 snapEvent.rotation = rotation;
1785 snapEvent.duration = totalDuration;
1787 mSnapStartedSignalV2.Emit( snapEvent );
1789 return (mScrollStateFlags & SCROLL_ANIMATION_FLAGS) != 0;
1792 void ScrollView::SetOvershootEnabled(bool enabled)
1794 if(enabled && !mOvershootIndicator)
1796 mOvershootIndicator = ScrollOvershootIndicator::New();
1800 mMaxOvershoot = OVERSCROLL_CLAMP;
1801 mOvershootIndicator->AttachToScrollable(*this);
1805 mMaxOvershoot = mUserMaxOvershoot;
1806 mOvershootIndicator->DetachFromScrollable(*this);
1808 UpdateMainInternalConstraint();
1811 void ScrollView::AddOverlay(Actor actor)
1813 mInternalActor.Add( actor );
1816 void ScrollView::RemoveOverlay(Actor actor)
1818 mInternalActor.Remove( actor );
1821 void ScrollView::SetScrollingDirection( Radian direction, Radian threshold )
1823 PanGestureDetector panGesture( GetPanGestureDetector() );
1825 // First remove just in case we have some set, then add.
1826 panGesture.RemoveDirection( direction );
1827 panGesture.AddDirection( direction, threshold );
1830 void ScrollView::RemoveScrollingDirection( Radian direction )
1832 PanGestureDetector panGesture( GetPanGestureDetector() );
1833 panGesture.RemoveDirection( direction );
1836 Toolkit::ScrollView::SnapStartedSignalV2& ScrollView::SnapStartedSignal()
1838 return mSnapStartedSignalV2;
1841 void ScrollView::FindAndUnbindActor(Actor child)
1846 Vector3 ScrollView::GetPropertyPrePosition() const
1848 Vector3 position = Self().GetProperty<Vector3>(mPropertyPrePosition);
1849 WrapPosition(position);
1853 Vector3 ScrollView::GetPropertyPosition() const
1855 Vector3 position = Self().GetProperty<Vector3>(mPropertyPosition);
1856 WrapPosition(position);
1861 Vector3 ScrollView::GetPropertyScale() const
1863 return Self().GetProperty<Vector3>(mPropertyScale);
1866 void ScrollView::HandleStoppedAnimation()
1868 // Animation has stopped, so stop sending the scroll-update signal.
1869 CancelRefreshTimer();
1872 void ScrollView::HandleSnapAnimationFinished()
1874 // Emit Signal that scrolling has completed.
1876 Actor self = Self();
1877 self.SetProperty(mPropertyScrolling, false);
1879 Vector3 deltaPosition(mScrollPrePosition);
1881 UpdateLocalScrollProperties();
1882 WrapPosition(mScrollPrePosition);
1883 self.SetProperty(mPropertyPrePosition, mScrollPrePosition);
1885 Vector3 currentScrollPosition = GetCurrentScrollPosition();
1886 mScrollCompletedSignalV2.Emit( currentScrollPosition );
1888 mDomainOffset += deltaPosition - mScrollPostPosition;
1889 self.SetProperty(mPropertyDomainOffset, mDomainOffset);
1890 HandleStoppedAnimation();
1893 bool ScrollView::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
1895 Dali::BaseHandle handle( object );
1897 bool connected( true );
1898 Toolkit::ScrollView view = Toolkit::ScrollView::DownCast( handle );
1900 if( Toolkit::ScrollView::SIGNAL_SNAP_STARTED == signalName )
1902 view.SnapStartedSignal().Connect( tracker, functor );
1906 // signalName does not match any signal
1913 void ScrollView::OnSizeAnimation(Animation& animation, const Vector3& targetSize)
1915 // need to update domain properties for new size
1916 UpdatePropertyDomain(targetSize);
1919 void ScrollView::OnControlSizeSet( const Vector3& size )
1921 // need to update domain properties for new size
1922 if( mDefaultMaxOvershoot )
1924 mUserMaxOvershoot.x = size.x * 0.5f;
1925 mUserMaxOvershoot.y = size.y * 0.5f;
1926 if( !IsScrollComponentEnabled(Toolkit::Scrollable::OvershootIndicator) )
1928 mMaxOvershoot = mUserMaxOvershoot;
1931 UpdatePropertyDomain(size);
1932 UpdateMainInternalConstraint();
1933 if( IsScrollComponentEnabled(Toolkit::Scrollable::OvershootIndicator) )
1935 mOvershootIndicator->Reset();
1939 void ScrollView::OnChildAdd(Actor& child)
1947 void ScrollView::OnChildRemove(Actor& child)
1949 // TODO: Actor needs a RemoveConstraint method to take out an individual constraint.
1953 void ScrollView::OnPropertySet( Property::Index index, Property::Value propertyValue )
1955 Actor self = Self();
1956 if( index == mPropertyX )
1958 self.GetProperty(mPropertyPrePosition).Get(mScrollPrePosition);
1959 propertyValue.Get(mScrollPrePosition.x);
1960 self.SetProperty(mPropertyPrePosition, mScrollPrePosition);
1962 else if( index == mPropertyY )
1964 self.GetProperty(mPropertyPrePosition).Get(mScrollPrePosition);
1965 propertyValue.Get(mScrollPrePosition.y);
1966 self.SetProperty(mPropertyPrePosition, mScrollPrePosition);
1968 else if( index == mPropertyPrePosition )
1970 propertyValue.Get(mScrollPrePosition);
1974 void ScrollView::StartTouchDownTimer()
1976 if ( !mTouchDownTimer )
1978 mTouchDownTimer = Timer::New( TOUCH_DOWN_TIMER_INTERVAL );
1979 mTouchDownTimer.TickSignal().Connect( this, &ScrollView::OnTouchDownTimeout );
1982 mTouchDownTimer.Start();
1985 void ScrollView::StopTouchDownTimer()
1987 if ( mTouchDownTimer )
1989 mTouchDownTimer.Stop();
1993 bool ScrollView::OnTouchDownTimeout()
1995 mTouchDownTimeoutReached = true;
1997 if( mScrollStateFlags & (SCROLL_ANIMATION_FLAGS | SNAP_ANIMATION_FLAGS) )
2000 if( mScrollStateFlags & SCROLL_ANIMATION_FLAGS )
2002 mScrollInterrupted = true;
2003 // reset domain offset as scrolling from original plane.
2004 mDomainOffset = Vector3::ZERO;
2005 Self().SetProperty(mPropertyDomainOffset, Vector3::ZERO);
2007 UpdateLocalScrollProperties();
2008 Vector3 currentScrollPosition = GetCurrentScrollPosition();
2009 mScrollCompletedSignalV2.Emit( currentScrollPosition );
2016 bool ScrollView::OnTouchEvent(const TouchEvent& event)
2020 // Ignore this touch event, if scrollview is insensitive.
2024 // Ignore events with multiple-touch points
2025 if (event.GetPointCount() != 1)
2030 if( event.GetPoint(0).state == TouchPoint::Down )
2032 if(mGestureStackDepth==0)
2034 mTouchDownTime = event.time;
2036 // This allows time for a pan-gesture to start, to avoid breaking snap-animation behavior with fast flicks.
2037 // If touch-down does not become a pan (after timeout interval), then snap-animation can be interrupted.
2038 StartTouchDownTimer();
2041 else if( event.GetPoint(0).state == TouchPoint::Up )
2043 StopTouchDownTimer();
2045 // if the user touches and releases without enough movement to go
2046 // into a gesture state, then we should snap to nearest point.
2047 // otherwise our scroll could be stopped (interrupted) half way through an animation.
2048 if(mGestureStackDepth==0 && mTouchDownTimeoutReached)
2050 unsigned timeDelta( event.time - mTouchDownTime );
2051 if ( timeDelta >= MINIMUM_TIME_BETWEEN_DOWN_AND_UP_FOR_RESET )
2053 // Reset the velocity only if down was received a while ago
2054 mLastVelocity = Vector2( 0.0f, 0.0f );
2057 UpdateLocalScrollProperties();
2058 // Only finish the transform if scrolling was interrupted on down or if we are scrolling
2059 if ( mScrollInterrupted || mScrolling )
2064 mTouchDownTimeoutReached = false;
2065 mScrollInterrupted = false;
2071 bool ScrollView::OnMouseWheelEvent(const MouseWheelEvent& event)
2075 // Ignore this mouse wheel event, if scrollview is insensitive.
2079 Vector3 targetScrollPosition = GetPropertyPosition();
2081 if(mRulerX->IsEnabled() && !mRulerY->IsEnabled())
2083 // If only the ruler in the X axis is enabled, scroll in the X axis.
2084 if(mRulerX->GetType() == Ruler::Free)
2086 // Free panning mode
2087 targetScrollPosition.x += event.z * mMouseWheelScrollDistanceStep.x;
2088 ClampPosition(targetScrollPosition);
2089 ScrollTo(-targetScrollPosition);
2091 else if(!mScrolling)
2093 // Snap mode, only respond to the event when the previous snap animation is finished.
2094 ScrollTo(GetCurrentPage() - event.z);
2099 // If the ruler in the Y axis is enabled, scroll in the Y axis.
2100 if(mRulerY->GetType() == Ruler::Free)
2102 // Free panning mode
2103 targetScrollPosition.y += event.z * mMouseWheelScrollDistanceStep.y;
2104 ClampPosition(targetScrollPosition);
2105 ScrollTo(-targetScrollPosition);
2107 else if(!mScrolling)
2109 // Snap mode, only respond to the event when the previous snap animation is finished.
2110 ScrollTo(GetCurrentPage() - event.z * mRulerX->GetTotalPages());
2117 void ScrollView::ResetScrolling()
2119 Actor self = Self();
2120 self.GetProperty(mPropertyPosition).Get(mScrollPostPosition);
2121 mScrollPrePosition = mScrollPostPosition;
2122 self.SetProperty(mPropertyPrePosition, mScrollPostPosition);
2125 void ScrollView::UpdateLocalScrollProperties()
2127 Actor self = Self();
2128 self.GetProperty(mPropertyPrePosition).Get(mScrollPrePosition);
2129 self.GetProperty(mPropertyPosition).Get(mScrollPostPosition);
2132 // private functions
2134 void ScrollView::PreAnimatedScrollSetup()
2136 // mPropertyPrePosition is our unclamped property with wrapping
2137 // mPropertyPosition is our final scroll position after clamping
2139 Actor self = Self();
2141 Vector3 deltaPosition(mScrollPostPosition);
2142 WrapPosition(mScrollPostPosition);
2143 mDomainOffset += deltaPosition - mScrollPostPosition;
2144 Self().SetProperty(mPropertyDomainOffset, mDomainOffset);
2146 if( mScrollStateFlags & SCROLL_X_STATE_MASK )
2148 // already performing animation on internal x position
2149 StopAnimation(mInternalXAnimation);
2152 if( mScrollStateFlags & SCROLL_Y_STATE_MASK )
2154 // already performing animation on internal y position
2155 StopAnimation(mInternalYAnimation);
2158 mScrollStateFlags = 0;
2160 mScrollPostScale = GetPropertyScale();
2162 // Update Actor position with this wrapped value.
2165 mScrollPreScale = mScrollPostScale;
2166 mScrollPreRotation = mScrollPostRotation;
2169 void ScrollView::FinaliseAnimatedScroll()
2171 // TODO - common animation finishing code in here
2174 void ScrollView::AnimateInternalXTo( float position, float duration, AlphaFunction alpha )
2176 StopAnimation(mInternalXAnimation);
2178 if( duration > Math::MACHINE_EPSILON_10 )
2180 Actor self = Self();
2181 mInternalXAnimation = Animation::New(duration);
2182 mInternalXAnimation.FinishedSignal().Connect(this, &ScrollView::OnScrollAnimationFinished);
2183 mInternalXAnimation.AnimateTo( Property(self, mPropertyPrePosition, 0), position, alpha, duration);
2184 mInternalXAnimation.Play();
2186 // erase current state flags
2187 mScrollStateFlags &= ~SCROLL_X_STATE_MASK;
2188 // add internal animation state flag
2189 mScrollStateFlags |= AnimatingInternalX;
2193 void ScrollView::AnimateInternalYTo( float position, float duration, AlphaFunction alpha )
2195 StopAnimation(mInternalYAnimation);
2197 if( duration > Math::MACHINE_EPSILON_10 )
2199 Actor self = Self();
2200 mInternalYAnimation = Animation::New(duration);
2201 mInternalYAnimation.FinishedSignal().Connect(this, &ScrollView::OnScrollAnimationFinished);
2202 mInternalYAnimation.AnimateTo( Property(self, mPropertyPrePosition, 1), position, alpha, TimePeriod(duration));
2203 mInternalYAnimation.Play();
2205 // erase current state flags
2206 mScrollStateFlags &= ~SCROLL_Y_STATE_MASK;
2207 // add internal animation state flag
2208 mScrollStateFlags |= AnimatingInternalY;
2212 void ScrollView::OnScrollAnimationFinished( Animation& source )
2214 // Guard against destruction during signal emission
2215 // Note that ScrollCompletedSignal is emitted from HandleSnapAnimationFinished()
2216 Toolkit::ScrollView handle( GetOwner() );
2218 bool scrollingFinished = false;
2220 // update our local scroll positions
2221 UpdateLocalScrollProperties();
2223 if( source == mSnapAnimation )
2225 // generic snap animation used for scaling and rotation
2226 mSnapAnimation.Reset();
2229 if( source == mInternalXAnimation )
2231 if( !(mScrollStateFlags & AnimatingInternalY) )
2233 scrollingFinished = true;
2235 mInternalXAnimation.Reset();
2236 SnapInternalXTo(mScrollPostPosition.x);
2239 if( source == mInternalYAnimation )
2241 if( !(mScrollStateFlags & AnimatingInternalX) )
2243 scrollingFinished = true;
2245 mInternalYAnimation.Reset();
2246 SnapInternalYTo(mScrollPostPosition.y);
2249 if(scrollingFinished)
2251 HandleSnapAnimationFinished();
2255 void ScrollView::OnSnapInternalPositionFinished( Animation& source )
2257 Actor self = Self();
2258 UpdateLocalScrollProperties();
2259 if( source == mInternalXAnimation )
2261 // clear internal x animation flags
2262 mScrollStateFlags &= ~SCROLL_X_STATE_MASK;
2263 mInternalXAnimation.Reset();
2264 WrapPosition(mScrollPrePosition);
2266 if( source == mInternalYAnimation )
2268 mScrollStateFlags &= ~SCROLL_Y_STATE_MASK;
2269 mInternalYAnimation.Reset();
2270 WrapPosition(mScrollPrePosition);
2274 void ScrollView::SnapInternalXTo(float position)
2276 Actor self = Self();
2278 StopAnimation(mInternalXAnimation);
2280 // erase current state flags
2281 mScrollStateFlags &= ~SCROLL_X_STATE_MASK;
2283 // if internal x not equal to inputed parameter, animate it
2284 float duration = std::min(fabsf((position - mScrollPrePosition.x) / mMaxOvershoot.x) * mSnapOvershootDuration, mSnapOvershootDuration);
2285 if( duration > Math::MACHINE_EPSILON_1 )
2287 mInternalXAnimation = Animation::New(duration);
2288 mInternalXAnimation.FinishedSignal().Connect(this, &ScrollView::OnSnapInternalPositionFinished);
2289 mInternalXAnimation.AnimateTo(Property(self, mPropertyPrePosition, 0), position);
2290 mInternalXAnimation.Play();
2292 // add internal animation state flag
2293 mScrollStateFlags |= SnappingInternalX;
2297 void ScrollView::SnapInternalYTo(float position)
2299 Actor self = Self();
2301 StopAnimation(mInternalYAnimation);
2303 // erase current state flags
2304 mScrollStateFlags &= ~SCROLL_Y_STATE_MASK;
2306 // if internal y not equal to inputed parameter, animate it
2307 float duration = std::min(fabsf((position - mScrollPrePosition.y) / mMaxOvershoot.y) * mSnapOvershootDuration, mSnapOvershootDuration);
2308 if( duration > Math::MACHINE_EPSILON_1 )
2310 mInternalYAnimation = Animation::New(duration);
2311 mInternalYAnimation.FinishedSignal().Connect(this, &ScrollView::OnSnapInternalPositionFinished);
2312 mInternalYAnimation.AnimateTo(Property(self, mPropertyPrePosition, 1), position);
2313 mInternalYAnimation.Play();
2315 // add internal animation state flag
2316 mScrollStateFlags |= SnappingInternalY;
2320 void ScrollView::GestureStarted()
2322 // we handle the first gesture.
2323 // if we're currently doing a gesture and receive another
2324 // we continue and combine the effects of the gesture instead of reseting.
2325 if(mGestureStackDepth++==0)
2327 Actor self = Self();
2328 StopTouchDownTimer();
2330 mPanDelta = Vector3::ZERO;
2331 mScaleDelta = Vector3::ONE;
2332 mRotationDelta = 0.0f;
2333 mLastVelocity = Vector2(0.0f, 0.0f);
2336 mLockAxis = LockPossible;
2339 if( mScrollStateFlags & SCROLL_X_STATE_MASK )
2341 StopAnimation(mInternalXAnimation);
2343 if( mScrollStateFlags & SCROLL_Y_STATE_MASK )
2345 StopAnimation(mInternalYAnimation);
2347 mScrollStateFlags = 0;
2349 if(mScrolling) // are we interrupting a current scroll?
2351 // set mScrolling to false, in case user has code that interrogates mScrolling Getter() in complete.
2353 // send negative scroll position since scroll internal scroll position works as an offset for actors,
2354 // give applications the position within the domain from the scroll view's anchor position
2355 mScrollCompletedSignalV2.Emit( -mScrollPostPosition );
2360 void ScrollView::GestureContinuing(const Vector2& panDelta, const Vector2& scaleDelta, float rotationDelta)
2362 mPanDelta.x+= panDelta.x;
2363 mPanDelta.y+= panDelta.y;
2364 mScaleDelta.x*= scaleDelta.x;
2365 mScaleDelta.y*= scaleDelta.y;
2366 mRotationDelta+= rotationDelta;
2368 // Save the velocity, there is a bug in PanGesture
2369 // Whereby the Gesture::Finished's velocity is either:
2370 // NaN (due to time delta of zero between the last two events)
2371 // or 0 (due to position being the same between the last two events)
2373 // Axis Auto Lock - locks the panning to the horizontal or vertical axis if the pan
2374 // appears mostly horizontal or mostly vertical respectively.
2377 mLockAxis = GetLockAxis(mPanDelta.GetVectorXY(), mLockAxis, mAxisAutoLockGradient);
2378 } // end if mAxisAutoLock
2381 // TODO: Upgrade to use a more powerful gesture detector (one that supports multiple touches on pan - so works as pan and flick gesture)
2382 // TODO: Reimplement Scaling (pinching 2+ points)
2383 // TODO: Reimplment Rotation (pinching 2+ points)
2384 // BUG: Gesture::Finished doesn't always return velocity on release (due to
2385 // timeDelta between last two events being 0 sometimes, or posiiton being the same)
2386 void ScrollView::OnPan(PanGesture gesture)
2388 // Guard against destruction during signal emission
2389 // Note that Emit() methods are called indirectly e.g. from within ScrollView::OnGestureEx()
2390 Actor self( Self() );
2394 // If another callback on the same original signal disables sensitivity,
2395 // this callback will still be called, so we must suppress it.
2399 // translate Gesture input to get useful data...
2400 switch(gesture.state)
2402 case Gesture::Started:
2404 UpdateLocalScrollProperties();
2407 self.SetProperty( mPropertyPanning, true );
2408 self.SetProperty( mPropertyScrollStartPagePosition, Vector3(gesture.position.x, gesture.position.y, 0.0f) );
2410 UpdateMainInternalConstraint();
2414 case Gesture::Continuing:
2416 GestureContinuing(gesture.screenDisplacement, Vector2::ZERO, 0.0f);
2420 case Gesture::Finished:
2421 case Gesture::Cancelled:
2423 UpdateLocalScrollProperties();
2424 mLastVelocity = gesture.velocity;
2426 self.SetProperty( mPropertyPanning, false );
2428 if( mScrollMainInternalPrePositionConstraint )
2430 self.RemoveConstraint(mScrollMainInternalPrePositionConstraint);
2435 case Gesture::Possible:
2436 case Gesture::Clear:
2438 // Nothing to do, not needed.
2442 } // end switch(gesture.state)
2444 OnGestureEx(gesture.state);
2447 void ScrollView::OnGestureEx(Gesture::State state)
2449 // call necessary signals for application developer
2451 if(state == Gesture::Started)
2453 Vector3 currentScrollPosition = GetCurrentScrollPosition();
2454 Self().SetProperty(mPropertyScrolling, true);
2456 mScrollStartedSignalV2.Emit( currentScrollPosition );
2458 else if( (state == Gesture::Finished) ||
2459 (state == Gesture::Cancelled) ) // Finished/default
2461 // when all the gestures have finished, we finish the transform.
2462 // so if a user decides to pan (1 gesture), and then pan+zoom (2 gestures)
2463 // then stop panning (back to 1 gesture), and then stop zooming (0 gestures).
2464 // this is the point we end, and perform necessary snapping.
2465 mGestureStackDepth--;
2466 if(mGestureStackDepth==0)
2473 void ScrollView::UpdateTransform()
2475 // TODO: notify clamps using property notifications (or see if we need this, can deprecate it)
2478 void ScrollView::FinishTransform()
2480 // at this stage internal x and x scroll position should have followed prescroll position exactly
2481 Actor self = Self();
2483 PreAnimatedScrollSetup();
2485 bool animating = SnapWithVelocity(mLastVelocity * 1000.0f);
2489 // if not animating, then this pan has completed right now.
2491 Self().SetProperty(mPropertyScrolling, false);
2492 Vector3 currentScrollPosition = GetCurrentScrollPosition();
2493 mScrollCompletedSignalV2.Emit( currentScrollPosition );
2497 Vector3 ScrollView::GetOvershoot(Vector3& position) const
2499 Vector3 size = Self().GetCurrentSize();
2502 const RulerDomain rulerDomainX = mRulerX->GetDomain();
2503 const RulerDomain rulerDomainY = mRulerY->GetDomain();
2505 if(mRulerX->IsEnabled() && rulerDomainX.enabled)
2507 const float left = rulerDomainX.min - position.x;
2508 const float right = size.width - rulerDomainX.max - position.x;
2515 overshoot.x = right;
2519 if(mRulerY->IsEnabled() && rulerDomainY.enabled)
2521 const float top = rulerDomainY.min - position.y;
2522 const float bottom = size.height - rulerDomainY.max - position.y;
2529 overshoot.y = bottom;
2536 bool ScrollView::OnAccessibilityPan(PanGesture gesture)
2538 // Keep track of whether this is an AccessibilityPan
2539 mInAccessibilityPan = true;
2541 mInAccessibilityPan = false;
2546 void ScrollView::ClampPosition(Vector3& position) const
2548 ClampState3 clamped;
2549 ClampPosition(position, clamped);
2552 void ScrollView::ClampPosition(Vector3& position, ClampState3 &clamped) const
2554 Vector3 size = Self().GetCurrentSize();
2556 // determine size of viewport relative to current scaled size.
2557 // e.g. if you're zoomed in 200%, then each pixel on screen is only 0.5 pixels on subject.
2558 if(fabsf(mScrollPostScale.x) > Math::MACHINE_EPSILON_0)
2560 size.x /= mScrollPostScale.x;
2563 if(fabsf(mScrollPostScale.y) > Math::MACHINE_EPSILON_0)
2565 size.y /= mScrollPostScale.y;
2568 position.x = -mRulerX->Clamp(-position.x, size.width, 1.0f, clamped.x); // NOTE: X & Y rulers think in -ve coordinate system.
2569 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.
2571 clamped.z = NotClamped;
2574 void ScrollView::WrapPosition(Vector3& position) const
2578 const RulerDomain rulerDomainX = mRulerX->GetDomain();
2579 const RulerDomain rulerDomainY = mRulerY->GetDomain();
2581 if(mRulerX->IsEnabled())
2583 position.x = -WrapInDomain(-position.x, rulerDomainX.min, rulerDomainX.max);
2586 if(mRulerY->IsEnabled())
2588 position.y = -WrapInDomain(-position.y, rulerDomainY.min, rulerDomainY.max);
2593 void ScrollView::ClampScale(Vector3& scale) const
2595 ClampState3 clamped;
2596 ClampScale(scale, clamped);
2599 void ScrollView::ClampScale(Vector3& scale, ClampState3 &clamped) const
2601 scale.x = mRulerScaleX->Clamp(scale.x, 0.0f, 1.0f, clamped.x);
2602 scale.y = mRulerScaleY->Clamp(scale.y, 0.0f, 1.0f, clamped.y);
2603 clamped.z = NotClamped;
2606 void ScrollView::UpdateMainInternalConstraint()
2608 // TODO: Only update the constraints which have changed, rather than remove all and add all again.
2609 // Requires a dali-core ApplyConstraintAt, or a ReplaceConstraint. The former is probably more flexible.
2610 Actor self = Self();
2611 PanGestureDetector detector( GetPanGestureDetector() );
2613 if(mScrollMainInternalPositionConstraint)
2615 self.RemoveConstraint(mScrollMainInternalPositionConstraint);
2616 self.RemoveConstraint(mScrollMainInternalDeltaConstraint);
2617 self.RemoveConstraint(mScrollMainInternalFinalConstraint);
2618 self.RemoveConstraint(mScrollMainInternalRelativeConstraint);
2619 self.RemoveConstraint(mScrollMainInternalXConstraint);
2620 self.RemoveConstraint(mScrollMainInternalYConstraint);
2622 if( mScrollMainInternalPrePositionConstraint )
2624 self.RemoveConstraint(mScrollMainInternalPrePositionConstraint);
2627 // TODO: It's probably better to use a local displacement value as this will give a displacement when scrolling just commences
2628 // but we need to make sure than the gesture system gives displacement since last frame (60Hz), not displacement since last touch event (90Hz).
2630 // 1. First calculate the pre-position (this is the scroll position if no clamping has taken place)
2631 Vector2 initialPanMask = Vector2(mRulerX->IsEnabled() ? 1.0f : 0.0f, mRulerY->IsEnabled() ? 1.0f : 0.0f);
2633 if( mLockAxis == LockVertical )
2635 initialPanMask.y = 0.0f;
2637 else if( mLockAxis == LockHorizontal )
2639 initialPanMask.x = 0.0f;
2641 Constraint constraint;
2645 constraint = Constraint::New<Vector3>( mPropertyPrePosition,
2646 Source( detector, PanGestureDetector::LOCAL_POSITION ),
2647 Source( detector, PanGestureDetector::LOCAL_DISPLACEMENT ),
2648 Source( self, Actor::SIZE ),
2649 InternalPrePositionConstraint( initialPanMask, mAxisAutoLock, mAxisAutoLockGradient, mLockAxis, mMaxOvershoot, mRulerX->GetDomain(), mRulerY->GetDomain() ) );
2650 mScrollMainInternalPrePositionConstraint = self.ApplyConstraint( constraint );
2653 // 2. Second calculate the clamped position (actual position)
2654 constraint = Constraint::New<Vector3>( mPropertyPosition,
2655 LocalSource( mPropertyPrePosition ),
2656 LocalSource( mPropertyPositionMin ),
2657 LocalSource( mPropertyPositionMax ),
2658 Source( self, Actor::SIZE ),
2659 InternalPositionConstraint( mRulerX->GetDomain(),
2660 mRulerY->GetDomain(), mWrapMode ) );
2661 mScrollMainInternalPositionConstraint = self.ApplyConstraint( constraint );
2663 constraint = Constraint::New<Vector3>( mPropertyPositionDelta,
2664 LocalSource( mPropertyPosition ),
2665 LocalSource( mPropertyDomainOffset ),
2666 InternalPositionDeltaConstraint );
2667 mScrollMainInternalDeltaConstraint = self.ApplyConstraint( constraint );
2669 constraint = Constraint::New<Vector3>( mPropertyFinal,
2670 LocalSource( mPropertyPosition ),
2671 LocalSource( mPropertyOvershootX ),
2672 LocalSource( mPropertyOvershootY ),
2673 InternalFinalConstraint( FinalDefaultAlphaFunction,
2674 FinalDefaultAlphaFunction ) );
2675 mScrollMainInternalFinalConstraint = self.ApplyConstraint( constraint );
2677 constraint = Constraint::New<Vector3>( mPropertyRelativePosition,
2678 LocalSource( mPropertyPosition ),
2679 LocalSource( mPropertyPositionMin ),
2680 LocalSource( mPropertyPositionMax ),
2681 LocalSource( Actor::SIZE ),
2682 InternalRelativePositionConstraint );
2683 mScrollMainInternalRelativeConstraint = self.ApplyConstraint( constraint );
2685 constraint = Constraint::New<float>( mPropertyX,
2686 LocalSource( mPropertyPrePosition ),
2687 InternalXConstraint );
2688 mScrollMainInternalXConstraint = self.ApplyConstraint( constraint );
2690 constraint = Constraint::New<float>( mPropertyY,
2691 LocalSource( mPropertyPrePosition ),
2692 InternalYConstraint );
2693 mScrollMainInternalYConstraint = self.ApplyConstraint( constraint );
2695 // When panning we want to make sure overshoot values are affected by pre position and post position
2696 SetOvershootConstraintsEnabled(!mWrapMode);
2699 void ScrollView::SetOvershootConstraintsEnabled(bool enabled)
2701 Actor self( Self() );
2702 // remove and reset, it may now be in wrong order with the main internal constraints
2703 if( mScrollMainInternalOvershootXConstraint )
2705 self.RemoveConstraint(mScrollMainInternalOvershootXConstraint);
2706 mScrollMainInternalOvershootXConstraint.Reset();
2707 self.RemoveConstraint(mScrollMainInternalOvershootYConstraint);
2708 mScrollMainInternalOvershootYConstraint.Reset();
2712 Constraint constraint = Constraint::New<float>( mPropertyOvershootX,
2713 LocalSource( mPropertyPrePosition ),
2714 LocalSource( mPropertyPosition ),
2715 LocalSource( mPropertyCanScrollHorizontal ),
2716 OvershootXConstraint(mMaxOvershoot.x) );
2717 mScrollMainInternalOvershootXConstraint = self.ApplyConstraint( constraint );
2719 constraint = Constraint::New<float>( mPropertyOvershootY,
2720 LocalSource( mPropertyPrePosition ),
2721 LocalSource( mPropertyPosition ),
2722 LocalSource( mPropertyCanScrollVertical ),
2723 OvershootYConstraint(mMaxOvershoot.y) );
2724 mScrollMainInternalOvershootYConstraint = self.ApplyConstraint( constraint );
2728 self.SetProperty(mPropertyOvershootX, 0.0f);
2729 self.SetProperty(mPropertyOvershootY, 0.0f);
2733 void ScrollView::SetInternalConstraints()
2735 // Internal constraints (applied to target ScrollBase Actor itself) /////////
2736 UpdateMainInternalConstraint();
2738 // User definable constraints to apply to all child actors //////////////////
2739 Actor self = Self();
2741 // LocalSource - The Actors to be moved.
2742 // self - The ScrollView
2744 // Apply some default constraints to ScrollView.
2745 // Movement + Scaling + Wrap function
2747 Constraint constraint;
2749 // MoveScaledActor (scrolling/zooming)
2750 constraint = Constraint::New<Vector3>( Actor::POSITION,
2751 Source( self, mPropertyPosition ),
2752 Source( self, mPropertyScale ),
2753 MoveScaledActorConstraint );
2754 constraint.SetRemoveAction(Constraint::Discard);
2755 ApplyConstraintToBoundActors(constraint);
2757 // ScaleActor (scrolling/zooming)
2758 constraint = Constraint::New<Vector3>( Actor::SCALE,
2759 Source( self, mPropertyScale ),
2760 ScaleActorConstraint );
2761 constraint.SetRemoveAction(Constraint::Discard);
2762 ApplyConstraintToBoundActors(constraint);
2764 // WrapActor (wrap functionality)
2765 constraint = Constraint::New<Vector3>( Actor::POSITION,
2766 LocalSource( Actor::SCALE ),
2767 LocalSource( Actor::ANCHOR_POINT ),
2768 LocalSource( Actor::SIZE ),
2769 Source( self, mPropertyPositionMin ),
2770 Source( self, mPropertyPositionMax ),
2771 Source( self, mPropertyWrap ),
2772 WrapActorConstraint );
2773 constraint.SetRemoveAction(Constraint::Discard);
2774 ApplyConstraintToBoundActors(constraint);
2777 void ScrollView::StartRefreshTimer()
2779 if(mRefreshIntervalMilliseconds > 0)
2783 mRefreshTimer = Timer::New( mRefreshIntervalMilliseconds );
2784 mRefreshTimer.TickSignal().Connect( this, &ScrollView::OnRefreshTick );
2787 if (!mRefreshTimer.IsRunning())
2789 mRefreshTimer.Start();
2794 void ScrollView::CancelRefreshTimer()
2798 mRefreshTimer.Stop();
2802 bool ScrollView::OnRefreshTick()
2804 // Guard against destruction during signal emission
2805 Toolkit::ScrollView handle( GetOwner() );
2807 Vector3 currentScrollPosition = GetCurrentScrollPosition();
2808 mScrollUpdatedSignalV2.Emit( currentScrollPosition );
2813 } // namespace Internal
2815 } // namespace Toolkit