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)
439 const Vector3& scrollPrePosition = scrollPrePositionProperty.GetVector3();
440 const Vector3& scrollPostPosition = scrollPostPositionProperty.GetVector3();
441 float newOvershoot = scrollPrePosition.x - scrollPostPosition.x;
442 return (newOvershoot > 0.0f ? std::min(newOvershoot, mMaxOvershoot) : std::max(newOvershoot, -mMaxOvershoot)) / mMaxOvershoot;
449 * This constraint updates the Y overshoot property using the difference
450 * mPropertyPrePosition.y and mPropertyPosition.y, returning a relative value between 0.0f and 1.0f
452 struct OvershootYConstraint
454 OvershootYConstraint(float maxOvershoot) : mMaxOvershoot(maxOvershoot) {}
456 float operator()(const float& current,
457 const PropertyInput& scrollPrePositionProperty,
458 const PropertyInput& scrollPostPositionProperty)
460 const Vector3& scrollPrePosition = scrollPrePositionProperty.GetVector3();
461 const Vector3& scrollPostPosition = scrollPostPositionProperty.GetVector3();
462 float newOvershoot = scrollPrePosition.y - scrollPostPosition.y;
463 return (newOvershoot > 0.0f ? std::min(newOvershoot, mMaxOvershoot) : std::max(newOvershoot, -mMaxOvershoot)) / mMaxOvershoot;
470 * When panning, this constraint updates the X property, otherwise
471 * it has no effect on the X property.
473 float InternalXConstraint(const float& current,
474 const PropertyInput& scrollPosition)
476 return scrollPosition.GetVector3().x;
480 * When panning, this constraint updates the Y property, otherwise
481 * it has no effect on the Y property.
483 float InternalYConstraint(const float& current,
484 const PropertyInput& scrollPosition)
486 return scrollPosition.GetVector3().y;
490 * Internal Position-Delta Property Constraint.
492 * Generates position-delta property based on scroll-position + scroll-offset properties.
494 Vector3 InternalPositionDeltaConstraint(const Vector3& current,
495 const PropertyInput& scrollPositionProperty,
496 const PropertyInput& scrollOffsetProperty)
498 const Vector3& scrollPosition = scrollPositionProperty.GetVector3();
499 const Vector3& scrollOffset = scrollOffsetProperty.GetVector3();
501 return scrollPosition + scrollOffset;
505 * Internal Final Position Constraint
506 * The position of content is:
507 * of scroll-position + f(scroll-overshoot)
508 * where f(...) function defines how overshoot
509 * should affect final-position.
511 struct InternalFinalConstraint
513 InternalFinalConstraint(AlphaFunction functionX,
514 AlphaFunction functionY)
515 : mFunctionX(functionX),
516 mFunctionY(functionY)
520 Vector3 operator()(const Vector3& current,
521 const PropertyInput& scrollPositionProperty,
522 const PropertyInput& scrollOvershootXProperty,
523 const PropertyInput& scrollOvershootYProperty)
525 const float& overshootx = scrollOvershootXProperty.GetFloat();
526 const float& overshooty = scrollOvershootYProperty.GetFloat();
527 Vector3 offset( mFunctionX(overshootx),
528 mFunctionY(overshooty),
531 return scrollPositionProperty.GetVector3() - offset;
534 AlphaFunction mFunctionX;
535 AlphaFunction mFunctionY;
541 return Toolkit::ScrollView::New();
544 TypeRegistration typeRegistration( typeid(Toolkit::ScrollView), typeid(Toolkit::Scrollable), Create );
546 SignalConnectorType signalConnector1( typeRegistration, Toolkit::ScrollView::SIGNAL_SNAP_STARTED, &ScrollView::DoConnectSignal );
551 ///////////////////////////////////////////////////////////////////////////////////////////////////
553 ///////////////////////////////////////////////////////////////////////////////////////////////////
555 Dali::Toolkit::ScrollView ScrollView::New()
557 // Create the implementation
558 ScrollViewPtr scrollView(new ScrollView());
560 // Pass ownership to CustomActor via derived handle
561 Dali::Toolkit::ScrollView handle(*scrollView);
563 // Second-phase init of the implementation
564 // This can only be done after the CustomActor connection has been made...
565 scrollView->Initialize();
570 ScrollView::ScrollView()
573 mGestureStackDepth(0),
574 mRotationDelta(0.0f),
575 mScrollStateFlags(0),
576 mScrollPreRotation(0.0f),
577 mScrollPostRotation(0.0f),
578 mMinTouchesForPanning(1),
579 mMaxTouchesForPanning(1),
580 mLockAxis(LockPossible),
581 mRefreshIntervalMilliseconds(DEFAULT_REFRESH_INTERVAL_MILLISECONDS),
582 mOvershootDelay(1.0f),
583 mMaxOvershoot(Toolkit::ScrollView::DEFAULT_MAX_OVERSHOOT, Toolkit::ScrollView::DEFAULT_MAX_OVERSHOOT),
584 mUserMaxOvershoot(Toolkit::ScrollView::DEFAULT_MAX_OVERSHOOT, Toolkit::ScrollView::DEFAULT_MAX_OVERSHOOT),
585 mSnapOvershootDuration(Toolkit::ScrollView::DEFAULT_SNAP_OVERSHOOT_DURATION),
586 mSnapOvershootAlphaFunction(AlphaFunctions::EaseOut),
587 mSnapDuration(Toolkit::ScrollView::DEFAULT_SLOW_SNAP_ANIMATION_DURATION),
588 mSnapAlphaFunction(AlphaFunctions::EaseOut),
589 mFlickDuration(Toolkit::ScrollView::DEFAULT_FAST_SNAP_ANIMATION_DURATION),
590 mFlickAlphaFunction(AlphaFunctions::EaseOut),
591 mAxisAutoLockGradient(Toolkit::ScrollView::DEFAULT_AXIS_AUTO_LOCK_GRADIENT),
592 mFrictionCoefficient(Toolkit::ScrollView::DEFAULT_FRICTION_COEFFICIENT),
593 mFlickSpeedCoefficient(Toolkit::ScrollView::DEFAULT_FLICK_SPEED_COEFFICIENT),
594 mMaxFlickSpeed(Toolkit::ScrollView::DEFAULT_MAX_FLICK_SPEED),
595 mInAccessibilityPan(false),
598 mScrollInterrupted(false),
601 mTouchDownTimeoutReached(false),
602 mActorAutoSnapEnabled(false),
603 mAutoResizeContainerEnabled(false),
605 mAxisAutoLock(false),
607 mDefaultMaxOvershoot(true)
609 SetRequiresMouseWheelEvents(true);
612 void ScrollView::OnInitialize()
616 // Internal Actor, used to hide actors from enumerations.
617 // Also actors added to Internal actor appear as overlays e.g. ScrollBar components.
618 mInternalActor = Actor::New();
619 mInternalActor.SetDrawMode(DrawMode::OVERLAY);
620 self.Add(mInternalActor);
621 mInternalActor.ApplyConstraint( Constraint::New<Vector3>( Actor::SIZE, ParentSource( Actor::SIZE ), EqualToConstraint() ) );
622 mInternalActor.SetParentOrigin(ParentOrigin::CENTER);
623 mInternalActor.SetAnchorPoint(AnchorPoint::CENTER);
627 // Register Scroll Properties.
628 RegisterProperties();
630 mScrollPostPosition = mScrollPrePosition = Vector3::ZERO;
631 mScrollPostScale = mScrollPreScale = Vector3::ONE;
632 mScrollPostRotation = mScrollPreRotation = 0.0f;
634 mMouseWheelScrollDistanceStep = Stage::GetCurrent().GetSize() * DEFAULT_MOUSE_WHEEL_SCROLL_DISTANCE_STEP_PROPORTION;
638 mGestureStackDepth = 0;
640 EnableGestureDetection( Gesture::Type( Gesture::Pan ) );
642 // For pan, default to only 1 touch required, ignoring touches outside this range.
643 SetTouchesRequiredForPanning(1, 1, false);
645 // By default we'll allow the user to freely drag the scroll view,
646 // while disabling the other rulers.
647 RulerPtr ruler = new DefaultRuler();
648 RulerPtr rulerDisabled = new DefaultRuler();
649 rulerDisabled->Disable();
652 mRulerScaleX = rulerDisabled;
653 mRulerScaleY = rulerDisabled;
654 mRulerRotation = rulerDisabled;
656 EnableScrollComponent(Toolkit::Scrollable::OvershootIndicator);
658 Vector3 size = GetControlSize();
659 UpdatePropertyDomain(size);
660 SetInternalConstraints();
663 void ScrollView::OnControlStageConnection()
667 SetScrollSensitive( false );
668 SetScrollSensitive( true );
670 if(IsScrollComponentEnabled(Toolkit::Scrollable::OvershootIndicator))
672 // try and make sure property notifications are set
673 EnableScrollComponent(Toolkit::Scrollable::OvershootIndicator);
677 void ScrollView::OnControlStageDisconnection()
682 ScrollView::~ScrollView()
686 AlphaFunction ScrollView::GetScrollSnapAlphaFunction() const
688 return mSnapAlphaFunction;
691 void ScrollView::SetScrollSnapAlphaFunction(AlphaFunction alpha)
693 mSnapAlphaFunction = alpha;
696 AlphaFunction ScrollView::GetScrollFlickAlphaFunction() const
698 return mFlickAlphaFunction;
701 void ScrollView::SetScrollFlickAlphaFunction(AlphaFunction alpha)
703 mFlickAlphaFunction = alpha;
706 float ScrollView::GetScrollSnapDuration() const
708 return mSnapDuration;
711 void ScrollView::SetScrollSnapDuration(float time)
713 mSnapDuration = time;
716 float ScrollView::GetScrollFlickDuration() const
718 return mFlickDuration;
721 void ScrollView::SetScrollFlickDuration(float time)
723 mFlickDuration = time;
726 void ScrollView::ApplyEffect(Toolkit::ScrollViewEffect effect)
728 Dali::Toolkit::ScrollView self = Dali::Toolkit::ScrollView::DownCast(Self());
730 // Assertion check to ensure effect doesn't already exist in this scrollview
731 bool effectAlreadyExistsInScrollView(false);
732 for (ScrollViewEffectIter iter = mEffects.begin(); iter != mEffects.end(); ++iter)
736 effectAlreadyExistsInScrollView = true;
741 DALI_ASSERT_ALWAYS(!effectAlreadyExistsInScrollView);
743 // add effect to effects list
744 mEffects.push_back(effect);
746 // invoke Attachment request to ScrollView first
747 GetImpl(effect).Attach(self);
750 Toolkit::ScrollViewEffect ScrollView::ApplyEffect(Toolkit::ScrollView::PageEffect effect)
752 Toolkit::ScrollViewEffect scrollEffect;
755 case Toolkit::ScrollView::PageEffectNone:
759 case Toolkit::ScrollView::PageEffectOuterCube:
761 Toolkit::ScrollViewCustomEffect customEffect;
762 scrollEffect = customEffect = Toolkit::ScrollViewCustomEffect::New();
763 Vector2 pageSize = Stage::GetCurrent().GetSize();
764 // 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
765 // 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)
766 // the page moving off screen will slowly build a spacing from 0.0f to 20.0f
767 // the spacing from each page is added together for the final spacing between the two pages.
768 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));
769 customEffect.SetSwingAngleOut(ANGLE_CUSTOM_CUBE_SWING.x, Vector3(0.0f, -1.0f, 0.0f));
770 customEffect.SetSwingAnchor(AnchorPoint::CENTER, AnchorPoint::CENTER_LEFT);
771 customEffect.SetOpacityThreshold(0.7f);
774 case Toolkit::ScrollView::PageEffectDepth:
776 Toolkit::ScrollViewCustomEffect customEffect;
777 scrollEffect = customEffect = Toolkit::ScrollViewCustomEffect::New();
780 case Toolkit::ScrollView::PageEffectInnerCube:
782 Toolkit::ScrollViewCustomEffect customEffect;
783 scrollEffect = customEffect = Toolkit::ScrollViewCustomEffect::New();
784 customEffect.SetPageSpacing(Vector2(30.0f, 30.0f));
785 customEffect.SetAngledOriginPageRotation(ANGLE_CUBE_PAGE_ROTATE);
786 customEffect.SetSwingAngle(ANGLE_CUBE_PAGE_ROTATE.x, Vector3(0,-1,0));
787 customEffect.SetOpacityThreshold(0.5f);
790 case Toolkit::ScrollView::PageEffectCarousel:
792 Toolkit::ScrollViewCustomEffect customEffect;
793 scrollEffect = customEffect = Toolkit::ScrollViewCustomEffect::New();
794 customEffect.SetPageTranslation(Vector3(0,0,0), Vector3(-30, 0, 0));
795 customEffect.SetPageSpacing(Vector2(60.0f, 60.0f));
796 customEffect.SetAngledOriginPageRotation(-ANGLE_CUBE_PAGE_ROTATE);
797 customEffect.SetOpacityThreshold(0.2f, 0.6f);
800 case Toolkit::ScrollView::PageEffectSpiral:
802 Toolkit::ScrollViewCustomEffect customEffect;
803 scrollEffect = customEffect = Toolkit::ScrollViewCustomEffect::New();
805 Vector2 pageSize = Stage::GetCurrent().GetSize();
806 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));
807 //customEffect.SetSwingAngleAlphaFunctionOut(AlphaFunctions::EaseOut);
808 customEffect.SetSwingAnchor(AnchorPoint::CENTER_RIGHT);
809 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);
810 //customEffect.SetPageTranslateAlphaFunctionOut(AlphaFunctions::EaseOut);
811 customEffect.SetOpacityThreshold(0.75f, 0.6f);
812 customEffect.SetOpacityAlphaFunctionIn(AlphaFunctions::EaseInOut);
817 DALI_ASSERT_DEBUG(0 && "unknown scroll view effect");
820 RemoveConstraintsFromChildren();
823 ApplyEffect(scrollEffect);
828 void ScrollView::RemoveEffect(Toolkit::ScrollViewEffect effect)
830 Dali::Toolkit::ScrollView self = Dali::Toolkit::ScrollView::DownCast(Self());
832 // remove effect from effects list
833 bool effectExistedInScrollView(false);
834 for (ScrollViewEffectIter iter = mEffects.begin(); iter != mEffects.end(); ++iter)
838 mEffects.erase(iter);
839 effectExistedInScrollView = true;
844 // Assertion check to ensure effect existed.
845 DALI_ASSERT_ALWAYS(effectExistedInScrollView);
847 // invoke Detachment request to ScrollView last
848 GetImpl(effect).Detach(self);
851 void ScrollView::RemoveAllEffects()
853 Dali::Toolkit::ScrollView self = Dali::Toolkit::ScrollView::DownCast(Self());
855 for (ScrollViewEffectIter effectIter = mEffects.begin(); effectIter != mEffects.end(); ++effectIter)
857 Toolkit::ScrollViewEffect effect = *effectIter;
859 // invoke Detachment request to ScrollView last
860 GetImpl(effect).Detach(self);
866 void ScrollView::ApplyConstraintToChildren(Constraint constraint)
868 ApplyConstraintToBoundActors(constraint);
871 void ScrollView::RemoveConstraintsFromChildren()
873 RemoveConstraintsFromBoundActors();
876 const RulerPtr ScrollView::GetRulerX() const
881 const RulerPtr ScrollView::GetRulerY() const
886 void ScrollView::SetRulerX(RulerPtr ruler)
890 Vector3 size = GetControlSize();
891 UpdatePropertyDomain(size);
892 UpdateMainInternalConstraint();
895 void ScrollView::SetRulerY(RulerPtr ruler)
899 Vector3 size = GetControlSize();
900 UpdatePropertyDomain(size);
901 UpdateMainInternalConstraint();
904 void ScrollView::UpdatePropertyDomain(const Vector3& size)
907 Vector3 min = self.GetProperty<Vector3>(mPropertyPositionMin);
908 Vector3 max = self.GetProperty<Vector3>(mPropertyPositionMax);
909 bool scrollPositionChanged = false;
910 bool domainChanged = false;
912 bool canScrollVertical = false;
913 bool canScrollHorizontal = false;
914 UpdateLocalScrollProperties();
915 if(mRulerX->IsEnabled())
917 const Toolkit::RulerDomain& rulerDomain = mRulerX->GetDomain();
918 if( fabsf(min.x - rulerDomain.min) > Math::MACHINE_EPSILON_10000
919 || fabsf(max.x - rulerDomain.max) > Math::MACHINE_EPSILON_10000 )
921 domainChanged = true;
922 min.x = rulerDomain.min;
923 max.x = rulerDomain.max;
925 // make sure new scroll value is within new domain
926 if( mScrollPrePosition.x < min.x
927 || mScrollPrePosition.x > max.x )
929 scrollPositionChanged = true;
930 mScrollPrePosition.x = Clamp(mScrollPrePosition.x, -(max.x - size.x), -min.x);
932 if((fabsf(max.x - min.x) - size.x) > Math::MACHINE_EPSILON_10000)
934 canScrollHorizontal = true;
939 if(mRulerY->IsEnabled())
941 const Toolkit::RulerDomain& rulerDomain = mRulerY->GetDomain();
942 if( fabsf(min.y - rulerDomain.min) > Math::MACHINE_EPSILON_10000
943 || fabsf(max.y - rulerDomain.max) > Math::MACHINE_EPSILON_10000 )
945 domainChanged = true;
946 min.y = rulerDomain.min;
947 max.y = rulerDomain.max;
949 // make sure new scroll value is within new domain
950 if( mScrollPrePosition.y < min.y
951 || mScrollPrePosition.y > max.y )
953 scrollPositionChanged = true;
954 mScrollPrePosition.y = Clamp(mScrollPrePosition.y, -(max.y - size.y), -min.y);
956 if((fabsf(max.y - min.y) - size.y) > Math::MACHINE_EPSILON_10000)
958 canScrollVertical = true;
962 // avoid setting properties if possible, otherwise this will cause an entire update as well as triggering constraints using each property we update
963 if( self.GetProperty<bool>(mPropertyCanScrollVertical) != canScrollVertical )
965 self.SetProperty(mPropertyCanScrollVertical, canScrollVertical);
967 if( self.GetProperty<bool>(mPropertyCanScrollHorizontal) != canScrollHorizontal )
969 self.SetProperty(mPropertyCanScrollHorizontal, canScrollVertical);
971 if( scrollPositionChanged )
973 self.SetProperty(mPropertyPrePosition, mScrollPrePosition);
977 self.SetProperty(mPropertyPositionMin, min );
978 self.SetProperty(mPropertyPositionMax, max );
982 void ScrollView::SetRulerScaleX(RulerPtr ruler)
984 mRulerScaleX = ruler;
985 UpdateMainInternalConstraint();
988 void ScrollView::SetRulerScaleY(RulerPtr ruler)
990 mRulerScaleY = ruler;
991 UpdateMainInternalConstraint();
994 void ScrollView::SetRulerRotation(RulerPtr ruler)
996 mRulerRotation = ruler;
997 UpdateMainInternalConstraint();
1000 void ScrollView::SetScrollSensitive(bool sensitive)
1002 Actor self = Self();
1003 PanGestureDetector panGesture( GetPanGestureDetector() );
1005 if((!mSensitive) && (sensitive))
1007 mSensitive = sensitive;
1008 panGesture.Attach(self);
1010 else if((mSensitive) && (!sensitive))
1012 // while the scroll view is panning, the state needs to be reset.
1013 bool isPanning = self.GetProperty<bool>( mPropertyPanning );
1016 PanGesture cancelGesture( Gesture::Cancelled );
1017 OnPan( cancelGesture );
1020 panGesture.Detach(self);
1021 mSensitive = sensitive;
1023 mGestureStackDepth = 0;
1027 void ScrollView::SetMaxOvershoot(float overshootX, float overshootY)
1029 mMaxOvershoot.x = overshootX;
1030 mMaxOvershoot.y = overshootY;
1031 mUserMaxOvershoot = mMaxOvershoot;
1032 mDefaultMaxOvershoot = false;
1033 UpdateMainInternalConstraint();
1036 void ScrollView::SetSnapOvershootAlphaFunction(AlphaFunction alpha)
1038 mSnapOvershootAlphaFunction = alpha;
1041 void ScrollView::SetSnapOvershootDuration(float duration)
1043 mSnapOvershootDuration = duration;
1046 void ScrollView::SetTouchesRequiredForPanning(unsigned int minTouches, unsigned int maxTouches, bool endOutside)
1048 PanGestureDetector panGesture( GetPanGestureDetector() );
1050 mMinTouchesForPanning = minTouches;
1051 mMaxTouchesForPanning = maxTouches;
1055 panGesture.SetMinimumTouchesRequired(minTouches);
1056 panGesture.SetMaximumTouchesRequired(maxTouches);
1060 panGesture.SetMinimumTouchesRequired(1);
1061 panGesture.SetMaximumTouchesRequired(UINT_MAX);
1065 void ScrollView::SetActorAutoSnap(bool enable)
1067 mActorAutoSnapEnabled = enable;
1070 void ScrollView::SetAutoResize(bool enable)
1072 mAutoResizeContainerEnabled = enable;
1073 // TODO: This needs a lot of issues to be addressed before working.
1076 bool ScrollView::GetWrapMode() const
1081 void ScrollView::SetWrapMode(bool enable)
1084 Self().SetProperty(mPropertyWrap, enable);
1087 int ScrollView::GetRefreshInterval() const
1089 return mRefreshIntervalMilliseconds;
1092 void ScrollView::SetRefreshInterval(int milliseconds)
1094 mRefreshIntervalMilliseconds = milliseconds;
1097 bool ScrollView::GetAxisAutoLock() const
1099 return mAxisAutoLock;
1102 void ScrollView::SetAxisAutoLock(bool enable)
1104 mAxisAutoLock = enable;
1105 UpdateMainInternalConstraint();
1108 float ScrollView::GetAxisAutoLockGradient() const
1110 return mAxisAutoLockGradient;
1113 void ScrollView::SetAxisAutoLockGradient(float gradient)
1115 DALI_ASSERT_DEBUG( gradient >= 0.0f && gradient <= 1.0f );
1116 mAxisAutoLockGradient = gradient;
1117 UpdateMainInternalConstraint();
1120 float ScrollView::GetFrictionCoefficient() const
1122 return mFrictionCoefficient;
1125 void ScrollView::SetFrictionCoefficient(float friction)
1127 DALI_ASSERT_DEBUG( friction > 0.0f );
1128 mFrictionCoefficient = friction;
1131 float ScrollView::GetFlickSpeedCoefficient() const
1133 return mFlickSpeedCoefficient;
1136 void ScrollView::SetFlickSpeedCoefficient(float speed)
1138 mFlickSpeedCoefficient = speed;
1141 float ScrollView::GetMaxFlickSpeed() const
1143 return mMaxFlickSpeed;
1146 void ScrollView::SetMaxFlickSpeed(float speed)
1148 mMaxFlickSpeed = speed;
1151 void ScrollView::SetMouseWheelScrollDistanceStep(Vector2 step)
1153 mMouseWheelScrollDistanceStep = step;
1156 Vector2 ScrollView::GetMouseWheelScrollDistanceStep() const
1158 return mMouseWheelScrollDistanceStep;
1161 unsigned int ScrollView::GetCurrentPage() const
1163 // in case animation is currently taking place.
1164 Vector3 position = GetPropertyPosition();
1166 Actor self = Self();
1167 unsigned int page = 0;
1168 unsigned int pagesPerVolume = 1;
1169 unsigned int volume = 0;
1171 // if rulerX is enabled, then get page count (columns)
1172 page = mRulerX->GetPageFromPosition(-position.x, mWrapMode);
1173 volume = mRulerY->GetPageFromPosition(-position.y, mWrapMode);
1174 pagesPerVolume = mRulerX->GetTotalPages();
1176 return volume * pagesPerVolume + page;
1179 Vector3 ScrollView::GetCurrentScrollPosition() const
1181 return -GetPropertyPosition();
1184 void ScrollView::SetScrollPosition(const Vector3& position)
1186 mScrollPrePosition = position;
1189 Vector3 ScrollView::GetCurrentScrollScale() const
1191 // in case animation is currently taking place.
1192 return GetPropertyScale();
1195 Vector3 ScrollView::GetDomainSize() const
1197 Vector3 size = Self().GetCurrentSize();
1199 const RulerDomain& xDomain = GetRulerX()->GetDomain();
1200 const RulerDomain& yDomain = GetRulerY()->GetDomain();
1202 Vector3 domainSize = Vector3( xDomain.max - xDomain.min, yDomain.max - yDomain.min, 0.0f ) - size;
1206 void ScrollView::TransformTo(const Vector3& position, const Vector3& scale, float rotation,
1207 DirectionBias horizontalBias, DirectionBias verticalBias)
1209 TransformTo(position, scale, rotation, mSnapDuration, horizontalBias, verticalBias);
1212 void ScrollView::TransformTo(const Vector3& position, const Vector3& scale, float rotation, float duration,
1213 DirectionBias horizontalBias, DirectionBias verticalBias)
1215 // Guard against destruction during signal emission
1216 // Note that Emit() methods are called indirectly e.g. from within ScrollView::AnimateTo()
1217 Toolkit::ScrollView handle( GetOwner() );
1219 Vector3 currentScrollPosition = GetCurrentScrollPosition();
1220 Self().SetProperty( mPropertyScrollStartPagePosition, currentScrollPosition );
1222 if(mScrolling) // are we interrupting a current scroll?
1224 // set mScrolling to false, in case user has code that interrogates mScrolling Getter() in complete.
1226 mScrollCompletedSignalV2.Emit( currentScrollPosition );
1229 Self().SetProperty(mPropertyScrolling, true);
1231 mScrollStartedSignalV2.Emit( currentScrollPosition );
1232 bool animating = AnimateTo(-position,
1233 Vector3::ONE * duration,
1235 Vector3::ONE * duration,
1246 // if not animating, then this pan has completed right now.
1247 Self().SetProperty(mPropertyScrolling, false);
1249 mScrollCompletedSignalV2.Emit( currentScrollPosition );
1253 void ScrollView::ScrollTo(const Vector3& position)
1255 ScrollTo(position, mSnapDuration );
1258 void ScrollView::ScrollTo(const Vector3& position, float duration)
1260 ScrollTo(position, duration, DirectionBiasNone, DirectionBiasNone);
1263 void ScrollView::ScrollTo(const Vector3& position, float duration,
1264 DirectionBias horizontalBias, DirectionBias verticalBias)
1266 TransformTo(position, mScrollPostScale, mScrollPostRotation, duration, horizontalBias, verticalBias);
1269 void ScrollView::ScrollTo(unsigned int page)
1271 ScrollTo(page, mSnapDuration);
1274 void ScrollView::ScrollTo(unsigned int page, float duration, DirectionBias bias)
1277 unsigned int volume;
1278 unsigned int libraries;
1280 // The position to scroll to is continuous and linear
1281 // unless a domain has been enabled on the X axis.
1282 // or if WrapMode has been enabled.
1283 bool carryX = mRulerX->GetDomain().enabled | mWrapMode;
1284 bool carryY = mRulerY->GetDomain().enabled | mWrapMode;
1286 position.x = mRulerX->GetPositionFromPage(page, volume, carryX);
1287 position.y = mRulerY->GetPositionFromPage(volume, libraries, carryY);
1289 ScrollTo(position, duration, bias, bias);
1292 void ScrollView::ScrollTo(Actor &actor)
1294 ScrollTo(actor, mSnapDuration);
1297 void ScrollView::ScrollTo(Actor &actor, float duration)
1299 DALI_ASSERT_ALWAYS(actor.GetParent() == Self());
1301 Actor self = Self();
1302 Vector3 size = self.GetCurrentSize();
1303 Vector3 position = actor.GetCurrentPosition();
1304 position -= GetPropertyPrePosition();
1306 ScrollTo(Vector3(position.x - size.width * 0.5f, position.y - size.height * 0.5f, 0.0f), duration);
1309 Actor ScrollView::FindClosestActor()
1311 Actor self = Self();
1312 Vector3 size = self.GetCurrentSize();
1314 return FindClosestActorToPosition(Vector3(size.width * 0.5f,size.height * 0.5f,0.0f));
1317 Actor ScrollView::FindClosestActorToPosition(const Vector3& position, FindDirection dirX, FindDirection dirY, FindDirection dirZ)
1320 float closestDistance2 = 0.0f;
1321 Vector3 actualPosition = position;
1323 unsigned int numChildren = Self().GetChildCount();
1325 for(unsigned int i = 0; i < numChildren; ++i)
1327 Actor child = Self().GetChildAt(i);
1329 if(mInternalActor == child) // ignore internal actor.
1334 Vector3 childPosition = GetPositionOfAnchor(child, AnchorPoint::CENTER);
1336 Vector3 delta = childPosition - actualPosition;
1338 // X-axis checking (only find Actors to the [dirX] of actualPosition)
1339 if(dirX > All) // != All,None
1341 FindDirection deltaH = delta.x > 0 ? Right : Left;
1348 // Y-axis checking (only find Actors to the [dirY] of actualPosition)
1349 if(dirY > All) // != All,None
1351 FindDirection deltaV = delta.y > 0 ? Down : Up;
1358 // Z-axis checking (only find Actors to the [dirZ] of actualPosition)
1359 if(dirZ > All) // != All,None
1361 FindDirection deltaV = delta.y > 0 ? In : Out;
1368 // compare child to closest child in terms of distance.
1369 float distance2 = 0.0f;
1371 // distance2 = the Square of the relevant dimensions of delta
1374 distance2 += delta.x * delta.x;
1379 distance2 += delta.y * delta.y;
1384 distance2 += delta.z * delta.z;
1387 if(closestChild) // Next time.
1389 if(distance2 < closestDistance2)
1391 closestChild = child;
1392 closestDistance2 = distance2;
1397 closestChild = child;
1398 closestDistance2 = distance2;
1402 return closestChild;
1405 bool ScrollView::ScrollToSnapPoint()
1407 Vector2 stationaryVelocity = Vector2(0.0f, 0.0f);
1408 return SnapWithVelocity( stationaryVelocity );
1411 void ScrollView::ScaleTo(const Vector3& scale)
1413 ScaleTo(scale, mSnapDuration);
1416 void ScrollView::ScaleTo(const Vector3& scale, float duration)
1418 TransformTo(mScrollPostPosition, scale, mScrollPostRotation, duration);
1422 // TODO: In situations where axes are different (X snap, Y free)
1423 // Each axis should really have their own independent animation (time and equation)
1424 // Consider, X axis snapping to nearest grid point (EaseOut over fixed time)
1425 // Consider, Y axis simulating physics to arrive at a point (Physics equation over variable time)
1426 // Currently, the axes have been split however, they both use the same EaseOut equation.
1427 bool ScrollView::SnapWithVelocity(Vector2 velocity)
1429 // Animator takes over now, touches are assumed not to interfere.
1430 // And if touches do interfere, then we'll stop animation, update PrePosition
1431 // to current mScroll's properties, and then resume.
1432 // Note: For Flicking this may work a bit different...
1434 float angle = atan2(velocity.y, velocity.x);
1435 float speed2 = velocity.LengthSquared();
1436 AlphaFunction alphaFunction = mSnapAlphaFunction;
1437 Vector3 positionDuration = Vector3::ONE * mSnapDuration;
1438 Vector3 scaleDuration = Vector3::ONE * mSnapDuration;
1439 float rotationDuration = mSnapDuration;
1442 FindDirection horizontal = None;
1443 FindDirection vertical = None;
1445 // orthoAngleRange = Angle tolerance within the Exact N,E,S,W direction
1446 // that will be accepted as a general N,E,S,W flick direction.
1448 const float orthoAngleRange = FLICK_ORTHO_ANGLE_RANGE * M_PI / 180.0f;
1449 const float flickSpeedThreshold2 = FLICK_SPEED_THRESHOLD*FLICK_SPEED_THRESHOLD;
1451 Vector3 positionSnap = mScrollPrePosition;
1453 // Flick logic X Axis
1455 if(mRulerX->IsEnabled() && mLockAxis != LockHorizontal)
1459 if( speed2 > flickSpeedThreshold2 || // exceeds flick threshold
1460 mInAccessibilityPan ) // With AccessibilityPan its easier to move between snap positions
1462 if((angle >= -orthoAngleRange) && (angle < orthoAngleRange)) // Swiping East
1464 biasX = 0.0f, horizontal = Left;
1466 // This guards against an error where no movement occurs, due to the flick finishing
1467 // before the update-thread has advanced mScrollPostPosition past the the previous snap point.
1468 positionSnap.x += 1.0f;
1470 else if((angle >= M_PI-orthoAngleRange) || (angle < -M_PI+orthoAngleRange)) // Swiping West
1472 biasX = 1.0f, horizontal = Right;
1474 // This guards against an error where no movement occurs, due to the flick finishing
1475 // before the update-thread has advanced mScrollPostPosition past the the previous snap point.
1476 positionSnap.x -= 1.0f;
1481 // Flick logic Y Axis
1483 if(mRulerY->IsEnabled() && mLockAxis != LockVertical)
1487 if( speed2 > flickSpeedThreshold2 || // exceeds flick threshold
1488 mInAccessibilityPan ) // With AccessibilityPan its easier to move between snap positions
1490 if((angle >= M_PI_2-orthoAngleRange) && (angle < M_PI_2+orthoAngleRange)) // Swiping South
1492 biasY = 0.0f, vertical = Up;
1494 else if((angle >= -M_PI_2-orthoAngleRange) && (angle < -M_PI_2+orthoAngleRange)) // Swiping North
1496 biasY = 1.0f, vertical = Down;
1501 // isFlick: Whether this gesture is a flick or not.
1502 bool isFlick = (horizontal != All || vertical != All);
1503 // isFreeFlick: Whether this gesture is a flick under free panning criteria.
1504 bool isFreeFlick = velocity.LengthSquared() > (FREE_FLICK_SPEED_THRESHOLD*FREE_FLICK_SPEED_THRESHOLD);
1506 if(isFlick || isFreeFlick)
1508 positionDuration = Vector3::ONE * mFlickDuration;
1509 alphaFunction = mFlickAlphaFunction;
1512 // Calculate next positionSnap ////////////////////////////////////////////////////////////
1514 if(mActorAutoSnapEnabled)
1516 Vector3 size = Self().GetCurrentSize();
1518 Actor child = FindClosestActorToPosition( Vector3(size.width * 0.5f,size.height * 0.5f,0.0f), horizontal, vertical );
1520 if(!child && isFlick )
1522 // If we conducted a direction limited search and found no actor, then just snap to the closest actor.
1523 child = FindClosestActorToPosition( Vector3(size.width * 0.5f,size.height * 0.5f,0.0f) );
1528 Vector3 position = Self().GetProperty<Vector3>(mPropertyPosition);
1530 // Get center-point of the Actor.
1531 Vector3 childPosition = GetPositionOfAnchor(child, AnchorPoint::CENTER);
1533 if(mRulerX->IsEnabled())
1535 positionSnap.x = position.x - childPosition.x + size.width * 0.5f;
1537 if(mRulerY->IsEnabled())
1539 positionSnap.y = position.y - childPosition.y + size.height * 0.5f;
1544 Vector3 startPosition = positionSnap;
1545 positionSnap.x = -mRulerX->Snap(-positionSnap.x, biasX); // NOTE: X & Y rulers think in -ve coordinate system.
1546 positionSnap.y = -mRulerY->Snap(-positionSnap.y, biasY); // That is scrolling RIGHT (e.g. 100.0, 0.0) means moving LEFT.
1548 Vector3 clampDelta(Vector3::ZERO);
1549 ClampPosition(positionSnap);
1551 if( (mRulerX->GetType() == Ruler::Free || mRulerY->GetType() == Ruler::Free)
1552 && isFreeFlick && !mActorAutoSnapEnabled)
1554 // Calculate target position based on velocity of flick.
1556 // a = Deceleration (Set to diagonal stage length * friction coefficient)
1557 // u = Initial Velocity (Flick velocity)
1558 // v = 0 (Final Velocity)
1559 // t = Time (Velocity / Deceleration)
1560 Vector2 stageSize = Stage::GetCurrent().GetSize();
1561 float stageLength = Vector3(stageSize.x, stageSize.y, 0.0f).Length();
1562 float a = (stageLength * mFrictionCoefficient);
1563 Vector3 u = Vector3(velocity.x, velocity.y, 0.0f) * mFlickSpeedCoefficient;
1564 float speed = u.Length();
1567 // TODO: Change this to a decay function. (faster you flick, the slower it should be)
1568 speed = std::min(speed, stageLength * mMaxFlickSpeed );
1570 alphaFunction = ConstantDecelerationAlphaFunction;
1572 float t = speed / a;
1574 if(mRulerX->IsEnabled() && mRulerX->GetType() == Ruler::Free)
1576 positionSnap.x += t*u.x*0.5f;
1579 if(mRulerY->IsEnabled() && mRulerY->GetType() == Ruler::Free)
1581 positionSnap.y += t*u.y*0.5f;
1584 clampDelta = positionSnap;
1585 ClampPosition(positionSnap);
1586 if((positionSnap - startPosition).LengthSquared() > Math::MACHINE_EPSILON_0)
1588 clampDelta -= positionSnap;
1589 clampDelta.x = clampDelta.x > 0.0f ? std::min(clampDelta.x, mMaxOvershoot.x) : std::max(clampDelta.x, -mMaxOvershoot.x);
1590 clampDelta.y = clampDelta.y > 0.0f ? std::min(clampDelta.y, mMaxOvershoot.y) : std::max(clampDelta.y, -mMaxOvershoot.y);
1594 clampDelta = Vector3::ZERO;
1597 // If Axis is Free and has velocity, then calculate time taken
1598 // to reach target based on velocity in axis.
1599 if(mRulerX->IsEnabled() && mRulerX->GetType() == Ruler::Free)
1601 float deltaX = fabsf(startPosition.x - positionSnap.x);
1603 if(fabsf(u.x) > Math::MACHINE_EPSILON_1)
1605 positionDuration.x = fabsf(deltaX / u.x);
1609 positionDuration.x = 0;
1613 if(mRulerY->IsEnabled() && mRulerY->GetType() == Ruler::Free)
1615 float deltaY = fabsf(startPosition.y - positionSnap.y);
1617 if(fabsf(u.y) > Math::MACHINE_EPSILON_1)
1619 positionDuration.y = fabsf(deltaY / u.y);
1623 positionDuration.y = 0;
1627 positionSnap += clampDelta;
1629 // Scale Snap ///////////////////////////////////////////////////////////////
1630 Vector3 scaleSnap = mScrollPostScale;
1632 scaleSnap.x = mRulerScaleX->Snap(scaleSnap.x);
1633 scaleSnap.y = mRulerScaleY->Snap(scaleSnap.y);
1635 ClampScale(scaleSnap);
1637 // Rotation Snap ////////////////////////////////////////////////////////////
1638 float rotationSnap = mScrollPostRotation;
1639 // TODO: implement rotation snap
1641 bool animating = AnimateTo(positionSnap, positionDuration,
1642 scaleSnap, scaleDuration,
1643 rotationSnap, rotationDuration,
1644 alphaFunction, false,
1645 DirectionBiasNone, DirectionBiasNone,
1646 isFlick || isFreeFlick ? Flick : Snap);
1651 void ScrollView::StopAnimation(void)
1653 // Clear Snap animation if exists.
1654 StopAnimation(mSnapAnimation);
1655 StopAnimation(mInternalXAnimation);
1656 StopAnimation(mInternalYAnimation);
1657 mScrollStateFlags = 0;
1658 // remove scroll animation flags
1659 HandleStoppedAnimation();
1662 void ScrollView::StopAnimation(Animation& animation)
1671 bool ScrollView::AnimateTo(const Vector3& position, const Vector3& positionDuration,
1672 const Vector3& scale, const Vector3& scaleDuration,
1673 float rotation, float rotationDuration,
1674 AlphaFunction alpha, bool findShortcuts,
1675 DirectionBias horizontalBias, DirectionBias verticalBias,
1678 // Here we perform an animation on a number of properties (depending on which have changed)
1679 // The animation is applied to all ScrollBases
1680 Actor self = Self();
1681 mScrollTargetPosition = position;
1682 float totalDuration = 0.0f;
1684 bool positionChanged = (mScrollTargetPosition != mScrollPostPosition);
1685 bool scaleChanged = (scale != mScrollPostScale);
1686 bool rotationChanged = fabsf(rotation - mScrollPostRotation) > Math::MACHINE_EPSILON_0;
1690 totalDuration = std::max(totalDuration, positionDuration.x);
1691 totalDuration = std::max(totalDuration, positionDuration.y);
1695 // try to animate for a frame, on some occasions update will be changing scroll value while event side thinks it hasnt changed
1696 totalDuration = 0.01f;
1697 positionChanged = true;
1702 totalDuration = std::max(totalDuration, scaleDuration.x);
1703 totalDuration = std::max(totalDuration, scaleDuration.y);
1708 totalDuration = std::max(totalDuration, rotationDuration);
1712 // Position Delta ///////////////////////////////////////////////////////
1715 if(mWrapMode && findShortcuts)
1717 // In Wrap Mode, the shortest distance is a little less intuitive...
1718 const RulerDomain rulerDomainX = mRulerX->GetDomain();
1719 const RulerDomain rulerDomainY = mRulerY->GetDomain();
1721 if(mRulerX->IsEnabled())
1723 float dir = VectorInDomain(-mScrollPostPosition.x, -mScrollTargetPosition.x, rulerDomainX.min, rulerDomainX.max, horizontalBias);
1724 mScrollTargetPosition.x = mScrollPostPosition.x + -dir;
1727 if(mRulerY->IsEnabled())
1729 float dir = VectorInDomain(-mScrollPostPosition.y, -mScrollTargetPosition.y, rulerDomainY.min, rulerDomainY.max, verticalBias);
1730 mScrollTargetPosition.y = mScrollPostPosition.y + -dir;
1734 // note we have two separate animations for X & Y, this deals with sliding diagonally and hitting
1735 // a horizonal/vertical wall.delay
1736 AnimateInternalXTo(mScrollTargetPosition.x, positionDuration.x, alpha);
1737 AnimateInternalYTo(mScrollTargetPosition.y, positionDuration.y, alpha);
1739 if( !(mScrollStateFlags & SCROLL_ANIMATION_FLAGS) )
1741 self.SetProperty(mPropertyPrePosition, mScrollTargetPosition);
1742 mScrollPrePosition = mScrollTargetPosition;
1746 // Scale Delta ///////////////////////////////////////////////////////
1749 if(totalDuration > Math::MACHINE_EPSILON_1)
1751 mSnapAnimation = Animation::New(totalDuration);
1752 mSnapAnimation.FinishedSignal().Connect(this, &ScrollView::OnScrollAnimationFinished);
1753 // TODO: for non-uniform scaling to different bounds e.g. scaling a square to a 4:3 aspect ratio screen with a velocity
1754 // the height will hit first, and then the width, so that would require two different animation times just like position.
1755 mSnapAnimation.AnimateTo( Property(self, mPropertyScale), scale, alpha, TimePeriod(0.0f, scaleDuration.x));
1757 mSnapAnimation.AnimateTo( Property(self, mPropertyTime), totalDuration, AlphaFunctions::Linear );
1758 mSnapAnimation.Play();
1762 self.SetProperty(mPropertyScale, scale);
1764 mScrollPreScale = mScrollPostScale = scale;
1767 StartRefreshTimer();
1769 // Always send a snap event when AnimateTo is called.
1770 Toolkit::ScrollView::SnapEvent snapEvent;
1771 snapEvent.type = snapType;
1772 snapEvent.position = -mScrollTargetPosition;
1773 snapEvent.scale = scale;
1774 snapEvent.rotation = rotation;
1775 snapEvent.duration = totalDuration;
1777 mSnapStartedSignalV2.Emit( snapEvent );
1779 return (mScrollStateFlags & SCROLL_ANIMATION_FLAGS) != 0;
1782 void ScrollView::SetOvershootEnabled(bool enabled)
1784 if(enabled && !mOvershootIndicator)
1786 mOvershootIndicator = ScrollOvershootIndicator::New();
1790 mMaxOvershoot = OVERSCROLL_CLAMP;
1791 mOvershootIndicator->AttachToScrollable(*this);
1795 mMaxOvershoot = mUserMaxOvershoot;
1796 mOvershootIndicator->DetachFromScrollable(*this);
1798 UpdateMainInternalConstraint();
1801 void ScrollView::AddOverlay(Actor actor)
1803 mInternalActor.Add( actor );
1806 void ScrollView::RemoveOverlay(Actor actor)
1808 mInternalActor.Remove( actor );
1811 void ScrollView::SetScrollingDirection( Radian direction, Radian threshold )
1813 PanGestureDetector panGesture( GetPanGestureDetector() );
1815 // First remove just in case we have some set, then add.
1816 panGesture.RemoveDirection( direction );
1817 panGesture.AddDirection( direction, threshold );
1820 void ScrollView::RemoveScrollingDirection( Radian direction )
1822 PanGestureDetector panGesture( GetPanGestureDetector() );
1823 panGesture.RemoveDirection( direction );
1826 Toolkit::ScrollView::SnapStartedSignalV2& ScrollView::SnapStartedSignal()
1828 return mSnapStartedSignalV2;
1831 void ScrollView::FindAndUnbindActor(Actor child)
1836 Vector3 ScrollView::GetPropertyPrePosition() const
1838 Vector3 position = Self().GetProperty<Vector3>(mPropertyPrePosition);
1839 WrapPosition(position);
1843 Vector3 ScrollView::GetPropertyPosition() const
1845 Vector3 position = Self().GetProperty<Vector3>(mPropertyPosition);
1846 WrapPosition(position);
1851 Vector3 ScrollView::GetPropertyScale() const
1853 return Self().GetProperty<Vector3>(mPropertyScale);
1856 void ScrollView::HandleStoppedAnimation()
1858 // Animation has stopped, so stop sending the scroll-update signal.
1859 CancelRefreshTimer();
1862 void ScrollView::HandleSnapAnimationFinished()
1864 // Emit Signal that scrolling has completed.
1866 Actor self = Self();
1867 self.SetProperty(mPropertyScrolling, false);
1869 Vector3 deltaPosition(mScrollPrePosition);
1871 UpdateLocalScrollProperties();
1872 WrapPosition(mScrollPrePosition);
1873 self.SetProperty(mPropertyPrePosition, mScrollPrePosition);
1875 Vector3 currentScrollPosition = GetCurrentScrollPosition();
1876 mScrollCompletedSignalV2.Emit( currentScrollPosition );
1878 mDomainOffset += deltaPosition - mScrollPostPosition;
1879 self.SetProperty(mPropertyDomainOffset, mDomainOffset);
1880 HandleStoppedAnimation();
1883 bool ScrollView::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
1885 Dali::BaseHandle handle( object );
1887 bool connected( true );
1888 Toolkit::ScrollView view = Toolkit::ScrollView::DownCast( handle );
1890 if( Toolkit::ScrollView::SIGNAL_SNAP_STARTED == signalName )
1892 view.SnapStartedSignal().Connect( tracker, functor );
1896 // signalName does not match any signal
1903 void ScrollView::OnSizeAnimation(Animation& animation, const Vector3& targetSize)
1905 // need to update domain properties for new size
1906 UpdatePropertyDomain(targetSize);
1909 void ScrollView::OnControlSizeSet( const Vector3& size )
1911 // need to update domain properties for new size
1912 if( mDefaultMaxOvershoot )
1914 mUserMaxOvershoot.x = size.x * 0.5f;
1915 mUserMaxOvershoot.y = size.y * 0.5f;
1916 if( !IsScrollComponentEnabled(Toolkit::Scrollable::OvershootIndicator) )
1918 mMaxOvershoot = mUserMaxOvershoot;
1921 UpdatePropertyDomain(size);
1922 UpdateMainInternalConstraint();
1923 if( IsScrollComponentEnabled(Toolkit::Scrollable::OvershootIndicator) )
1925 mOvershootIndicator->Reset();
1929 void ScrollView::OnChildAdd(Actor& child)
1937 void ScrollView::OnChildRemove(Actor& child)
1939 // TODO: Actor needs a RemoveConstraint method to take out an individual constraint.
1943 void ScrollView::OnPropertySet( Property::Index index, Property::Value propertyValue )
1945 Actor self = Self();
1946 if( index == mPropertyX )
1948 self.GetProperty(mPropertyPrePosition).Get(mScrollPrePosition);
1949 propertyValue.Get(mScrollPrePosition.x);
1950 self.SetProperty(mPropertyPrePosition, mScrollPrePosition);
1952 else if( index == mPropertyY )
1954 self.GetProperty(mPropertyPrePosition).Get(mScrollPrePosition);
1955 propertyValue.Get(mScrollPrePosition.y);
1956 self.SetProperty(mPropertyPrePosition, mScrollPrePosition);
1958 else if( index == mPropertyPrePosition )
1960 propertyValue.Get(mScrollPrePosition);
1964 void ScrollView::StartTouchDownTimer()
1966 if ( !mTouchDownTimer )
1968 mTouchDownTimer = Timer::New( TOUCH_DOWN_TIMER_INTERVAL );
1969 mTouchDownTimer.TickSignal().Connect( this, &ScrollView::OnTouchDownTimeout );
1972 mTouchDownTimer.Start();
1975 void ScrollView::StopTouchDownTimer()
1977 if ( mTouchDownTimer )
1979 mTouchDownTimer.Stop();
1983 bool ScrollView::OnTouchDownTimeout()
1985 mTouchDownTimeoutReached = true;
1987 if( mScrollStateFlags & (SCROLL_ANIMATION_FLAGS | SNAP_ANIMATION_FLAGS) )
1990 if( mScrollStateFlags & SCROLL_ANIMATION_FLAGS )
1992 mScrollInterrupted = true;
1993 // reset domain offset as scrolling from original plane.
1994 mDomainOffset = Vector3::ZERO;
1995 Self().SetProperty(mPropertyDomainOffset, Vector3::ZERO);
1997 UpdateLocalScrollProperties();
1998 Vector3 currentScrollPosition = GetCurrentScrollPosition();
1999 mScrollCompletedSignalV2.Emit( currentScrollPosition );
2006 bool ScrollView::OnTouchEvent(const TouchEvent& event)
2010 // Ignore this touch event, if scrollview is insensitive.
2014 // Ignore events with multiple-touch points
2015 if (event.GetPointCount() != 1)
2020 if( event.GetPoint(0).state == TouchPoint::Down )
2022 if(mGestureStackDepth==0)
2024 mTouchDownTime = event.time;
2026 // This allows time for a pan-gesture to start, to avoid breaking snap-animation behavior with fast flicks.
2027 // If touch-down does not become a pan (after timeout interval), then snap-animation can be interrupted.
2028 StartTouchDownTimer();
2031 else if( event.GetPoint(0).state == TouchPoint::Up )
2033 StopTouchDownTimer();
2035 // if the user touches and releases without enough movement to go
2036 // into a gesture state, then we should snap to nearest point.
2037 // otherwise our scroll could be stopped (interrupted) half way through an animation.
2038 if(mGestureStackDepth==0 && mTouchDownTimeoutReached)
2040 unsigned timeDelta( event.time - mTouchDownTime );
2041 if ( timeDelta >= MINIMUM_TIME_BETWEEN_DOWN_AND_UP_FOR_RESET )
2043 // Reset the velocity only if down was received a while ago
2044 mLastVelocity = Vector2( 0.0f, 0.0f );
2047 UpdateLocalScrollProperties();
2048 // Only finish the transform if scrolling was interrupted on down or if we are scrolling
2049 if ( mScrollInterrupted || mScrolling )
2054 mTouchDownTimeoutReached = false;
2055 mScrollInterrupted = false;
2061 bool ScrollView::OnMouseWheelEvent(const MouseWheelEvent& event)
2065 // Ignore this mouse wheel event, if scrollview is insensitive.
2069 Vector3 targetScrollPosition = GetPropertyPosition();
2071 if(mRulerX->IsEnabled() && !mRulerY->IsEnabled())
2073 // If only the ruler in the X axis is enabled, scroll in the X axis.
2074 if(mRulerX->GetType() == Ruler::Free)
2076 // Free panning mode
2077 targetScrollPosition.x += event.z * mMouseWheelScrollDistanceStep.x;
2078 ClampPosition(targetScrollPosition);
2079 ScrollTo(-targetScrollPosition);
2081 else if(!mScrolling)
2083 // Snap mode, only respond to the event when the previous snap animation is finished.
2084 ScrollTo(GetCurrentPage() - event.z);
2089 // If the ruler in the Y axis is enabled, scroll in the Y axis.
2090 if(mRulerY->GetType() == Ruler::Free)
2092 // Free panning mode
2093 targetScrollPosition.y += event.z * mMouseWheelScrollDistanceStep.y;
2094 ClampPosition(targetScrollPosition);
2095 ScrollTo(-targetScrollPosition);
2097 else if(!mScrolling)
2099 // Snap mode, only respond to the event when the previous snap animation is finished.
2100 ScrollTo(GetCurrentPage() - event.z * mRulerX->GetTotalPages());
2107 void ScrollView::ResetScrolling()
2109 Actor self = Self();
2110 self.GetProperty(mPropertyPosition).Get(mScrollPostPosition);
2111 mScrollPrePosition = mScrollPostPosition;
2112 self.SetProperty(mPropertyPrePosition, mScrollPostPosition);
2115 void ScrollView::UpdateLocalScrollProperties()
2117 Actor self = Self();
2118 self.GetProperty(mPropertyPrePosition).Get(mScrollPrePosition);
2119 self.GetProperty(mPropertyPosition).Get(mScrollPostPosition);
2122 // private functions
2124 void ScrollView::PreAnimatedScrollSetup()
2126 // mPropertyPrePosition is our unclamped property with wrapping
2127 // mPropertyPosition is our final scroll position after clamping
2129 Actor self = Self();
2131 Vector3 deltaPosition(mScrollPostPosition);
2132 WrapPosition(mScrollPostPosition);
2133 mDomainOffset += deltaPosition - mScrollPostPosition;
2134 Self().SetProperty(mPropertyDomainOffset, mDomainOffset);
2136 if( mScrollStateFlags & SCROLL_X_STATE_MASK )
2138 // already performing animation on internal x position
2139 StopAnimation(mInternalXAnimation);
2142 if( mScrollStateFlags & SCROLL_Y_STATE_MASK )
2144 // already performing animation on internal y position
2145 StopAnimation(mInternalYAnimation);
2148 mScrollStateFlags = 0;
2150 mScrollPostScale = GetPropertyScale();
2152 // Update Actor position with this wrapped value.
2155 mScrollPreScale = mScrollPostScale;
2156 mScrollPreRotation = mScrollPostRotation;
2159 void ScrollView::FinaliseAnimatedScroll()
2161 // TODO - common animation finishing code in here
2164 void ScrollView::AnimateInternalXTo( float position, float duration, AlphaFunction alpha )
2166 StopAnimation(mInternalXAnimation);
2168 if( duration > Math::MACHINE_EPSILON_10 )
2170 Actor self = Self();
2171 mInternalXAnimation = Animation::New(duration);
2172 mInternalXAnimation.FinishedSignal().Connect(this, &ScrollView::OnScrollAnimationFinished);
2173 mInternalXAnimation.AnimateTo( Property(self, mPropertyPrePosition, 0), position, alpha, duration);
2174 mInternalXAnimation.Play();
2176 // erase current state flags
2177 mScrollStateFlags &= ~SCROLL_X_STATE_MASK;
2178 // add internal animation state flag
2179 mScrollStateFlags |= AnimatingInternalX;
2183 void ScrollView::AnimateInternalYTo( float position, float duration, AlphaFunction alpha )
2185 StopAnimation(mInternalYAnimation);
2187 if( duration > Math::MACHINE_EPSILON_10 )
2189 Actor self = Self();
2190 mInternalYAnimation = Animation::New(duration);
2191 mInternalYAnimation.FinishedSignal().Connect(this, &ScrollView::OnScrollAnimationFinished);
2192 mInternalYAnimation.AnimateTo( Property(self, mPropertyPrePosition, 1), position, alpha, TimePeriod(duration));
2193 mInternalYAnimation.Play();
2195 // erase current state flags
2196 mScrollStateFlags &= ~SCROLL_Y_STATE_MASK;
2197 // add internal animation state flag
2198 mScrollStateFlags |= AnimatingInternalY;
2202 void ScrollView::OnScrollAnimationFinished( Animation& source )
2204 // Guard against destruction during signal emission
2205 // Note that ScrollCompletedSignal is emitted from HandleSnapAnimationFinished()
2206 Toolkit::ScrollView handle( GetOwner() );
2208 bool scrollingFinished = false;
2210 // update our local scroll positions
2211 UpdateLocalScrollProperties();
2213 if( source == mSnapAnimation )
2215 // generic snap animation used for scaling and rotation
2216 mSnapAnimation.Reset();
2219 if( source == mInternalXAnimation )
2221 if( !(mScrollStateFlags & AnimatingInternalY) )
2223 scrollingFinished = true;
2225 mInternalXAnimation.Reset();
2226 SnapInternalXTo(mScrollPostPosition.x);
2229 if( source == mInternalYAnimation )
2231 if( !(mScrollStateFlags & AnimatingInternalX) )
2233 scrollingFinished = true;
2235 mInternalYAnimation.Reset();
2236 SnapInternalYTo(mScrollPostPosition.y);
2239 if(scrollingFinished)
2241 HandleSnapAnimationFinished();
2245 void ScrollView::OnSnapInternalPositionFinished( Animation& source )
2247 Actor self = Self();
2248 UpdateLocalScrollProperties();
2249 if( source == mInternalXAnimation )
2251 // clear internal x animation flags
2252 mScrollStateFlags &= ~SCROLL_X_STATE_MASK;
2253 mInternalXAnimation.Reset();
2254 WrapPosition(mScrollPrePosition);
2256 if( source == mInternalYAnimation )
2258 mScrollStateFlags &= ~SCROLL_Y_STATE_MASK;
2259 mInternalYAnimation.Reset();
2260 WrapPosition(mScrollPrePosition);
2264 void ScrollView::SnapInternalXTo(float position)
2266 Actor self = Self();
2268 StopAnimation(mInternalXAnimation);
2270 // erase current state flags
2271 mScrollStateFlags &= ~SCROLL_X_STATE_MASK;
2273 // if internal x not equal to inputed parameter, animate it
2274 float duration = std::min(fabsf((position - mScrollPrePosition.x) / mMaxOvershoot.x) * mSnapOvershootDuration, mSnapOvershootDuration);
2275 if( duration > Math::MACHINE_EPSILON_1 )
2277 mInternalXAnimation = Animation::New(duration);
2278 mInternalXAnimation.FinishedSignal().Connect(this, &ScrollView::OnSnapInternalPositionFinished);
2279 mInternalXAnimation.AnimateTo(Property(self, mPropertyPrePosition, 0), position);
2280 mInternalXAnimation.Play();
2282 // add internal animation state flag
2283 mScrollStateFlags |= SnappingInternalX;
2287 void ScrollView::SnapInternalYTo(float position)
2289 Actor self = Self();
2291 StopAnimation(mInternalYAnimation);
2293 // erase current state flags
2294 mScrollStateFlags &= ~SCROLL_Y_STATE_MASK;
2296 // if internal y not equal to inputed parameter, animate it
2297 float duration = std::min(fabsf((position - mScrollPrePosition.y) / mMaxOvershoot.y) * mSnapOvershootDuration, mSnapOvershootDuration);
2298 if( duration > Math::MACHINE_EPSILON_1 )
2300 mInternalYAnimation = Animation::New(duration);
2301 mInternalYAnimation.FinishedSignal().Connect(this, &ScrollView::OnSnapInternalPositionFinished);
2302 mInternalYAnimation.AnimateTo(Property(self, mPropertyPrePosition, 1), position);
2303 mInternalYAnimation.Play();
2305 // add internal animation state flag
2306 mScrollStateFlags |= SnappingInternalY;
2310 void ScrollView::GestureStarted()
2312 // we handle the first gesture.
2313 // if we're currently doing a gesture and receive another
2314 // we continue and combine the effects of the gesture instead of reseting.
2315 if(mGestureStackDepth++==0)
2317 Actor self = Self();
2318 StopTouchDownTimer();
2320 mPanDelta = Vector3::ZERO;
2321 mScaleDelta = Vector3::ONE;
2322 mRotationDelta = 0.0f;
2323 mLastVelocity = Vector2(0.0f, 0.0f);
2326 mLockAxis = LockPossible;
2329 if( mScrollStateFlags & SCROLL_X_STATE_MASK )
2331 StopAnimation(mInternalXAnimation);
2333 if( mScrollStateFlags & SCROLL_Y_STATE_MASK )
2335 StopAnimation(mInternalYAnimation);
2337 mScrollStateFlags = 0;
2339 if(mScrolling) // are we interrupting a current scroll?
2341 // set mScrolling to false, in case user has code that interrogates mScrolling Getter() in complete.
2343 // send negative scroll position since scroll internal scroll position works as an offset for actors,
2344 // give applications the position within the domain from the scroll view's anchor position
2345 mScrollCompletedSignalV2.Emit( -mScrollPostPosition );
2350 void ScrollView::GestureContinuing(const Vector2& panDelta, const Vector2& scaleDelta, float rotationDelta)
2352 mPanDelta.x+= panDelta.x;
2353 mPanDelta.y+= panDelta.y;
2354 mScaleDelta.x*= scaleDelta.x;
2355 mScaleDelta.y*= scaleDelta.y;
2356 mRotationDelta+= rotationDelta;
2358 // Save the velocity, there is a bug in PanGesture
2359 // Whereby the Gesture::Finished's velocity is either:
2360 // NaN (due to time delta of zero between the last two events)
2361 // or 0 (due to position being the same between the last two events)
2363 // Axis Auto Lock - locks the panning to the horizontal or vertical axis if the pan
2364 // appears mostly horizontal or mostly vertical respectively.
2367 mLockAxis = GetLockAxis(mPanDelta.GetVectorXY(), mLockAxis, mAxisAutoLockGradient);
2368 } // end if mAxisAutoLock
2371 // TODO: Upgrade to use a more powerful gesture detector (one that supports multiple touches on pan - so works as pan and flick gesture)
2372 // TODO: Reimplement Scaling (pinching 2+ points)
2373 // TODO: Reimplment Rotation (pinching 2+ points)
2374 // BUG: Gesture::Finished doesn't always return velocity on release (due to
2375 // timeDelta between last two events being 0 sometimes, or posiiton being the same)
2376 void ScrollView::OnPan(PanGesture gesture)
2378 // Guard against destruction during signal emission
2379 // Note that Emit() methods are called indirectly e.g. from within ScrollView::OnGestureEx()
2380 Actor self( Self() );
2384 // If another callback on the same original signal disables sensitivity,
2385 // this callback will still be called, so we must suppress it.
2389 // translate Gesture input to get useful data...
2390 switch(gesture.state)
2392 case Gesture::Started:
2394 UpdateLocalScrollProperties();
2397 self.SetProperty( mPropertyPanning, true );
2398 self.SetProperty( mPropertyScrollStartPagePosition, Vector3(gesture.position.x, gesture.position.y, 0.0f) );
2400 UpdateMainInternalConstraint();
2404 case Gesture::Continuing:
2406 GestureContinuing(gesture.screenDisplacement, Vector2::ZERO, 0.0f);
2410 case Gesture::Finished:
2411 case Gesture::Cancelled:
2413 UpdateLocalScrollProperties();
2414 mLastVelocity = gesture.velocity;
2416 self.SetProperty( mPropertyPanning, false );
2418 if( mScrollMainInternalPrePositionConstraint )
2420 self.RemoveConstraint(mScrollMainInternalPrePositionConstraint);
2425 case Gesture::Possible:
2426 case Gesture::Clear:
2428 // Nothing to do, not needed.
2432 } // end switch(gesture.state)
2434 OnGestureEx(gesture.state);
2437 void ScrollView::OnGestureEx(Gesture::State state)
2439 // call necessary signals for application developer
2441 if(state == Gesture::Started)
2443 Vector3 currentScrollPosition = GetCurrentScrollPosition();
2444 Self().SetProperty(mPropertyScrolling, true);
2446 mScrollStartedSignalV2.Emit( currentScrollPosition );
2448 else if( (state == Gesture::Finished) ||
2449 (state == Gesture::Cancelled) ) // Finished/default
2451 // when all the gestures have finished, we finish the transform.
2452 // so if a user decides to pan (1 gesture), and then pan+zoom (2 gestures)
2453 // then stop panning (back to 1 gesture), and then stop zooming (0 gestures).
2454 // this is the point we end, and perform necessary snapping.
2455 mGestureStackDepth--;
2456 if(mGestureStackDepth==0)
2463 void ScrollView::UpdateTransform()
2465 // TODO: notify clamps using property notifications (or see if we need this, can deprecate it)
2468 void ScrollView::FinishTransform()
2470 // at this stage internal x and x scroll position should have followed prescroll position exactly
2471 Actor self = Self();
2473 PreAnimatedScrollSetup();
2475 bool animating = SnapWithVelocity(mLastVelocity * 1000.0f);
2479 // if not animating, then this pan has completed right now.
2481 Self().SetProperty(mPropertyScrolling, false);
2482 Vector3 currentScrollPosition = GetCurrentScrollPosition();
2483 mScrollCompletedSignalV2.Emit( currentScrollPosition );
2487 Vector3 ScrollView::GetOvershoot(Vector3& position) const
2489 Vector3 size = Self().GetCurrentSize();
2492 const RulerDomain rulerDomainX = mRulerX->GetDomain();
2493 const RulerDomain rulerDomainY = mRulerY->GetDomain();
2495 if(mRulerX->IsEnabled() && rulerDomainX.enabled)
2497 const float left = rulerDomainX.min - position.x;
2498 const float right = size.width - rulerDomainX.max - position.x;
2505 overshoot.x = right;
2509 if(mRulerY->IsEnabled() && rulerDomainY.enabled)
2511 const float top = rulerDomainY.min - position.y;
2512 const float bottom = size.height - rulerDomainY.max - position.y;
2519 overshoot.y = bottom;
2526 bool ScrollView::OnAccessibilityPan(PanGesture gesture)
2528 // Keep track of whether this is an AccessibilityPan
2529 mInAccessibilityPan = true;
2531 mInAccessibilityPan = false;
2536 void ScrollView::ClampPosition(Vector3& position) const
2538 ClampState3 clamped;
2539 ClampPosition(position, clamped);
2542 void ScrollView::ClampPosition(Vector3& position, ClampState3 &clamped) const
2544 Vector3 size = Self().GetCurrentSize();
2546 // determine size of viewport relative to current scaled size.
2547 // e.g. if you're zoomed in 200%, then each pixel on screen is only 0.5 pixels on subject.
2548 if(fabsf(mScrollPostScale.x) > Math::MACHINE_EPSILON_0)
2550 size.x /= mScrollPostScale.x;
2553 if(fabsf(mScrollPostScale.y) > Math::MACHINE_EPSILON_0)
2555 size.y /= mScrollPostScale.y;
2558 position.x = -mRulerX->Clamp(-position.x, size.width, 1.0f, clamped.x); // NOTE: X & Y rulers think in -ve coordinate system.
2559 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.
2561 clamped.z = NotClamped;
2564 void ScrollView::WrapPosition(Vector3& position) const
2568 const RulerDomain rulerDomainX = mRulerX->GetDomain();
2569 const RulerDomain rulerDomainY = mRulerY->GetDomain();
2571 if(mRulerX->IsEnabled())
2573 position.x = -WrapInDomain(-position.x, rulerDomainX.min, rulerDomainX.max);
2576 if(mRulerY->IsEnabled())
2578 position.y = -WrapInDomain(-position.y, rulerDomainY.min, rulerDomainY.max);
2583 void ScrollView::ClampScale(Vector3& scale) const
2585 ClampState3 clamped;
2586 ClampScale(scale, clamped);
2589 void ScrollView::ClampScale(Vector3& scale, ClampState3 &clamped) const
2591 scale.x = mRulerScaleX->Clamp(scale.x, 0.0f, 1.0f, clamped.x);
2592 scale.y = mRulerScaleY->Clamp(scale.y, 0.0f, 1.0f, clamped.y);
2593 clamped.z = NotClamped;
2596 void ScrollView::UpdateMainInternalConstraint()
2598 // TODO: Only update the constraints which have changed, rather than remove all and add all again.
2599 // Requires a dali-core ApplyConstraintAt, or a ReplaceConstraint. The former is probably more flexible.
2600 Actor self = Self();
2601 PanGestureDetector detector( GetPanGestureDetector() );
2603 if(mScrollMainInternalPositionConstraint)
2605 self.RemoveConstraint(mScrollMainInternalPositionConstraint);
2606 self.RemoveConstraint(mScrollMainInternalDeltaConstraint);
2607 self.RemoveConstraint(mScrollMainInternalFinalConstraint);
2608 self.RemoveConstraint(mScrollMainInternalRelativeConstraint);
2609 self.RemoveConstraint(mScrollMainInternalXConstraint);
2610 self.RemoveConstraint(mScrollMainInternalYConstraint);
2612 if( mScrollMainInternalPrePositionConstraint )
2614 self.RemoveConstraint(mScrollMainInternalPrePositionConstraint);
2617 // TODO: It's probably better to use a local displacement value as this will give a displacement when scrolling just commences
2618 // but we need to make sure than the gesture system gives displacement since last frame (60Hz), not displacement since last touch event (90Hz).
2620 // 1. First calculate the pre-position (this is the scroll position if no clamping has taken place)
2621 Vector2 initialPanMask = Vector2(mRulerX->IsEnabled() ? 1.0f : 0.0f, mRulerY->IsEnabled() ? 1.0f : 0.0f);
2623 if( mLockAxis == LockVertical )
2625 initialPanMask.y = 0.0f;
2627 else if( mLockAxis == LockHorizontal )
2629 initialPanMask.x = 0.0f;
2631 Constraint constraint;
2635 constraint = Constraint::New<Vector3>( mPropertyPrePosition,
2636 Source( detector, PanGestureDetector::LOCAL_POSITION ),
2637 Source( detector, PanGestureDetector::LOCAL_DISPLACEMENT ),
2638 Source( self, Actor::SIZE ),
2639 InternalPrePositionConstraint( initialPanMask, mAxisAutoLock, mAxisAutoLockGradient, mLockAxis, mMaxOvershoot, mRulerX->GetDomain(), mRulerY->GetDomain() ) );
2640 mScrollMainInternalPrePositionConstraint = self.ApplyConstraint( constraint );
2643 // 2. Second calculate the clamped position (actual position)
2644 constraint = Constraint::New<Vector3>( mPropertyPosition,
2645 LocalSource( mPropertyPrePosition ),
2646 LocalSource( mPropertyPositionMin ),
2647 LocalSource( mPropertyPositionMax ),
2648 Source( self, Actor::SIZE ),
2649 InternalPositionConstraint( mRulerX->GetDomain(),
2650 mRulerY->GetDomain(), mWrapMode ) );
2651 mScrollMainInternalPositionConstraint = self.ApplyConstraint( constraint );
2653 constraint = Constraint::New<Vector3>( mPropertyPositionDelta,
2654 LocalSource( mPropertyPosition ),
2655 LocalSource( mPropertyDomainOffset ),
2656 InternalPositionDeltaConstraint );
2657 mScrollMainInternalDeltaConstraint = self.ApplyConstraint( constraint );
2659 constraint = Constraint::New<Vector3>( mPropertyFinal,
2660 LocalSource( mPropertyPosition ),
2661 LocalSource( mPropertyOvershootX ),
2662 LocalSource( mPropertyOvershootY ),
2663 InternalFinalConstraint( FinalDefaultAlphaFunction,
2664 FinalDefaultAlphaFunction ) );
2665 mScrollMainInternalFinalConstraint = self.ApplyConstraint( constraint );
2667 constraint = Constraint::New<Vector3>( mPropertyRelativePosition,
2668 LocalSource( mPropertyPosition ),
2669 LocalSource( mPropertyPositionMin ),
2670 LocalSource( mPropertyPositionMax ),
2671 LocalSource( Actor::SIZE ),
2672 InternalRelativePositionConstraint );
2673 mScrollMainInternalRelativeConstraint = self.ApplyConstraint( constraint );
2675 constraint = Constraint::New<float>( mPropertyX,
2676 LocalSource( mPropertyPrePosition ),
2677 InternalXConstraint );
2678 mScrollMainInternalXConstraint = self.ApplyConstraint( constraint );
2680 constraint = Constraint::New<float>( mPropertyY,
2681 LocalSource( mPropertyPrePosition ),
2682 InternalYConstraint );
2683 mScrollMainInternalYConstraint = self.ApplyConstraint( constraint );
2685 // When panning we want to make sure overshoot values are affected by pre position and post position
2686 SetOvershootConstraintsEnabled(!mWrapMode);
2689 void ScrollView::SetOvershootConstraintsEnabled(bool enabled)
2691 Actor self( Self() );
2692 // remove and reset, it may now be in wrong order with the main internal constraints
2693 if( mScrollMainInternalOvershootXConstraint )
2695 self.RemoveConstraint(mScrollMainInternalOvershootXConstraint);
2696 mScrollMainInternalOvershootXConstraint.Reset();
2697 self.RemoveConstraint(mScrollMainInternalOvershootYConstraint);
2698 mScrollMainInternalOvershootYConstraint.Reset();
2702 Constraint constraint = Constraint::New<float>( mPropertyOvershootX,
2703 LocalSource( mPropertyPrePosition ),
2704 LocalSource( mPropertyPosition ),
2705 OvershootXConstraint(mMaxOvershoot.x) );
2706 mScrollMainInternalOvershootXConstraint = self.ApplyConstraint( constraint );
2708 constraint = Constraint::New<float>( mPropertyOvershootY,
2709 LocalSource( mPropertyPrePosition ),
2710 LocalSource( mPropertyPosition ),
2711 OvershootYConstraint(mMaxOvershoot.y) );
2712 mScrollMainInternalOvershootYConstraint = self.ApplyConstraint( constraint );
2716 self.SetProperty(mPropertyOvershootX, 0.0f);
2717 self.SetProperty(mPropertyOvershootY, 0.0f);
2721 void ScrollView::SetInternalConstraints()
2723 // Internal constraints (applied to target ScrollBase Actor itself) /////////
2724 UpdateMainInternalConstraint();
2726 // User definable constraints to apply to all child actors //////////////////
2727 Actor self = Self();
2729 // LocalSource - The Actors to be moved.
2730 // self - The ScrollView
2732 // Apply some default constraints to ScrollView.
2733 // Movement + Scaling + Wrap function
2735 Constraint constraint;
2737 // MoveScaledActor (scrolling/zooming)
2738 constraint = Constraint::New<Vector3>( Actor::POSITION,
2739 Source( self, mPropertyPosition ),
2740 Source( self, mPropertyScale ),
2741 MoveScaledActorConstraint );
2742 constraint.SetRemoveAction(Constraint::Discard);
2743 ApplyConstraintToBoundActors(constraint);
2745 // ScaleActor (scrolling/zooming)
2746 constraint = Constraint::New<Vector3>( Actor::SCALE,
2747 Source( self, mPropertyScale ),
2748 ScaleActorConstraint );
2749 constraint.SetRemoveAction(Constraint::Discard);
2750 ApplyConstraintToBoundActors(constraint);
2752 // WrapActor (wrap functionality)
2753 constraint = Constraint::New<Vector3>( Actor::POSITION,
2754 LocalSource( Actor::SCALE ),
2755 LocalSource( Actor::ANCHOR_POINT ),
2756 LocalSource( Actor::SIZE ),
2757 Source( self, mPropertyPositionMin ),
2758 Source( self, mPropertyPositionMax ),
2759 Source( self, mPropertyWrap ),
2760 WrapActorConstraint );
2761 constraint.SetRemoveAction(Constraint::Discard);
2762 ApplyConstraintToBoundActors(constraint);
2765 void ScrollView::StartRefreshTimer()
2767 if(mRefreshIntervalMilliseconds > 0)
2771 mRefreshTimer = Timer::New( mRefreshIntervalMilliseconds );
2772 mRefreshTimer.TickSignal().Connect( this, &ScrollView::OnRefreshTick );
2775 if (!mRefreshTimer.IsRunning())
2777 mRefreshTimer.Start();
2782 void ScrollView::CancelRefreshTimer()
2786 mRefreshTimer.Stop();
2790 bool ScrollView::OnRefreshTick()
2792 // Guard against destruction during signal emission
2793 Toolkit::ScrollView handle( GetOwner() );
2795 Vector3 currentScrollPosition = GetCurrentScrollPosition();
2796 mScrollUpdatedSignalV2.Emit( currentScrollPosition );
2801 } // namespace Internal
2803 } // namespace Toolkit