2 * Copyright (c) 2014 Samsung Electronics Co., Ltd.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 #include <dali/public-api/events/mouse-wheel-event.h>
21 #include <dali-toolkit/public-api/controls/scrollable/scroll-view/scroll-view-constraints.h>
22 #include <dali-toolkit/public-api/controls/scrollable/scroll-component-impl.h>
23 #include <dali-toolkit/internal/controls/scrollable/scroll-view/scroll-view-impl.h>
24 #include <dali-toolkit/internal/controls/scrollable/scroll-view/scroll-view-effect-impl.h>
25 #include <dali-toolkit/internal/controls/scrollable/scroll-view/scroll-overshoot-indicator-impl.h>
26 #include <dali/integration-api/debug.h>
28 //#define ENABLED_SCROLL_STATE_LOGGING
30 #ifdef ENABLED_SCROLL_STATE_LOGGING
31 #define DALI_LOG_SCROLL_STATE(format, args...) Dali::Integration::Log::LogMessage(Dali::Integration::Log::DebugInfo, "%s:%d " format "\n", __PRETTY_FUNCTION__, __LINE__, ## args)
33 #define DALI_LOG_SCROLL_STATE(format, args...)
36 // TODO: Change to two class system:
37 // 1. DraggableActor (is an actor which can be dragged anywhere/scaled/rotated, can be set to range using the ruler)
38 // 2. ScrollView (contains a draggable actor that can a) be dragged in the negative X, and Y domain, b) has a hitArea for touches)
40 // TODO: Asymetrical scaling
41 // TODO: external components (page and status overlays).
43 // TODO: upgrade Vector2/3 to support returning Unit vectors, normals, & cross product (dot product is already provided)
50 const int DEFAULT_REFRESH_INTERVAL_MILLISECONDS = 50; ///< Refresh rate TODO: Animation should have an update signal (and see item-view-impl)
51 const Vector2 DEFAULT_MIN_FLICK_DISTANCE(30.0f, 30.0f); ///< minimum distance for pan before flick allowed
52 const float DEFAULT_MIN_FLICK_SPEED_THRESHOLD(500.0f); ///< Minimum pan speed required for flick in pixels/s
53 const float FREE_FLICK_SPEED_THRESHOLD = 200.0f; ///< Free-Flick threshold in pixels/ms
54 const float AUTOLOCK_AXIS_MINIMUM_DISTANCE2 = 100.0f; ///< Auto-lock axis after minimum distance squared.
55 const float FLICK_ORTHO_ANGLE_RANGE = 75.0f; ///< degrees. (if >45, then supports diagonal flicking)
56 const unsigned int MAXIMUM_NUMBER_OF_VALUES = 5; ///< Number of values to use for weighted pan calculation.
57 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.
58 const unsigned long MINIMUM_TIME_BETWEEN_DOWN_AND_UP_FOR_RESET( 150u );
59 const float DEFAULT_OVERSHOOT_ANIMATION_DURATION = 0.35f; // time in seconds
60 const Vector2 OVERSCROLL_CLAMP(1.0f, 1.0f); // maximum overscroll allowed in pixels when overshoot indicator is being used
61 const float TOUCH_DOWN_TIMER_INTERVAL = 100.0f;
62 const float DEFAULT_SCROLL_UPDATE_DISTANCE( 30.0f ); ///< Default distance to travel in pixels for scroll update signal
64 // predefined effect values
65 const Vector3 ANGLE_CAROUSEL_ROTATE(Math::PI * 0.5f, Math::PI * 0.5f, 0.0f);
66 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
67 const Vector2 ANGLE_CUSTOM_CUBE_SWING(-Math::PI * 0.45f, -Math::PI * 0.45f); ///< outer cube pages swing 90 degrees as they pan offscreen
68 const Vector2 ANGLE_SPIRAL_SWING_IN(Math::PI * 0.5f, Math::PI * 0.5f);
69 const Vector2 ANGLE_SPIRAL_SWING_OUT(Math::PI * 0.35f, Math::PI * 0.35f);
70 const Vector2 ANGLE_OUTER_CUBE_SWING(Math::PI * 0.5f, Math::PI * 0.5f); ///< outer cube pages swing 90 degrees as they pan offscreen
72 // Helpers ////////////////////////////////////////////////////////////////////////////////////////
74 // TODO: GetAngle for Vector2 can be moved.
75 // GetAngle for Vector3 needs to be measured against a normal/plane.
78 * @param[in] vector The 3D vector to be measured
79 * @return angle in radians from 0 to 2PI
81 float GetAngle(const Vector3& vector)
83 return atan2(vector.y, vector.x) + Math::PI;
87 * @param[in] vector The 2D vector to be measured
88 * @return angle in radians from 0 to 2PI
90 float GetAngle(const Vector2& vector)
92 return atan2(vector.y, vector.x) + Math::PI;
96 * Find the vector (distance) from (a) to (b)
97 * in domain (start) to (end)
98 * (\ / start) (\ / end)
101 * @note assumes both (a) and (b) are already with the domain
104 * @param[in] a the current point
105 * @param[in] b the target point
106 * @param[in] start the start of the domain
107 * @param[in] end the end of the domain
108 * @param[in] bias whether to only take the right direction or the left direction,
109 * or the shortest direction.
110 * @return the shortest direction and distance
112 float VectorInDomain(float a, float b, float start, float end, Dali::Toolkit::DirectionBias bias)
114 if(bias == Dali::Toolkit::DirectionBiasNone)
116 return ShortestDistanceInDomain( a, b, start, end );
119 float size = end-start;
125 if(bias == Dali::Toolkit::DirectionBiasRight) // going right, take the vector.
131 float aRight = a+size;
138 if(bias == Dali::Toolkit::DirectionBiasLeft) // going left, take the vector.
144 float aLeft = a-size;
151 * Returns the position of the anchor within actor
153 * @param actor The Actor
154 * @param anchor The Anchor point of interest.
155 * @return The position of the Anchor
157 Vector3 GetPositionOfAnchor(Actor &actor, const Vector3 &anchor)
159 Vector3 childPosition = actor.GetCurrentPosition();
160 Vector3 childAnchor = - actor.GetCurrentAnchorPoint() + anchor;
161 Vector3 childSize = actor.GetCurrentSize();
163 return childPosition + childAnchor * childSize;
166 // AlphaFunctions /////////////////////////////////////////////////////////////////////////////////
168 float FinalDefaultAlphaFunction(float offset)
170 return offset * 0.5f;
174 * ConstantDecelerationAlphaFunction
175 * Newtoninan distance for constant deceleration
176 * v = 1 - t, s = t - 1/2 t^2
177 * when t = 0, s = 0.0 (min distance)
178 * when t = 1, s = 0.5 (max distance)
179 * progress = s / (max-min) = 2t - t^2
181 * @param[in] offset The input progress
182 * @return The output progress
184 float ConstantDecelerationAlphaFunction(float progress)
186 return progress * 2.0f - progress * progress;
189 // Internal Constraints ///////////////////////////////////////////////////////////////////////////
192 * Internal Relative position Constraint
193 * Generates the relative position value of the scroll view
194 * based on the absolute position, and it's relation to the
195 * scroll domain. This is a value from 0.0f to 1.0f in each
196 * scroll position axis.
198 Vector3 InternalRelativePositionConstraint(const Vector3& current,
199 const PropertyInput& scrollPositionProperty,
200 const PropertyInput& scrollMinProperty,
201 const PropertyInput& scrollMaxProperty,
202 const PropertyInput& scrollSizeProperty)
204 Vector3 position = -scrollPositionProperty.GetVector3();
205 const Vector3& min = scrollMinProperty.GetVector3();
206 const Vector3& max = scrollMaxProperty.GetVector3();
207 const Vector3& size = scrollSizeProperty.GetVector3();
209 position.x = WrapInDomain(position.x, min.x, max.x);
210 position.y = WrapInDomain(position.y, min.y, max.y);
212 Vector3 relativePosition;
213 Vector3 domainSize = (max - min) - size;
215 relativePosition.x = domainSize.x > Math::MACHINE_EPSILON_1 ? fabsf((position.x - min.x) / domainSize.x) : 0.0f;
216 relativePosition.y = domainSize.y > Math::MACHINE_EPSILON_1 ? fabsf((position.y - min.y) / domainSize.y) : 0.0f;
218 return relativePosition;
221 } // unnamed namespace
236 * Returns whether to lock scrolling to a particular axis
238 * @param[in] panDelta Distance panned since gesture started
239 * @param[in] currentLockAxis The current lock axis value
240 * @param[in] lockGradient How quickly to lock to a particular axis
242 * @return The new axis lock state
244 ScrollView::LockAxis GetLockAxis(const Vector2& panDelta, ScrollView::LockAxis currentLockAxis, float lockGradient)
246 if(panDelta.LengthSquared() > AUTOLOCK_AXIS_MINIMUM_DISTANCE2 &&
247 currentLockAxis == ScrollView::LockPossible)
249 float dx = fabsf(panDelta.x);
250 float dy = fabsf(panDelta.y);
251 if(dx * lockGradient >= dy)
253 // 0.36:1 gradient to the horizontal (deviate < 20 degrees)
254 currentLockAxis = ScrollView::LockVertical;
256 else if(dy * lockGradient > dx)
258 // 0.36:1 gradient to the vertical (deviate < 20 degrees)
259 currentLockAxis = ScrollView::LockHorizontal;
263 currentLockAxis = ScrollView::LockNone;
266 return currentLockAxis;
270 * Internal Pre-Position Property Constraint.
272 * Generates position property based on current position + gesture displacement.
273 * Or generates position property based on positionX/Y.
274 * Note: This is the position prior to any clamping at scroll boundaries.
275 * TODO: Scale & Rotation Transforms.
277 struct InternalPrePositionConstraint
279 InternalPrePositionConstraint(const Vector2& initialPanMask,
281 float axisAutoLockGradient,
282 ScrollView::LockAxis initialLockAxis,
283 const Vector2& maxOvershoot,
284 const RulerDomain& domainX, const RulerDomain& domainY)
285 : mInitialPanMask(initialPanMask),
286 mDomainMin( -domainX.min, -domainY.min ),
287 mDomainMax( -domainX.max, -domainY.max ),
288 mMaxOvershoot(maxOvershoot),
289 mAxisAutoLockGradient(axisAutoLockGradient),
290 mLockAxis(initialLockAxis),
291 mAxisAutoLock(axisAutoLock),
293 mClampX( domainX.enabled ),
294 mClampY( domainY.enabled )
298 Vector3 operator()(const Vector3& current,
299 const PropertyInput& gesturePositionProperty,
300 const PropertyInput& gestureDisplacementProperty,
301 const PropertyInput& sizeProperty)
303 Vector3 scrollPostPosition = current;
304 Vector2 panPosition = gesturePositionProperty.GetVector2();
308 mLocalStart = gesturePositionProperty.GetVector2() - gestureDisplacementProperty.GetVector2();
309 mPrePosition = current;
310 mCurrentPanMask = mInitialPanMask;
314 // Calculate Deltas...
315 Vector2 currentPosition = gesturePositionProperty.GetVector2();
316 Vector2 panDelta( currentPosition - mLocalStart );
318 // Axis Auto Lock - locks the panning to the horizontal or vertical axis if the pan
319 // appears mostly horizontal or mostly vertical respectively...
322 mLockAxis = GetLockAxis(panDelta, mLockAxis, mAxisAutoLockGradient);
323 if( mLockAxis == ScrollView::LockVertical )
325 mCurrentPanMask.y = 0.0f;
327 else if( mLockAxis == ScrollView::LockHorizontal )
329 mCurrentPanMask.x = 0.0f;
333 // Restrict deltas based on ruler enable/disable and axis-lock state...
334 panDelta *= mCurrentPanMask;
336 // Perform Position transform based on input deltas...
337 scrollPostPosition = mPrePosition;
338 scrollPostPosition.GetVectorXY() += panDelta;
340 // if no wrapping then clamp preposition to maximum overshoot amount
341 const Vector3& size = sizeProperty.GetVector3();
344 float newXPosition = Clamp(scrollPostPosition.x, (mDomainMax.x + size.x) - mMaxOvershoot.x, mDomainMin.x + mMaxOvershoot.x );
345 if( (newXPosition < scrollPostPosition.x - Math::MACHINE_EPSILON_1)
346 || (newXPosition > scrollPostPosition.x + Math::MACHINE_EPSILON_1) )
348 mPrePosition.x = newXPosition;
349 mLocalStart.x = panPosition.x;
351 scrollPostPosition.x = newXPosition;
355 float newYPosition = Clamp(scrollPostPosition.y, (mDomainMax.y + size.y) - mMaxOvershoot.y, mDomainMin.y + mMaxOvershoot.y );
356 if( (newYPosition < scrollPostPosition.y - Math::MACHINE_EPSILON_1)
357 || (newYPosition > scrollPostPosition.y + Math::MACHINE_EPSILON_1) )
359 mPrePosition.y = newYPosition;
360 mLocalStart.y = panPosition.y;
362 scrollPostPosition.y = newYPosition;
365 return scrollPostPosition;
368 Vector3 mPrePosition;
370 Vector2 mInitialPanMask; ///< Initial pan mask (based on ruler settings)
371 Vector2 mCurrentPanMask; ///< Current pan mask that can be altered by axis lock mode.
374 Vector2 mMaxOvershoot;
376 float mAxisAutoLockGradient; ///< Set by ScrollView
377 ScrollView::LockAxis mLockAxis;
379 bool mAxisAutoLock:1; ///< Set by ScrollView
386 * Internal Position Property Constraint.
388 * Generates position property based on pre-position
389 * Note: This is the position after clamping.
390 * (uses result of InternalPrePositionConstraint)
392 struct InternalPositionConstraint
394 InternalPositionConstraint(const RulerDomain& domainX, const RulerDomain& domainY, bool wrap)
395 : mDomainMin( -domainX.min, -domainY.min ),
396 mDomainMax( -domainX.max, -domainY.max ),
397 mClampX( domainX.enabled ),
398 mClampY( domainY.enabled ),
403 Vector3 operator()(const Vector3& current,
404 const PropertyInput& scrollPositionProperty,
405 const PropertyInput& scrollMinProperty,
406 const PropertyInput& scrollMaxProperty,
407 const PropertyInput& scrollSizeProperty)
409 Vector3 position = scrollPositionProperty.GetVector3();
410 const Vector2& size = scrollSizeProperty.GetVector3().GetVectorXY();
411 const Vector3& min = scrollMinProperty.GetVector3();
412 const Vector3& max = scrollMaxProperty.GetVector3();
416 position.x = -WrapInDomain(-position.x, min.x, max.x);
417 position.y = -WrapInDomain(-position.y, min.y, max.y);
421 // clamp post position to domain
422 position.x = mClampX ? Clamp(position.x, mDomainMax.x + size.x, mDomainMin.x ) : position.x;
423 position.y = mClampY ? Clamp(position.y, mDomainMax.y + size.y, mDomainMin.y ) : position.y;
438 * This constraint updates the X overshoot property using the difference
439 * mPropertyPrePosition.x and mPropertyPosition.x, returning a relative value between 0.0f and 1.0f
441 struct OvershootXConstraint
443 OvershootXConstraint(float maxOvershoot) : mMaxOvershoot(maxOvershoot) {}
445 float operator()(const float& current,
446 const PropertyInput& scrollPrePositionProperty,
447 const PropertyInput& scrollPostPositionProperty,
448 const PropertyInput& canScrollProperty)
450 if( canScrollProperty.GetBoolean() )
452 const Vector3& scrollPrePosition = scrollPrePositionProperty.GetVector3();
453 const Vector3& scrollPostPosition = scrollPostPositionProperty.GetVector3();
454 float newOvershoot = scrollPrePosition.x - scrollPostPosition.x;
455 return (newOvershoot > 0.0f ? std::min(newOvershoot, mMaxOvershoot) : std::max(newOvershoot, -mMaxOvershoot)) / mMaxOvershoot;
464 * This constraint updates the Y overshoot property using the difference
465 * mPropertyPrePosition.y and mPropertyPosition.y, returning a relative value between 0.0f and 1.0f
467 struct OvershootYConstraint
469 OvershootYConstraint(float maxOvershoot) : mMaxOvershoot(maxOvershoot) {}
471 float operator()(const float& current,
472 const PropertyInput& scrollPrePositionProperty,
473 const PropertyInput& scrollPostPositionProperty,
474 const PropertyInput& canScrollProperty)
476 if( canScrollProperty.GetBoolean() )
478 const Vector3& scrollPrePosition = scrollPrePositionProperty.GetVector3();
479 const Vector3& scrollPostPosition = scrollPostPositionProperty.GetVector3();
480 float newOvershoot = scrollPrePosition.y - scrollPostPosition.y;
481 return (newOvershoot > 0.0f ? std::min(newOvershoot, mMaxOvershoot) : std::max(newOvershoot, -mMaxOvershoot)) / mMaxOvershoot;
490 * When panning, this constraint updates the X property, otherwise
491 * it has no effect on the X property.
493 float InternalXConstraint(const float& current,
494 const PropertyInput& scrollPosition)
496 return scrollPosition.GetVector3().x;
500 * When panning, this constraint updates the Y property, otherwise
501 * it has no effect on the Y property.
503 float InternalYConstraint(const float& current,
504 const PropertyInput& scrollPosition)
506 return scrollPosition.GetVector3().y;
510 * Internal Position-Delta Property Constraint.
512 * Generates position-delta property based on scroll-position + scroll-offset properties.
514 Vector3 InternalPositionDeltaConstraint(const Vector3& current,
515 const PropertyInput& scrollPositionProperty,
516 const PropertyInput& scrollOffsetProperty)
518 const Vector3& scrollPosition = scrollPositionProperty.GetVector3();
519 const Vector3& scrollOffset = scrollOffsetProperty.GetVector3();
521 return scrollPosition + scrollOffset;
525 * Internal Final Position Constraint
526 * The position of content is:
527 * of scroll-position + f(scroll-overshoot)
528 * where f(...) function defines how overshoot
529 * should affect final-position.
531 struct InternalFinalConstraint
533 InternalFinalConstraint(AlphaFunction functionX,
534 AlphaFunction functionY)
535 : mFunctionX(functionX),
536 mFunctionY(functionY)
540 Vector3 operator()(const Vector3& current,
541 const PropertyInput& scrollPositionProperty,
542 const PropertyInput& scrollOvershootXProperty,
543 const PropertyInput& scrollOvershootYProperty)
545 const float& overshootx = scrollOvershootXProperty.GetFloat();
546 const float& overshooty = scrollOvershootYProperty.GetFloat();
547 Vector3 offset( mFunctionX(overshootx),
548 mFunctionY(overshooty),
551 return scrollPositionProperty.GetVector3() - offset;
554 AlphaFunction mFunctionX;
555 AlphaFunction mFunctionY;
561 return Toolkit::ScrollView::New();
564 TypeRegistration typeRegistration( typeid(Toolkit::ScrollView), typeid(Toolkit::Scrollable), Create );
566 SignalConnectorType signalConnector1( typeRegistration, Toolkit::ScrollView::SIGNAL_SNAP_STARTED, &ScrollView::DoConnectSignal );
571 ///////////////////////////////////////////////////////////////////////////////////////////////////
573 ///////////////////////////////////////////////////////////////////////////////////////////////////
575 Dali::Toolkit::ScrollView ScrollView::New()
577 // Create the implementation
578 ScrollViewPtr scrollView(new ScrollView());
580 // Pass ownership to CustomActor via derived handle
581 Dali::Toolkit::ScrollView handle(*scrollView);
583 // Second-phase init of the implementation
584 // This can only be done after the CustomActor connection has been made...
585 scrollView->Initialize();
590 ScrollView::ScrollView()
593 mGestureStackDepth(0),
594 mRotationDelta(0.0f),
595 mScrollStateFlags(0),
596 mScrollPreRotation(0.0f),
597 mScrollPostRotation(0.0f),
598 mMinTouchesForPanning(1),
599 mMaxTouchesForPanning(1),
600 mLockAxis(LockPossible),
601 mScrollUpdateDistance(DEFAULT_SCROLL_UPDATE_DISTANCE),
602 mOvershootDelay(1.0f),
603 mMaxOvershoot(Toolkit::ScrollView::DEFAULT_MAX_OVERSHOOT, Toolkit::ScrollView::DEFAULT_MAX_OVERSHOOT),
604 mUserMaxOvershoot(Toolkit::ScrollView::DEFAULT_MAX_OVERSHOOT, Toolkit::ScrollView::DEFAULT_MAX_OVERSHOOT),
605 mSnapOvershootDuration(Toolkit::ScrollView::DEFAULT_SNAP_OVERSHOOT_DURATION),
606 mSnapOvershootAlphaFunction(AlphaFunctions::EaseOut),
607 mSnapDuration(Toolkit::ScrollView::DEFAULT_SLOW_SNAP_ANIMATION_DURATION),
608 mSnapAlphaFunction(AlphaFunctions::EaseOut),
609 mMinFlickDistance(DEFAULT_MIN_FLICK_DISTANCE),
610 mFlickSpeedThreshold(DEFAULT_MIN_FLICK_SPEED_THRESHOLD),
611 mFlickDuration(Toolkit::ScrollView::DEFAULT_FAST_SNAP_ANIMATION_DURATION),
612 mFlickAlphaFunction(AlphaFunctions::EaseOut),
613 mAxisAutoLockGradient(Toolkit::ScrollView::DEFAULT_AXIS_AUTO_LOCK_GRADIENT),
614 mFrictionCoefficient(Toolkit::ScrollView::DEFAULT_FRICTION_COEFFICIENT),
615 mFlickSpeedCoefficient(Toolkit::ScrollView::DEFAULT_FLICK_SPEED_COEFFICIENT),
616 mMaxFlickSpeed(Toolkit::ScrollView::DEFAULT_MAX_FLICK_SPEED),
617 mInAccessibilityPan(false),
620 mScrollInterrupted(false),
623 mTouchDownTimeoutReached(false),
624 mActorAutoSnapEnabled(false),
625 mAutoResizeContainerEnabled(false),
627 mAxisAutoLock(false),
629 mDefaultMaxOvershoot(true),
630 mCanScrollHorizontal(true),
631 mCanScrollVertical(true)
633 SetRequiresMouseWheelEvents(true);
636 void ScrollView::OnInitialize()
640 // Internal Actor, used to hide actors from enumerations.
641 // Also actors added to Internal actor appear as overlays e.g. ScrollBar components.
642 mInternalActor = Actor::New();
643 mInternalActor.SetDrawMode(DrawMode::OVERLAY);
644 self.Add(mInternalActor);
645 mInternalActor.ApplyConstraint( Constraint::New<Vector3>( Actor::SIZE, ParentSource( Actor::SIZE ), EqualToConstraint() ) );
646 mInternalActor.SetParentOrigin(ParentOrigin::CENTER);
647 mInternalActor.SetAnchorPoint(AnchorPoint::CENTER);
651 // Register Scroll Properties.
652 RegisterProperties();
654 mScrollPostPosition = mScrollPrePosition = Vector3::ZERO;
655 mScrollPostScale = mScrollPreScale = Vector3::ONE;
656 mScrollPostRotation = mScrollPreRotation = 0.0f;
658 mMouseWheelScrollDistanceStep = Stage::GetCurrent().GetSize() * DEFAULT_MOUSE_WHEEL_SCROLL_DISTANCE_STEP_PROPORTION;
662 mGestureStackDepth = 0;
664 EnableGestureDetection( Gesture::Type( Gesture::Pan ) );
666 // For pan, default to only 1 touch required, ignoring touches outside this range.
667 SetTouchesRequiredForPanning(1, 1, false);
669 // By default we'll allow the user to freely drag the scroll view,
670 // while disabling the other rulers.
671 RulerPtr ruler = new DefaultRuler();
672 RulerPtr rulerDisabled = new DefaultRuler();
673 rulerDisabled->Disable();
676 mRulerScaleX = rulerDisabled;
677 mRulerScaleY = rulerDisabled;
678 mRulerRotation = rulerDisabled;
680 EnableScrollComponent(Toolkit::Scrollable::OvershootIndicator);
682 Vector3 size = GetControlSize();
683 UpdatePropertyDomain(size);
684 SetInternalConstraints();
687 void ScrollView::OnControlStageConnection()
689 DALI_LOG_SCROLL_STATE("[0x%X]", this);
693 SetScrollSensitive( false );
694 SetScrollSensitive( true );
696 if(IsScrollComponentEnabled(Toolkit::Scrollable::OvershootIndicator))
698 // try and make sure property notifications are set
699 EnableScrollComponent(Toolkit::Scrollable::OvershootIndicator);
703 void ScrollView::OnControlStageDisconnection()
705 DALI_LOG_SCROLL_STATE("[0x%X]", this);
710 ScrollView::~ScrollView()
712 DALI_LOG_SCROLL_STATE("[0x%X]", this);
715 AlphaFunction ScrollView::GetScrollSnapAlphaFunction() const
717 return mSnapAlphaFunction;
720 void ScrollView::SetScrollSnapAlphaFunction(AlphaFunction alpha)
722 mSnapAlphaFunction = alpha;
725 AlphaFunction ScrollView::GetScrollFlickAlphaFunction() const
727 return mFlickAlphaFunction;
730 void ScrollView::SetScrollFlickAlphaFunction(AlphaFunction alpha)
732 mFlickAlphaFunction = alpha;
735 float ScrollView::GetScrollSnapDuration() const
737 return mSnapDuration;
740 void ScrollView::SetScrollSnapDuration(float time)
742 mSnapDuration = time;
745 float ScrollView::GetScrollFlickDuration() const
747 return mFlickDuration;
750 void ScrollView::SetScrollFlickDuration(float time)
752 mFlickDuration = time;
755 void ScrollView::ApplyEffect(Toolkit::ScrollViewEffect effect)
757 Dali::Toolkit::ScrollView self = Dali::Toolkit::ScrollView::DownCast(Self());
759 // Assertion check to ensure effect doesn't already exist in this scrollview
760 bool effectAlreadyExistsInScrollView(false);
761 for (ScrollViewEffectIter iter = mEffects.begin(); iter != mEffects.end(); ++iter)
765 effectAlreadyExistsInScrollView = true;
770 DALI_ASSERT_ALWAYS(!effectAlreadyExistsInScrollView);
772 // add effect to effects list
773 mEffects.push_back(effect);
775 // invoke Attachment request to ScrollView first
776 GetImpl(effect).Attach(self);
779 Toolkit::ScrollViewEffect ScrollView::ApplyEffect(Toolkit::ScrollView::PageEffect effect)
781 Toolkit::ScrollViewEffect scrollEffect;
784 case Toolkit::ScrollView::PageEffectNone:
788 case Toolkit::ScrollView::PageEffectOuterCube:
790 Toolkit::ScrollViewCustomEffect customEffect;
791 scrollEffect = customEffect = Toolkit::ScrollViewCustomEffect::New();
792 Vector2 pageSize = Stage::GetCurrent().GetSize();
793 // 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
794 // 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)
795 // the page moving off screen will slowly build a spacing from 0.0f to 20.0f
796 // the spacing from each page is added together for the final spacing between the two pages.
797 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));
798 customEffect.SetSwingAngleOut(ANGLE_CUSTOM_CUBE_SWING.x, Vector3(0.0f, -1.0f, 0.0f));
799 customEffect.SetSwingAnchor(AnchorPoint::CENTER, AnchorPoint::CENTER_LEFT);
800 customEffect.SetOpacityThreshold(0.7f);
803 case Toolkit::ScrollView::PageEffectDepth:
805 Toolkit::ScrollViewCustomEffect customEffect;
806 scrollEffect = customEffect = Toolkit::ScrollViewCustomEffect::New();
809 case Toolkit::ScrollView::PageEffectInnerCube:
811 Toolkit::ScrollViewCustomEffect customEffect;
812 scrollEffect = customEffect = Toolkit::ScrollViewCustomEffect::New();
813 customEffect.SetPageSpacing(Vector2(30.0f, 30.0f));
814 customEffect.SetAngledOriginPageRotation(ANGLE_CUBE_PAGE_ROTATE);
815 customEffect.SetSwingAngle(ANGLE_CUBE_PAGE_ROTATE.x, Vector3(0,-1,0));
816 customEffect.SetOpacityThreshold(0.5f);
819 case Toolkit::ScrollView::PageEffectCarousel:
821 Toolkit::ScrollViewCustomEffect customEffect;
822 scrollEffect = customEffect = Toolkit::ScrollViewCustomEffect::New();
823 customEffect.SetPageTranslation(Vector3(0,0,0), Vector3(-30, 0, 0));
824 customEffect.SetPageSpacing(Vector2(60.0f, 60.0f));
825 customEffect.SetAngledOriginPageRotation(-ANGLE_CUBE_PAGE_ROTATE);
826 customEffect.SetOpacityThreshold(0.2f, 0.6f);
829 case Toolkit::ScrollView::PageEffectSpiral:
831 Toolkit::ScrollViewCustomEffect customEffect;
832 scrollEffect = customEffect = Toolkit::ScrollViewCustomEffect::New();
834 Vector2 pageSize = Stage::GetCurrent().GetSize();
835 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));
836 //customEffect.SetSwingAngleAlphaFunctionOut(AlphaFunctions::EaseOut);
837 customEffect.SetSwingAnchor(AnchorPoint::CENTER_RIGHT);
838 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);
839 //customEffect.SetPageTranslateAlphaFunctionOut(AlphaFunctions::EaseOut);
840 customEffect.SetOpacityThreshold(0.75f, 0.6f);
841 customEffect.SetOpacityAlphaFunctionIn(AlphaFunctions::EaseInOut);
846 DALI_ASSERT_DEBUG(0 && "unknown scroll view effect");
849 RemoveConstraintsFromChildren();
852 ApplyEffect(scrollEffect);
857 void ScrollView::RemoveEffect(Toolkit::ScrollViewEffect effect)
859 Dali::Toolkit::ScrollView self = Dali::Toolkit::ScrollView::DownCast(Self());
861 // remove effect from effects list
862 bool effectExistedInScrollView(false);
863 for (ScrollViewEffectIter iter = mEffects.begin(); iter != mEffects.end(); ++iter)
867 mEffects.erase(iter);
868 effectExistedInScrollView = true;
873 // Assertion check to ensure effect existed.
874 DALI_ASSERT_ALWAYS(effectExistedInScrollView);
876 // invoke Detachment request to ScrollView last
877 GetImpl(effect).Detach(self);
880 void ScrollView::RemoveAllEffects()
882 Dali::Toolkit::ScrollView self = Dali::Toolkit::ScrollView::DownCast(Self());
884 for (ScrollViewEffectIter effectIter = mEffects.begin(); effectIter != mEffects.end(); ++effectIter)
886 Toolkit::ScrollViewEffect effect = *effectIter;
888 // invoke Detachment request to ScrollView last
889 GetImpl(effect).Detach(self);
895 void ScrollView::ApplyConstraintToChildren(Constraint constraint)
897 ApplyConstraintToBoundActors(constraint);
900 void ScrollView::RemoveConstraintsFromChildren()
902 RemoveConstraintsFromBoundActors();
905 const RulerPtr ScrollView::GetRulerX() const
910 const RulerPtr ScrollView::GetRulerY() const
915 void ScrollView::SetRulerX(RulerPtr ruler)
919 Vector3 size = GetControlSize();
920 UpdatePropertyDomain(size);
921 UpdateMainInternalConstraint();
924 void ScrollView::SetRulerY(RulerPtr ruler)
928 Vector3 size = GetControlSize();
929 UpdatePropertyDomain(size);
930 UpdateMainInternalConstraint();
933 void ScrollView::UpdatePropertyDomain(const Vector3& size)
936 Vector3 min = mMinScroll;
937 Vector3 max = mMaxScroll;
938 bool scrollPositionChanged = false;
939 bool domainChanged = false;
941 bool canScrollVertical = false;
942 bool canScrollHorizontal = false;
943 UpdateLocalScrollProperties();
944 if(mRulerX->IsEnabled())
946 const Toolkit::RulerDomain& rulerDomain = mRulerX->GetDomain();
947 if( fabsf(min.x - rulerDomain.min) > Math::MACHINE_EPSILON_100
948 || fabsf(max.x - rulerDomain.max) > Math::MACHINE_EPSILON_100 )
950 domainChanged = true;
951 min.x = rulerDomain.min;
952 max.x = rulerDomain.max;
954 // make sure new scroll value is within new domain
955 if( mScrollPrePosition.x < min.x
956 || mScrollPrePosition.x > max.x )
958 scrollPositionChanged = true;
959 mScrollPrePosition.x = Clamp(mScrollPrePosition.x, -(max.x - size.x), -min.x);
962 if( (fabsf(rulerDomain.max - rulerDomain.min) - size.x) > Math::MACHINE_EPSILON_100 )
964 canScrollHorizontal = true;
967 else if( fabs(min.x) > Math::MACHINE_EPSILON_100
968 || fabs(max.x) > Math::MACHINE_EPSILON_100 )
970 // need to reset to 0
971 domainChanged = true;
974 canScrollHorizontal = false;
977 if(mRulerY->IsEnabled())
979 const Toolkit::RulerDomain& rulerDomain = mRulerY->GetDomain();
980 if( fabsf(min.y - rulerDomain.min) > Math::MACHINE_EPSILON_100
981 || fabsf(max.y - rulerDomain.max) > Math::MACHINE_EPSILON_100 )
983 domainChanged = true;
984 min.y = rulerDomain.min;
985 max.y = rulerDomain.max;
987 // make sure new scroll value is within new domain
988 if( mScrollPrePosition.y < min.y
989 || mScrollPrePosition.y > max.y )
991 scrollPositionChanged = true;
992 mScrollPrePosition.y = Clamp(mScrollPrePosition.y, -(max.y - size.y), -min.y);
995 if( (fabsf(rulerDomain.max - rulerDomain.min) - size.y) > Math::MACHINE_EPSILON_100 )
997 canScrollVertical = true;
1000 else if( fabs(min.y) > Math::MACHINE_EPSILON_100
1001 || fabs(max.y) > Math::MACHINE_EPSILON_100 )
1003 // need to reset to 0
1004 domainChanged = true;
1007 canScrollHorizontal = false;
1010 // avoid setting properties if possible, otherwise this will cause an entire update as well as triggering constraints using each property we update
1011 if( mCanScrollVertical != canScrollVertical )
1013 mCanScrollVertical = canScrollVertical;
1014 self.SetProperty(mPropertyCanScrollVertical, canScrollVertical);
1016 if( mCanScrollHorizontal != canScrollHorizontal )
1018 mCanScrollHorizontal = canScrollHorizontal;
1019 self.SetProperty(mPropertyCanScrollHorizontal, canScrollHorizontal);
1021 if( scrollPositionChanged )
1023 DALI_LOG_SCROLL_STATE("[0x%X] Domain Changed, setting mPropertyPrePosition To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y );
1024 self.SetProperty(mPropertyPrePosition, mScrollPrePosition);
1030 self.SetProperty(mPropertyPositionMin, mMinScroll );
1031 self.SetProperty(mPropertyPositionMax, mMaxScroll );
1035 void ScrollView::SetRulerScaleX(RulerPtr ruler)
1037 mRulerScaleX = ruler;
1038 UpdateMainInternalConstraint();
1041 void ScrollView::SetRulerScaleY(RulerPtr ruler)
1043 mRulerScaleY = ruler;
1044 UpdateMainInternalConstraint();
1047 void ScrollView::SetRulerRotation(RulerPtr ruler)
1049 mRulerRotation = ruler;
1050 UpdateMainInternalConstraint();
1053 void ScrollView::SetScrollSensitive(bool sensitive)
1055 Actor self = Self();
1056 PanGestureDetector panGesture( GetPanGestureDetector() );
1058 DALI_LOG_SCROLL_STATE("[0x%X] sensitive: before:[%d] setting[%d]", this, int(mSensitive), int(sensitive));
1060 if((!mSensitive) && (sensitive))
1062 mSensitive = sensitive;
1063 panGesture.Attach(self);
1065 else if((mSensitive) && (!sensitive))
1067 DALI_LOG_SCROLL_STATE("[0x%X] BEFORE: panning:[%d]", this, int(mPanning));
1069 // while the scroll view is panning, the state needs to be reset.
1072 PanGesture cancelGesture( Gesture::Cancelled );
1073 OnPan( cancelGesture );
1076 panGesture.Detach(self);
1077 mSensitive = sensitive;
1079 mGestureStackDepth = 0;
1080 DALI_LOG_SCROLL_STATE("[0x%X] AFTER: panning:[%d]", this, int(mPanning));
1084 void ScrollView::SetMaxOvershoot(float overshootX, float overshootY)
1086 mMaxOvershoot.x = overshootX;
1087 mMaxOvershoot.y = overshootY;
1088 mUserMaxOvershoot = mMaxOvershoot;
1089 mDefaultMaxOvershoot = false;
1090 UpdateMainInternalConstraint();
1093 void ScrollView::SetSnapOvershootAlphaFunction(AlphaFunction alpha)
1095 mSnapOvershootAlphaFunction = alpha;
1098 void ScrollView::SetSnapOvershootDuration(float duration)
1100 mSnapOvershootDuration = duration;
1103 void ScrollView::SetTouchesRequiredForPanning(unsigned int minTouches, unsigned int maxTouches, bool endOutside)
1105 PanGestureDetector panGesture( GetPanGestureDetector() );
1107 mMinTouchesForPanning = minTouches;
1108 mMaxTouchesForPanning = maxTouches;
1112 panGesture.SetMinimumTouchesRequired(minTouches);
1113 panGesture.SetMaximumTouchesRequired(maxTouches);
1117 panGesture.SetMinimumTouchesRequired(1);
1118 panGesture.SetMaximumTouchesRequired(UINT_MAX);
1122 void ScrollView::SetActorAutoSnap(bool enable)
1124 mActorAutoSnapEnabled = enable;
1127 void ScrollView::SetAutoResize(bool enable)
1129 mAutoResizeContainerEnabled = enable;
1130 // TODO: This needs a lot of issues to be addressed before working.
1133 bool ScrollView::GetWrapMode() const
1138 void ScrollView::SetWrapMode(bool enable)
1141 Self().SetProperty(mPropertyWrap, enable);
1144 int ScrollView::GetRefreshInterval() const
1146 return mScrollUpdateDistance;
1149 void ScrollView::SetRefreshInterval(int milliseconds)
1151 mScrollUpdateDistance = milliseconds;
1154 int ScrollView::GetScrollUpdateDistance() const
1156 return mScrollUpdateDistance;
1159 void ScrollView::SetScrollUpdateDistance(int distance)
1161 mScrollUpdateDistance = distance;
1164 bool ScrollView::GetAxisAutoLock() const
1166 return mAxisAutoLock;
1169 void ScrollView::SetAxisAutoLock(bool enable)
1171 mAxisAutoLock = enable;
1172 UpdateMainInternalConstraint();
1175 float ScrollView::GetAxisAutoLockGradient() const
1177 return mAxisAutoLockGradient;
1180 void ScrollView::SetAxisAutoLockGradient(float gradient)
1182 DALI_ASSERT_DEBUG( gradient >= 0.0f && gradient <= 1.0f );
1183 mAxisAutoLockGradient = gradient;
1184 UpdateMainInternalConstraint();
1187 float ScrollView::GetFrictionCoefficient() const
1189 return mFrictionCoefficient;
1192 void ScrollView::SetFrictionCoefficient(float friction)
1194 DALI_ASSERT_DEBUG( friction > 0.0f );
1195 mFrictionCoefficient = friction;
1198 float ScrollView::GetFlickSpeedCoefficient() const
1200 return mFlickSpeedCoefficient;
1203 void ScrollView::SetFlickSpeedCoefficient(float speed)
1205 mFlickSpeedCoefficient = speed;
1208 Vector2 ScrollView::GetMinimumDistanceForFlick() const
1210 return mMinFlickDistance;
1213 void ScrollView::SetMinimumDistanceForFlick( const Vector2& distance )
1215 mMinFlickDistance = distance;
1218 float ScrollView::GetMinimumSpeedForFlick() const
1220 return mFlickSpeedThreshold;
1223 void ScrollView::SetMinimumSpeedForFlick( float speed )
1225 mFlickSpeedThreshold = speed;
1228 float ScrollView::GetMaxFlickSpeed() const
1230 return mMaxFlickSpeed;
1233 void ScrollView::SetMaxFlickSpeed(float speed)
1235 mMaxFlickSpeed = speed;
1238 void ScrollView::SetMouseWheelScrollDistanceStep(Vector2 step)
1240 mMouseWheelScrollDistanceStep = step;
1243 Vector2 ScrollView::GetMouseWheelScrollDistanceStep() const
1245 return mMouseWheelScrollDistanceStep;
1248 unsigned int ScrollView::GetCurrentPage() const
1250 // in case animation is currently taking place.
1251 Vector3 position = GetPropertyPosition();
1253 Actor self = Self();
1254 unsigned int page = 0;
1255 unsigned int pagesPerVolume = 1;
1256 unsigned int volume = 0;
1258 // if rulerX is enabled, then get page count (columns)
1259 page = mRulerX->GetPageFromPosition(-position.x, mWrapMode);
1260 volume = mRulerY->GetPageFromPosition(-position.y, mWrapMode);
1261 pagesPerVolume = mRulerX->GetTotalPages();
1263 return volume * pagesPerVolume + page;
1266 Vector3 ScrollView::GetCurrentScrollPosition() const
1268 return -GetPropertyPosition();
1271 void ScrollView::SetScrollPosition(const Vector3& position)
1273 mScrollPrePosition = position;
1276 Vector3 ScrollView::GetCurrentScrollScale() const
1278 // in case animation is currently taking place.
1279 return GetPropertyScale();
1282 Vector3 ScrollView::GetDomainSize() const
1284 Vector3 size = Self().GetCurrentSize();
1286 const RulerDomain& xDomain = GetRulerX()->GetDomain();
1287 const RulerDomain& yDomain = GetRulerY()->GetDomain();
1289 Vector3 domainSize = Vector3( xDomain.max - xDomain.min, yDomain.max - yDomain.min, 0.0f ) - size;
1293 void ScrollView::TransformTo(const Vector3& position, const Vector3& scale, float rotation,
1294 DirectionBias horizontalBias, DirectionBias verticalBias)
1296 TransformTo(position, scale, rotation, mSnapDuration, horizontalBias, verticalBias);
1299 void ScrollView::TransformTo(const Vector3& position, const Vector3& scale, float rotation, float duration,
1300 DirectionBias horizontalBias, DirectionBias verticalBias)
1302 Actor self( Self() );
1304 // Guard against destruction during signal emission
1305 // Note that Emit() methods are called indirectly e.g. from within ScrollView::AnimateTo()
1306 Toolkit::ScrollView handle( GetOwner() );
1308 DALI_LOG_SCROLL_STATE("[0x%X] pos[%.2f,%.2f], scale[%.2f,%.2f], rot[%.2f], duration[%.2f] bias[%d, %d]",
1309 this, position.x, position.y, scale.x, scale.y, rotation, duration, int(horizontalBias), int(verticalBias));
1311 Vector3 currentScrollPosition = GetCurrentScrollPosition();
1312 self.SetProperty( mPropertyScrollStartPagePosition, currentScrollPosition );
1314 if( mScrolling ) // are we interrupting a current scroll?
1316 // set mScrolling to false, in case user has code that interrogates mScrolling Getter() in complete.
1318 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignalV2 1 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
1319 mScrollCompletedSignalV2.Emit( currentScrollPosition );
1322 if( mPanning ) // are we interrupting a current pan?
1324 DALI_LOG_SCROLL_STATE("[0x%X] Interrupting Pan, set to false", this );
1326 mGestureStackDepth = 0;
1327 self.SetProperty( mPropertyPanning, false );
1329 if( mScrollMainInternalPrePositionConstraint )
1331 self.RemoveConstraint(mScrollMainInternalPrePositionConstraint);
1335 self.SetProperty(mPropertyScrolling, true);
1338 DALI_LOG_SCROLL_STATE("[0x%X] mScrollStartedSignalV2 1 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
1339 mScrollStartedSignalV2.Emit( currentScrollPosition );
1340 bool animating = AnimateTo(-position,
1341 Vector3::ONE * duration,
1343 Vector3::ONE * duration,
1354 // if not animating, then this pan has completed right now.
1355 self.SetProperty(mPropertyScrolling, false);
1358 // If we have no duration, then in the next update frame, we will be at the position specified as we just set.
1359 // In this scenario, we cannot return the currentScrollPosition as this is out-of-date and should instead return the requested final position
1360 Vector3 completedPosition( currentScrollPosition );
1361 if( duration <= Math::MACHINE_EPSILON_10 )
1363 completedPosition = position;
1366 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignalV2 2 [%.2f, %.2f]", this, completedPosition.x, completedPosition.y);
1367 SetScrollUpdateNotification(false);
1368 mScrollCompletedSignalV2.Emit( completedPosition );
1372 void ScrollView::ScrollTo(const Vector3& position)
1374 ScrollTo(position, mSnapDuration );
1377 void ScrollView::ScrollTo(const Vector3& position, float duration)
1379 ScrollTo(position, duration, DirectionBiasNone, DirectionBiasNone);
1382 void ScrollView::ScrollTo(const Vector3& position, float duration,
1383 DirectionBias horizontalBias, DirectionBias verticalBias)
1385 DALI_LOG_SCROLL_STATE("[0x%X] position[%.2f, %.2f] duration[%.2f]",
1386 this, position.x, position.y, duration, int(horizontalBias), int(verticalBias));
1388 TransformTo(position, mScrollPostScale, mScrollPostRotation, duration, horizontalBias, verticalBias);
1391 void ScrollView::ScrollTo(unsigned int page)
1393 ScrollTo(page, mSnapDuration);
1396 void ScrollView::ScrollTo(unsigned int page, float duration, DirectionBias bias)
1399 unsigned int volume;
1400 unsigned int libraries;
1402 // The position to scroll to is continuous and linear
1403 // unless a domain has been enabled on the X axis.
1404 // or if WrapMode has been enabled.
1405 bool carryX = mRulerX->GetDomain().enabled | mWrapMode;
1406 bool carryY = mRulerY->GetDomain().enabled | mWrapMode;
1408 position.x = mRulerX->GetPositionFromPage(page, volume, carryX);
1409 position.y = mRulerY->GetPositionFromPage(volume, libraries, carryY);
1411 ScrollTo(position, duration, bias, bias);
1414 void ScrollView::ScrollTo(Actor &actor)
1416 ScrollTo(actor, mSnapDuration);
1419 void ScrollView::ScrollTo(Actor &actor, float duration)
1421 DALI_ASSERT_ALWAYS(actor.GetParent() == Self());
1423 Actor self = Self();
1424 Vector3 size = self.GetCurrentSize();
1425 Vector3 position = actor.GetCurrentPosition();
1426 position -= GetPropertyPrePosition();
1428 ScrollTo(Vector3(position.x - size.width * 0.5f, position.y - size.height * 0.5f, 0.0f), duration);
1431 Actor ScrollView::FindClosestActor()
1433 Actor self = Self();
1434 Vector3 size = self.GetCurrentSize();
1436 return FindClosestActorToPosition(Vector3(size.width * 0.5f,size.height * 0.5f,0.0f));
1439 Actor ScrollView::FindClosestActorToPosition(const Vector3& position, FindDirection dirX, FindDirection dirY, FindDirection dirZ)
1442 float closestDistance2 = 0.0f;
1443 Vector3 actualPosition = position;
1445 unsigned int numChildren = Self().GetChildCount();
1447 for(unsigned int i = 0; i < numChildren; ++i)
1449 Actor child = Self().GetChildAt(i);
1451 if(mInternalActor == child) // ignore internal actor.
1456 Vector3 childPosition = GetPositionOfAnchor(child, AnchorPoint::CENTER);
1458 Vector3 delta = childPosition - actualPosition;
1460 // X-axis checking (only find Actors to the [dirX] of actualPosition)
1461 if(dirX > All) // != All,None
1463 FindDirection deltaH = delta.x > 0 ? Right : Left;
1470 // Y-axis checking (only find Actors to the [dirY] of actualPosition)
1471 if(dirY > All) // != All,None
1473 FindDirection deltaV = delta.y > 0 ? Down : Up;
1480 // Z-axis checking (only find Actors to the [dirZ] of actualPosition)
1481 if(dirZ > All) // != All,None
1483 FindDirection deltaV = delta.y > 0 ? In : Out;
1490 // compare child to closest child in terms of distance.
1491 float distance2 = 0.0f;
1493 // distance2 = the Square of the relevant dimensions of delta
1496 distance2 += delta.x * delta.x;
1501 distance2 += delta.y * delta.y;
1506 distance2 += delta.z * delta.z;
1509 if(closestChild) // Next time.
1511 if(distance2 < closestDistance2)
1513 closestChild = child;
1514 closestDistance2 = distance2;
1519 closestChild = child;
1520 closestDistance2 = distance2;
1524 return closestChild;
1527 bool ScrollView::ScrollToSnapPoint()
1529 DALI_LOG_SCROLL_STATE("[0x%X]", this );
1530 Vector2 stationaryVelocity = Vector2(0.0f, 0.0f);
1531 return SnapWithVelocity( stationaryVelocity );
1534 void ScrollView::ScaleTo(const Vector3& scale)
1536 ScaleTo(scale, mSnapDuration);
1539 void ScrollView::ScaleTo(const Vector3& scale, float duration)
1541 TransformTo(mScrollPostPosition, scale, mScrollPostRotation, duration);
1545 // TODO: In situations where axes are different (X snap, Y free)
1546 // Each axis should really have their own independent animation (time and equation)
1547 // Consider, X axis snapping to nearest grid point (EaseOut over fixed time)
1548 // Consider, Y axis simulating physics to arrive at a point (Physics equation over variable time)
1549 // Currently, the axes have been split however, they both use the same EaseOut equation.
1550 bool ScrollView::SnapWithVelocity(Vector2 velocity)
1552 // Animator takes over now, touches are assumed not to interfere.
1553 // And if touches do interfere, then we'll stop animation, update PrePosition
1554 // to current mScroll's properties, and then resume.
1555 // Note: For Flicking this may work a bit different...
1557 float angle = atan2(velocity.y, velocity.x);
1558 float speed2 = velocity.LengthSquared();
1559 AlphaFunction alphaFunction = mSnapAlphaFunction;
1560 Vector3 positionDuration = Vector3::ONE * mSnapDuration;
1561 Vector3 scaleDuration = Vector3::ONE * mSnapDuration;
1562 float rotationDuration = mSnapDuration;
1565 FindDirection horizontal = None;
1566 FindDirection vertical = None;
1568 // orthoAngleRange = Angle tolerance within the Exact N,E,S,W direction
1569 // that will be accepted as a general N,E,S,W flick direction.
1571 const float orthoAngleRange = FLICK_ORTHO_ANGLE_RANGE * M_PI / 180.0f;
1572 const float flickSpeedThreshold2 = mFlickSpeedThreshold * mFlickSpeedThreshold;
1574 Vector3 positionSnap = mScrollPrePosition;
1576 // Flick logic X Axis
1578 if(mRulerX->IsEnabled() && mLockAxis != LockHorizontal)
1582 if( speed2 > flickSpeedThreshold2 || // exceeds flick threshold
1583 mInAccessibilityPan ) // With AccessibilityPan its easier to move between snap positions
1585 if((angle >= -orthoAngleRange) && (angle < orthoAngleRange)) // Swiping East
1587 biasX = 0.0f, horizontal = Left;
1589 // This guards against an error where no movement occurs, due to the flick finishing
1590 // before the update-thread has advanced mScrollPostPosition past the the previous snap point.
1591 positionSnap.x += 1.0f;
1593 else if((angle >= M_PI-orthoAngleRange) || (angle < -M_PI+orthoAngleRange)) // Swiping West
1595 biasX = 1.0f, horizontal = Right;
1597 // This guards against an error where no movement occurs, due to the flick finishing
1598 // before the update-thread has advanced mScrollPostPosition past the the previous snap point.
1599 positionSnap.x -= 1.0f;
1604 // Flick logic Y Axis
1606 if(mRulerY->IsEnabled() && mLockAxis != LockVertical)
1610 if( speed2 > flickSpeedThreshold2 || // exceeds flick threshold
1611 mInAccessibilityPan ) // With AccessibilityPan its easier to move between snap positions
1613 if((angle >= M_PI_2-orthoAngleRange) && (angle < M_PI_2+orthoAngleRange)) // Swiping South
1615 biasY = 0.0f, vertical = Up;
1617 else if((angle >= -M_PI_2-orthoAngleRange) && (angle < -M_PI_2+orthoAngleRange)) // Swiping North
1619 biasY = 1.0f, vertical = Down;
1624 // isFlick: Whether this gesture is a flick or not.
1625 bool isFlick = (horizontal != All || vertical != All);
1626 // isFreeFlick: Whether this gesture is a flick under free panning criteria.
1627 bool isFreeFlick = velocity.LengthSquared() > (FREE_FLICK_SPEED_THRESHOLD*FREE_FLICK_SPEED_THRESHOLD);
1629 if(isFlick || isFreeFlick)
1631 positionDuration = Vector3::ONE * mFlickDuration;
1632 alphaFunction = mFlickAlphaFunction;
1635 // Calculate next positionSnap ////////////////////////////////////////////////////////////
1637 if(mActorAutoSnapEnabled)
1639 Vector3 size = Self().GetCurrentSize();
1641 Actor child = FindClosestActorToPosition( Vector3(size.width * 0.5f,size.height * 0.5f,0.0f), horizontal, vertical );
1643 if(!child && isFlick )
1645 // If we conducted a direction limited search and found no actor, then just snap to the closest actor.
1646 child = FindClosestActorToPosition( Vector3(size.width * 0.5f,size.height * 0.5f,0.0f) );
1651 Vector3 position = Self().GetProperty<Vector3>(mPropertyPosition);
1653 // Get center-point of the Actor.
1654 Vector3 childPosition = GetPositionOfAnchor(child, AnchorPoint::CENTER);
1656 if(mRulerX->IsEnabled())
1658 positionSnap.x = position.x - childPosition.x + size.width * 0.5f;
1660 if(mRulerY->IsEnabled())
1662 positionSnap.y = position.y - childPosition.y + size.height * 0.5f;
1667 Vector3 startPosition = positionSnap;
1668 positionSnap.x = -mRulerX->Snap(-positionSnap.x, biasX); // NOTE: X & Y rulers think in -ve coordinate system.
1669 positionSnap.y = -mRulerY->Snap(-positionSnap.y, biasY); // That is scrolling RIGHT (e.g. 100.0, 0.0) means moving LEFT.
1671 Vector3 clampDelta(Vector3::ZERO);
1672 ClampPosition(positionSnap);
1674 if( (mRulerX->GetType() == Ruler::Free || mRulerY->GetType() == Ruler::Free)
1675 && isFreeFlick && !mActorAutoSnapEnabled)
1677 // Calculate target position based on velocity of flick.
1679 // a = Deceleration (Set to diagonal stage length * friction coefficient)
1680 // u = Initial Velocity (Flick velocity)
1681 // v = 0 (Final Velocity)
1682 // t = Time (Velocity / Deceleration)
1683 Vector2 stageSize = Stage::GetCurrent().GetSize();
1684 float stageLength = Vector3(stageSize.x, stageSize.y, 0.0f).Length();
1685 float a = (stageLength * mFrictionCoefficient);
1686 Vector3 u = Vector3(velocity.x, velocity.y, 0.0f) * mFlickSpeedCoefficient;
1687 float speed = u.Length();
1690 // TODO: Change this to a decay function. (faster you flick, the slower it should be)
1691 speed = std::min(speed, stageLength * mMaxFlickSpeed );
1693 alphaFunction = ConstantDecelerationAlphaFunction;
1695 float t = speed / a;
1697 if(mRulerX->IsEnabled() && mRulerX->GetType() == Ruler::Free)
1699 positionSnap.x += t*u.x*0.5f;
1702 if(mRulerY->IsEnabled() && mRulerY->GetType() == Ruler::Free)
1704 positionSnap.y += t*u.y*0.5f;
1707 clampDelta = positionSnap;
1708 ClampPosition(positionSnap);
1709 if((positionSnap - startPosition).LengthSquared() > Math::MACHINE_EPSILON_0)
1711 clampDelta -= positionSnap;
1712 clampDelta.x = clampDelta.x > 0.0f ? std::min(clampDelta.x, mMaxOvershoot.x) : std::max(clampDelta.x, -mMaxOvershoot.x);
1713 clampDelta.y = clampDelta.y > 0.0f ? std::min(clampDelta.y, mMaxOvershoot.y) : std::max(clampDelta.y, -mMaxOvershoot.y);
1717 clampDelta = Vector3::ZERO;
1720 // If Axis is Free and has velocity, then calculate time taken
1721 // to reach target based on velocity in axis.
1722 if(mRulerX->IsEnabled() && mRulerX->GetType() == Ruler::Free)
1724 float deltaX = fabsf(startPosition.x - positionSnap.x);
1726 if(fabsf(u.x) > Math::MACHINE_EPSILON_1)
1728 positionDuration.x = fabsf(deltaX / u.x);
1732 positionDuration.x = 0;
1736 if(mRulerY->IsEnabled() && mRulerY->GetType() == Ruler::Free)
1738 float deltaY = fabsf(startPosition.y - positionSnap.y);
1740 if(fabsf(u.y) > Math::MACHINE_EPSILON_1)
1742 positionDuration.y = fabsf(deltaY / u.y);
1746 positionDuration.y = 0;
1750 positionSnap += clampDelta;
1752 // Scale Snap ///////////////////////////////////////////////////////////////
1753 Vector3 scaleSnap = mScrollPostScale;
1755 scaleSnap.x = mRulerScaleX->Snap(scaleSnap.x);
1756 scaleSnap.y = mRulerScaleY->Snap(scaleSnap.y);
1758 ClampScale(scaleSnap);
1760 // Rotation Snap ////////////////////////////////////////////////////////////
1761 float rotationSnap = mScrollPostRotation;
1762 // TODO: implement rotation snap
1764 bool animating = AnimateTo(positionSnap, positionDuration,
1765 scaleSnap, scaleDuration,
1766 rotationSnap, rotationDuration,
1767 alphaFunction, false,
1768 DirectionBiasNone, DirectionBiasNone,
1769 isFlick || isFreeFlick ? Flick : Snap);
1774 void ScrollView::StopAnimation(void)
1776 // Clear Snap animation if exists.
1777 StopAnimation(mSnapAnimation);
1778 StopAnimation(mInternalXAnimation);
1779 StopAnimation(mInternalYAnimation);
1780 mScrollStateFlags = 0;
1781 // remove scroll animation flags
1782 HandleStoppedAnimation();
1785 void ScrollView::StopAnimation(Animation& animation)
1794 bool ScrollView::AnimateTo(const Vector3& position, const Vector3& positionDuration,
1795 const Vector3& scale, const Vector3& scaleDuration,
1796 float rotation, float rotationDuration,
1797 AlphaFunction alpha, bool findShortcuts,
1798 DirectionBias horizontalBias, DirectionBias verticalBias,
1801 // Here we perform an animation on a number of properties (depending on which have changed)
1802 // The animation is applied to all ScrollBases
1803 Actor self = Self();
1804 mScrollTargetPosition = position;
1805 float totalDuration = 0.0f;
1807 bool positionChanged = (mScrollTargetPosition != mScrollPostPosition);
1808 bool scaleChanged = (scale != mScrollPostScale);
1809 bool rotationChanged = fabsf(rotation - mScrollPostRotation) > Math::MACHINE_EPSILON_0;
1813 totalDuration = std::max(totalDuration, positionDuration.x);
1814 totalDuration = std::max(totalDuration, positionDuration.y);
1818 // try to animate for a frame, on some occasions update will be changing scroll value while event side thinks it hasnt changed
1819 totalDuration = 0.01f;
1820 positionChanged = true;
1825 totalDuration = std::max(totalDuration, scaleDuration.x);
1826 totalDuration = std::max(totalDuration, scaleDuration.y);
1831 totalDuration = std::max(totalDuration, rotationDuration);
1835 // Position Delta ///////////////////////////////////////////////////////
1838 if(mWrapMode && findShortcuts)
1840 // In Wrap Mode, the shortest distance is a little less intuitive...
1841 const RulerDomain rulerDomainX = mRulerX->GetDomain();
1842 const RulerDomain rulerDomainY = mRulerY->GetDomain();
1844 if(mRulerX->IsEnabled())
1846 float dir = VectorInDomain(-mScrollPrePosition.x, -mScrollTargetPosition.x, rulerDomainX.min, rulerDomainX.max, horizontalBias);
1847 mScrollTargetPosition.x = mScrollPrePosition.x + -dir;
1850 if(mRulerY->IsEnabled())
1852 float dir = VectorInDomain(-mScrollPrePosition.y, -mScrollTargetPosition.y, rulerDomainY.min, rulerDomainY.max, verticalBias);
1853 mScrollTargetPosition.y = mScrollPrePosition.y + -dir;
1857 // note we have two separate animations for X & Y, this deals with sliding diagonally and hitting
1858 // a horizonal/vertical wall.delay
1859 AnimateInternalXTo(mScrollTargetPosition.x, positionDuration.x, alpha);
1860 AnimateInternalYTo(mScrollTargetPosition.y, positionDuration.y, alpha);
1862 if( !(mScrollStateFlags & SCROLL_ANIMATION_FLAGS) )
1864 DALI_LOG_SCROLL_STATE("[0x%X] Setting mPropertyPrePosition To[%.2f, %.2f]", this, mScrollTargetPosition.x, mScrollTargetPosition.y );
1865 self.SetProperty(mPropertyPrePosition, mScrollTargetPosition);
1866 mScrollPrePosition = mScrollTargetPosition;
1867 mScrollPostPosition = mScrollTargetPosition;
1868 WrapPosition(mScrollPostPosition);
1871 DALI_LOG_SCROLL_STATE("[0x%X] position-changed, mScrollTargetPosition[%.2f, %.2f], mScrollPrePosition[%.2f, %.2f], mScrollPostPosition[%.2f, %.2f]", this, mScrollTargetPosition.x, mScrollTargetPosition.y, mScrollPrePosition.x, mScrollPrePosition.y, mScrollPostPosition.x, mScrollPostPosition.y );
1872 DALI_LOG_SCROLL_STATE("[0x%X] mPropertyPrePosition[%.2f, %.2f], mPropertyPosition[%.2f, %.2f]", this, self.GetProperty( mPropertyPrePosition ).Get<Vector3>().x, self.GetProperty( mPropertyPrePosition ).Get<Vector3>().y, self.GetProperty( mPropertyPosition ).Get<Vector3>().x, self.GetProperty( mPropertyPosition ).Get<Vector3>().y );
1875 // Scale Delta ///////////////////////////////////////////////////////
1878 if(totalDuration > Math::MACHINE_EPSILON_1)
1880 mSnapAnimation = Animation::New(totalDuration);
1881 mSnapAnimation.FinishedSignal().Connect(this, &ScrollView::OnScrollAnimationFinished);
1882 // TODO: for non-uniform scaling to different bounds e.g. scaling a square to a 4:3 aspect ratio screen with a velocity
1883 // the height will hit first, and then the width, so that would require two different animation times just like position.
1884 mSnapAnimation.AnimateTo( Property(self, mPropertyScale), scale, alpha, TimePeriod(0.0f, scaleDuration.x));
1886 mSnapAnimation.AnimateTo( Property(self, mPropertyTime), totalDuration, AlphaFunctions::Linear );
1887 mSnapAnimation.Play();
1891 self.SetProperty(mPropertyScale, scale);
1893 mScrollPreScale = mScrollPostScale = scale;
1896 SetScrollUpdateNotification(true);
1898 // Always send a snap event when AnimateTo is called.
1899 Toolkit::ScrollView::SnapEvent snapEvent;
1900 snapEvent.type = snapType;
1901 snapEvent.position = -mScrollTargetPosition;
1902 snapEvent.scale = scale;
1903 snapEvent.rotation = rotation;
1904 snapEvent.duration = totalDuration;
1906 DALI_LOG_SCROLL_STATE("[0x%X] mSnapStartedSignalV2 [%.2f, %.2f]", this, snapEvent.position.x, snapEvent.position.y);
1907 mSnapStartedSignalV2.Emit( snapEvent );
1909 return (mScrollStateFlags & SCROLL_ANIMATION_FLAGS) != 0;
1912 void ScrollView::SetOvershootEnabled(bool enabled)
1914 if(enabled && !mOvershootIndicator)
1916 mOvershootIndicator = ScrollOvershootIndicator::New();
1920 mMaxOvershoot = OVERSCROLL_CLAMP;
1921 mOvershootIndicator->AttachToScrollable(*this);
1925 mMaxOvershoot = mUserMaxOvershoot;
1926 mOvershootIndicator->DetachFromScrollable(*this);
1928 UpdateMainInternalConstraint();
1931 void ScrollView::AddOverlay(Actor actor)
1933 mInternalActor.Add( actor );
1936 void ScrollView::RemoveOverlay(Actor actor)
1938 mInternalActor.Remove( actor );
1941 void ScrollView::SetOvershootEffectColor( const Vector4& color )
1943 mOvershootEffectColor = color;
1944 if( mOvershootIndicator )
1946 mOvershootIndicator->SetOvershootEffectColor( color );
1950 void ScrollView::SetScrollingDirection( Radian direction, Radian threshold )
1952 PanGestureDetector panGesture( GetPanGestureDetector() );
1954 // First remove just in case we have some set, then add.
1955 panGesture.RemoveDirection( direction );
1956 panGesture.AddDirection( direction, threshold );
1959 void ScrollView::RemoveScrollingDirection( Radian direction )
1961 PanGestureDetector panGesture( GetPanGestureDetector() );
1962 panGesture.RemoveDirection( direction );
1965 Toolkit::ScrollView::SnapStartedSignalV2& ScrollView::SnapStartedSignal()
1967 return mSnapStartedSignalV2;
1970 void ScrollView::FindAndUnbindActor(Actor child)
1975 Vector3 ScrollView::GetPropertyPrePosition() const
1977 Vector3 position = Self().GetProperty<Vector3>(mPropertyPrePosition);
1978 WrapPosition(position);
1982 Vector3 ScrollView::GetPropertyPosition() const
1984 Vector3 position = Self().GetProperty<Vector3>(mPropertyPosition);
1985 WrapPosition(position);
1990 Vector3 ScrollView::GetPropertyScale() const
1992 return Self().GetProperty<Vector3>(mPropertyScale);
1995 void ScrollView::HandleStoppedAnimation()
1997 SetScrollUpdateNotification(false);
2000 void ScrollView::HandleSnapAnimationFinished()
2002 // Emit Signal that scrolling has completed.
2004 Actor self = Self();
2005 self.SetProperty(mPropertyScrolling, false);
2007 Vector3 deltaPosition(mScrollPrePosition);
2009 UpdateLocalScrollProperties();
2010 WrapPosition(mScrollPrePosition);
2011 DALI_LOG_SCROLL_STATE("[0x%X] Setting mPropertyPrePosition To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y );
2012 self.SetProperty(mPropertyPrePosition, mScrollPrePosition);
2014 Vector3 currentScrollPosition = GetCurrentScrollPosition();
2015 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignalV2 3 current[%.2f, %.2f], mScrollTargetPosition[%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y, -mScrollTargetPosition.x, -mScrollTargetPosition.y );
2016 mScrollCompletedSignalV2.Emit( currentScrollPosition );
2018 mDomainOffset += deltaPosition - mScrollPostPosition;
2019 self.SetProperty(mPropertyDomainOffset, mDomainOffset);
2020 HandleStoppedAnimation();
2023 void ScrollView::SetScrollUpdateNotification( bool enabled )
2025 Actor self = Self();
2026 if( mScrollXUpdateNotification )
2028 // disconnect now to avoid a notification before removed from update thread
2029 mScrollXUpdateNotification.NotifySignal().Disconnect(this, &ScrollView::OnScrollUpdateNotification);
2030 self.RemovePropertyNotification(mScrollXUpdateNotification);
2031 mScrollXUpdateNotification.Reset();
2035 mScrollXUpdateNotification = self.AddPropertyNotification(mPropertyPosition, 0, StepCondition(mScrollUpdateDistance, 0.0f));
2036 mScrollXUpdateNotification.NotifySignal().Connect( this, &ScrollView::OnScrollUpdateNotification );
2038 if( mScrollYUpdateNotification )
2040 // disconnect now to avoid a notification before removed from update thread
2041 mScrollYUpdateNotification.NotifySignal().Disconnect(this, &ScrollView::OnScrollUpdateNotification);
2042 self.RemovePropertyNotification(mScrollYUpdateNotification);
2043 mScrollYUpdateNotification.Reset();
2047 mScrollYUpdateNotification = self.AddPropertyNotification(mPropertyPosition, 1, StepCondition(mScrollUpdateDistance, 0.0f));
2048 mScrollYUpdateNotification.NotifySignal().Connect( this, &ScrollView::OnScrollUpdateNotification );
2052 void ScrollView::OnScrollUpdateNotification(Dali::PropertyNotification& source)
2054 // Guard against destruction during signal emission
2055 Toolkit::ScrollView handle( GetOwner() );
2057 Vector3 currentScrollPosition = GetCurrentScrollPosition();
2058 mScrollUpdatedSignalV2.Emit( currentScrollPosition );
2061 bool ScrollView::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
2063 Dali::BaseHandle handle( object );
2065 bool connected( true );
2066 Toolkit::ScrollView view = Toolkit::ScrollView::DownCast( handle );
2068 if( Toolkit::ScrollView::SIGNAL_SNAP_STARTED == signalName )
2070 view.SnapStartedSignal().Connect( tracker, functor );
2074 // signalName does not match any signal
2081 void ScrollView::OnSizeAnimation(Animation& animation, const Vector3& targetSize)
2083 // need to update domain properties for new size
2084 UpdatePropertyDomain(targetSize);
2087 void ScrollView::OnControlSizeSet( const Vector3& size )
2089 // need to update domain properties for new size
2090 if( mDefaultMaxOvershoot )
2092 mUserMaxOvershoot.x = size.x * 0.5f;
2093 mUserMaxOvershoot.y = size.y * 0.5f;
2094 if( !IsScrollComponentEnabled(Toolkit::Scrollable::OvershootIndicator) )
2096 mMaxOvershoot = mUserMaxOvershoot;
2099 UpdatePropertyDomain(size);
2100 UpdateMainInternalConstraint();
2101 if( IsScrollComponentEnabled(Toolkit::Scrollable::OvershootIndicator) )
2103 mOvershootIndicator->Reset();
2107 void ScrollView::OnChildAdd(Actor& child)
2115 void ScrollView::OnChildRemove(Actor& child)
2117 // TODO: Actor needs a RemoveConstraint method to take out an individual constraint.
2121 void ScrollView::OnPropertySet( Property::Index index, Property::Value propertyValue )
2123 Actor self = Self();
2124 if( index == mPropertyX )
2126 self.GetProperty(mPropertyPrePosition).Get(mScrollPrePosition);
2127 propertyValue.Get(mScrollPrePosition.x);
2128 DALI_LOG_SCROLL_STATE("[0x%X] Setting mPropertyPrePosition To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y );
2129 self.SetProperty(mPropertyPrePosition, mScrollPrePosition);
2131 else if( index == mPropertyY )
2133 self.GetProperty(mPropertyPrePosition).Get(mScrollPrePosition);
2134 propertyValue.Get(mScrollPrePosition.y);
2135 DALI_LOG_SCROLL_STATE("[0x%X] Setting mPropertyPrePosition To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y );
2136 self.SetProperty(mPropertyPrePosition, mScrollPrePosition);
2138 else if( index == mPropertyPrePosition )
2140 DALI_LOG_SCROLL_STATE("[0x%X]: mPropertyPrePosition[%.2f, %.2f]", this, propertyValue.Get<Vector3>().x, propertyValue.Get<Vector3>().y);
2141 propertyValue.Get(mScrollPrePosition);
2145 void ScrollView::StartTouchDownTimer()
2147 if ( !mTouchDownTimer )
2149 mTouchDownTimer = Timer::New( TOUCH_DOWN_TIMER_INTERVAL );
2150 mTouchDownTimer.TickSignal().Connect( this, &ScrollView::OnTouchDownTimeout );
2153 mTouchDownTimer.Start();
2156 void ScrollView::StopTouchDownTimer()
2158 if ( mTouchDownTimer )
2160 mTouchDownTimer.Stop();
2164 bool ScrollView::OnTouchDownTimeout()
2166 DALI_LOG_SCROLL_STATE("[0x%X]", this);
2168 mTouchDownTimeoutReached = true;
2170 unsigned int currentScrollStateFlags( mScrollStateFlags ); // Cleared in StopAnimation so keep local copy for comparison
2171 if( currentScrollStateFlags & (SCROLL_ANIMATION_FLAGS | SNAP_ANIMATION_FLAGS) )
2173 DALI_LOG_SCROLL_STATE("[0x%X] Scrolling Or snapping flags set, stopping animation", this);
2176 if( currentScrollStateFlags & SCROLL_ANIMATION_FLAGS )
2178 DALI_LOG_SCROLL_STATE("[0x%X] Scrolling flags set, emitting signal", this);
2180 mScrollInterrupted = true;
2181 // reset domain offset as scrolling from original plane.
2182 mDomainOffset = Vector3::ZERO;
2183 Self().SetProperty(mPropertyDomainOffset, Vector3::ZERO);
2185 UpdateLocalScrollProperties();
2186 Vector3 currentScrollPosition = GetCurrentScrollPosition();
2187 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignalV2 4 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
2188 mScrollCompletedSignalV2.Emit( currentScrollPosition );
2195 bool ScrollView::OnTouchEvent(const TouchEvent& event)
2199 DALI_LOG_SCROLL_STATE("[0x%X], Not Sensitive, ignoring", this);
2201 // Ignore this touch event, if scrollview is insensitive.
2205 // Ignore events with multiple-touch points
2206 if (event.GetPointCount() != 1)
2208 DALI_LOG_SCROLL_STATE("[0x%X], multiple touch, ignoring", this);
2213 const TouchPoint::State pointState = event.GetPoint(0).state;
2214 if( pointState == TouchPoint::Down )
2216 DALI_LOG_SCROLL_STATE("[0x%X] Down", this);
2218 if(mGestureStackDepth==0)
2220 mTouchDownTime = event.time;
2222 // This allows time for a pan-gesture to start, to avoid breaking snap-animation behavior with fast flicks.
2223 // If touch-down does not become a pan (after timeout interval), then snap-animation can be interrupted.
2224 mTouchDownTimeoutReached = false;
2225 mScrollInterrupted = false;
2226 StartTouchDownTimer();
2229 else if( ( pointState == TouchPoint::Up ) ||
2230 ( ( pointState == TouchPoint::Interrupted ) && ( event.GetPoint(0).hitActor == Self() ) ) )
2232 DALI_LOG_SCROLL_STATE("[0x%X] %s", this, ( ( pointState == TouchPoint::Up ) ? "Up" : "Interrupted" ) );
2234 StopTouchDownTimer();
2236 // if the user touches and releases without enough movement to go
2237 // into a gesture state, then we should snap to nearest point.
2238 // otherwise our scroll could be stopped (interrupted) half way through an animation.
2239 if(mGestureStackDepth==0 && mTouchDownTimeoutReached)
2241 if( ( event.GetPoint(0).state == TouchPoint::Interrupted ) ||
2242 ( ( event.time - mTouchDownTime ) >= MINIMUM_TIME_BETWEEN_DOWN_AND_UP_FOR_RESET ) )
2244 // Reset the velocity only if down was received a while ago
2245 mLastVelocity = Vector2( 0.0f, 0.0f );
2248 UpdateLocalScrollProperties();
2249 // Only finish the transform if scrolling was interrupted on down or if we are scrolling
2250 if ( mScrollInterrupted || mScrolling )
2252 DALI_LOG_SCROLL_STATE("[0x%X] Calling FinishTransform", this);
2257 mTouchDownTimeoutReached = false;
2258 mScrollInterrupted = false;
2264 bool ScrollView::OnMouseWheelEvent(const MouseWheelEvent& event)
2268 // Ignore this mouse wheel event, if scrollview is insensitive.
2272 Vector3 targetScrollPosition = GetPropertyPosition();
2274 if(mRulerX->IsEnabled() && !mRulerY->IsEnabled())
2276 // If only the ruler in the X axis is enabled, scroll in the X axis.
2277 if(mRulerX->GetType() == Ruler::Free)
2279 // Free panning mode
2280 targetScrollPosition.x += event.z * mMouseWheelScrollDistanceStep.x;
2281 ClampPosition(targetScrollPosition);
2282 ScrollTo(-targetScrollPosition);
2284 else if(!mScrolling)
2286 // Snap mode, only respond to the event when the previous snap animation is finished.
2287 ScrollTo(GetCurrentPage() - event.z);
2292 // If the ruler in the Y axis is enabled, scroll in the Y axis.
2293 if(mRulerY->GetType() == Ruler::Free)
2295 // Free panning mode
2296 targetScrollPosition.y += event.z * mMouseWheelScrollDistanceStep.y;
2297 ClampPosition(targetScrollPosition);
2298 ScrollTo(-targetScrollPosition);
2300 else if(!mScrolling)
2302 // Snap mode, only respond to the event when the previous snap animation is finished.
2303 ScrollTo(GetCurrentPage() - event.z * mRulerX->GetTotalPages());
2310 void ScrollView::ResetScrolling()
2312 Actor self = Self();
2313 self.GetProperty(mPropertyPosition).Get(mScrollPostPosition);
2314 mScrollPrePosition = mScrollPostPosition;
2315 DALI_LOG_SCROLL_STATE("[0x%X] Setting mPropertyPrePosition To[%.2f, %.2f]", this, mScrollPostPosition.x, mScrollPostPosition.y );
2316 self.SetProperty(mPropertyPrePosition, mScrollPostPosition);
2319 void ScrollView::UpdateLocalScrollProperties()
2321 Actor self = Self();
2322 self.GetProperty(mPropertyPrePosition).Get(mScrollPrePosition);
2323 self.GetProperty(mPropertyPosition).Get(mScrollPostPosition);
2326 // private functions
2328 void ScrollView::PreAnimatedScrollSetup()
2330 // mPropertyPrePosition is our unclamped property with wrapping
2331 // mPropertyPosition is our final scroll position after clamping
2333 Actor self = Self();
2335 Vector3 deltaPosition(mScrollPostPosition);
2336 WrapPosition(mScrollPostPosition);
2337 mDomainOffset += deltaPosition - mScrollPostPosition;
2338 Self().SetProperty(mPropertyDomainOffset, mDomainOffset);
2340 if( mScrollStateFlags & SCROLL_X_STATE_MASK )
2342 // already performing animation on internal x position
2343 StopAnimation(mInternalXAnimation);
2346 if( mScrollStateFlags & SCROLL_Y_STATE_MASK )
2348 // already performing animation on internal y position
2349 StopAnimation(mInternalYAnimation);
2352 mScrollStateFlags = 0;
2354 mScrollPostScale = GetPropertyScale();
2356 // Update Actor position with this wrapped value.
2359 mScrollPreScale = mScrollPostScale;
2360 mScrollPreRotation = mScrollPostRotation;
2363 void ScrollView::FinaliseAnimatedScroll()
2365 // TODO - common animation finishing code in here
2368 void ScrollView::AnimateInternalXTo( float position, float duration, AlphaFunction alpha )
2370 StopAnimation(mInternalXAnimation);
2372 if( duration > Math::MACHINE_EPSILON_10 )
2374 Actor self = Self();
2375 DALI_LOG_SCROLL_STATE("[0x%X], Animating from[%.2f] to[%.2f]", this, self.GetProperty(mPropertyPrePosition).Get<Vector3>().x, position );
2376 mInternalXAnimation = Animation::New(duration);
2377 DALI_LOG_SCROLL_STATE("[0x%X], mInternalXAnimation[0x%X]", this, mInternalXAnimation.GetObjectPtr() );
2378 mInternalXAnimation.FinishedSignal().Connect(this, &ScrollView::OnScrollAnimationFinished);
2379 mInternalXAnimation.AnimateTo( Property(self, mPropertyPrePosition, 0), position, alpha, duration);
2380 mInternalXAnimation.Play();
2382 // erase current state flags
2383 mScrollStateFlags &= ~SCROLL_X_STATE_MASK;
2384 // add internal animation state flag
2385 mScrollStateFlags |= AnimatingInternalX;
2389 void ScrollView::AnimateInternalYTo( float position, float duration, AlphaFunction alpha )
2391 StopAnimation(mInternalYAnimation);
2393 if( duration > Math::MACHINE_EPSILON_10 )
2395 Actor self = Self();
2396 DALI_LOG_SCROLL_STATE("[0x%X], Animating from[%.2f] to[%.2f]", this, self.GetProperty(mPropertyPrePosition).Get<Vector3>().y, position );
2397 mInternalYAnimation = Animation::New(duration);
2398 DALI_LOG_SCROLL_STATE("[0x%X], mInternalYAnimation[0x%X]", this, mInternalYAnimation.GetObjectPtr() );
2399 mInternalYAnimation.FinishedSignal().Connect(this, &ScrollView::OnScrollAnimationFinished);
2400 mInternalYAnimation.AnimateTo( Property(self, mPropertyPrePosition, 1), position, alpha, TimePeriod(duration));
2401 mInternalYAnimation.Play();
2403 // erase current state flags
2404 mScrollStateFlags &= ~SCROLL_Y_STATE_MASK;
2405 // add internal animation state flag
2406 mScrollStateFlags |= AnimatingInternalY;
2410 void ScrollView::OnScrollAnimationFinished( Animation& source )
2412 // Guard against destruction during signal emission
2413 // Note that ScrollCompletedSignal is emitted from HandleSnapAnimationFinished()
2414 Toolkit::ScrollView handle( GetOwner() );
2416 bool scrollingFinished = false;
2418 // update our local scroll positions
2419 UpdateLocalScrollProperties();
2421 if( source == mSnapAnimation )
2423 DALI_LOG_SCROLL_STATE("[0x%X] mSnapAnimation[0x%X]", this, mSnapAnimation.GetObjectPtr() );
2425 // generic snap animation used for scaling and rotation
2426 mSnapAnimation.Reset();
2429 if( source == mInternalXAnimation )
2431 DALI_LOG_SCROLL_STATE("[0x%X] mInternalXAnimation[0x%X], expected[%.2f], actual[%.2f], post[%.2f]", this, mInternalXAnimation.GetObjectPtr(), mScrollTargetPosition.x, Self().GetProperty(mPropertyPrePosition).Get<Vector3>().x, mScrollPostPosition.x );
2433 if( !(mScrollStateFlags & AnimatingInternalY) )
2435 scrollingFinished = true;
2437 mInternalXAnimation.Reset();
2438 // wrap pre scroll x position and set it
2441 const RulerDomain rulerDomain = mRulerX->GetDomain();
2442 mScrollPrePosition.x = -WrapInDomain(-mScrollPrePosition.x, rulerDomain.min, rulerDomain.max);
2443 DALI_LOG_SCROLL_STATE("[0x%X] Setting mPropertyPrePosition To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y );
2444 handle.SetProperty(mPropertyPrePosition, mScrollPrePosition);
2446 SnapInternalXTo(mScrollPostPosition.x);
2449 if( source == mInternalYAnimation )
2451 DALI_LOG_SCROLL_STATE("[0x%X] mInternalYAnimation[0x%X], expected[%.2f], actual[%.2f], post[%.2f]", this, mInternalYAnimation.GetObjectPtr(), mScrollTargetPosition.y, Self().GetProperty(mPropertyPrePosition).Get<Vector3>().y, mScrollPostPosition.y );
2453 if( !(mScrollStateFlags & AnimatingInternalX) )
2455 scrollingFinished = true;
2457 mInternalYAnimation.Reset();
2460 // wrap pre scroll y position and set it
2461 const RulerDomain rulerDomain = mRulerY->GetDomain();
2462 mScrollPrePosition.y = -WrapInDomain(-mScrollPrePosition.y, rulerDomain.min, rulerDomain.max);
2463 DALI_LOG_SCROLL_STATE("[0x%X] Setting mPropertyPrePosition To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y );
2464 handle.SetProperty(mPropertyPrePosition, mScrollPrePosition);
2466 SnapInternalYTo(mScrollPostPosition.y);
2469 DALI_LOG_SCROLL_STATE("[0x%X] scrollingFinished[%d] Animation[0x%X]", this, scrollingFinished, source.GetObjectPtr());
2471 if(scrollingFinished)
2473 HandleSnapAnimationFinished();
2477 void ScrollView::OnSnapInternalPositionFinished( Animation& source )
2479 Actor self = Self();
2480 UpdateLocalScrollProperties();
2481 if( source == mInternalXAnimation )
2483 DALI_LOG_SCROLL_STATE("[0x%X] Finished X PostPosition Animation", this );
2485 // clear internal x animation flags
2486 mScrollStateFlags &= ~SCROLL_X_STATE_MASK;
2487 mInternalXAnimation.Reset();
2488 WrapPosition(mScrollPrePosition);
2490 if( source == mInternalYAnimation )
2492 DALI_LOG_SCROLL_STATE("[0x%X] Finished Y PostPosition Animation", this );
2494 mScrollStateFlags &= ~SCROLL_Y_STATE_MASK;
2495 mInternalYAnimation.Reset();
2496 WrapPosition(mScrollPrePosition);
2500 void ScrollView::SnapInternalXTo(float position)
2502 Actor self = Self();
2504 StopAnimation(mInternalXAnimation);
2506 // erase current state flags
2507 mScrollStateFlags &= ~SCROLL_X_STATE_MASK;
2509 // if internal x not equal to inputed parameter, animate it
2510 float duration = std::min(fabsf((position - mScrollPrePosition.x) / mMaxOvershoot.x) * mSnapOvershootDuration, mSnapOvershootDuration);
2511 DALI_LOG_SCROLL_STATE("[0x%X] duration[%.2f]", this, duration );
2512 if( duration > Math::MACHINE_EPSILON_1 )
2514 DALI_LOG_SCROLL_STATE("[0x%X] Starting X Snap Animation to[%.2f]", this, position );
2516 mInternalXAnimation = Animation::New(duration);
2517 mInternalXAnimation.FinishedSignal().Connect(this, &ScrollView::OnSnapInternalPositionFinished);
2518 mInternalXAnimation.AnimateTo(Property(self, mPropertyPrePosition, 0), position);
2519 mInternalXAnimation.Play();
2521 // add internal animation state flag
2522 mScrollStateFlags |= SnappingInternalX;
2526 void ScrollView::SnapInternalYTo(float position)
2528 Actor self = Self();
2530 StopAnimation(mInternalYAnimation);
2532 // erase current state flags
2533 mScrollStateFlags &= ~SCROLL_Y_STATE_MASK;
2535 // if internal y not equal to inputed parameter, animate it
2536 float duration = std::min(fabsf((position - mScrollPrePosition.y) / mMaxOvershoot.y) * mSnapOvershootDuration, mSnapOvershootDuration);
2537 DALI_LOG_SCROLL_STATE("[0x%X] duration[%.2f]", this, duration );
2538 if( duration > Math::MACHINE_EPSILON_1 )
2540 DALI_LOG_SCROLL_STATE("[0x%X] Starting Y Snap Animation to[%.2f]", this, position );
2542 mInternalYAnimation = Animation::New(duration);
2543 mInternalYAnimation.FinishedSignal().Connect(this, &ScrollView::OnSnapInternalPositionFinished);
2544 mInternalYAnimation.AnimateTo(Property(self, mPropertyPrePosition, 1), position);
2545 mInternalYAnimation.Play();
2547 // add internal animation state flag
2548 mScrollStateFlags |= SnappingInternalY;
2552 void ScrollView::GestureStarted()
2554 // we handle the first gesture.
2555 // if we're currently doing a gesture and receive another
2556 // we continue and combine the effects of the gesture instead of reseting.
2557 if(mGestureStackDepth++==0)
2559 Actor self = Self();
2560 StopTouchDownTimer();
2562 mPanDelta = Vector3::ZERO;
2563 mScaleDelta = Vector3::ONE;
2564 mRotationDelta = 0.0f;
2565 mLastVelocity = Vector2(0.0f, 0.0f);
2568 mLockAxis = LockPossible;
2571 if( mScrollStateFlags & SCROLL_X_STATE_MASK )
2573 StopAnimation(mInternalXAnimation);
2575 if( mScrollStateFlags & SCROLL_Y_STATE_MASK )
2577 StopAnimation(mInternalYAnimation);
2579 mScrollStateFlags = 0;
2581 if(mScrolling) // are we interrupting a current scroll?
2583 // set mScrolling to false, in case user has code that interrogates mScrolling Getter() in complete.
2585 // send negative scroll position since scroll internal scroll position works as an offset for actors,
2586 // give applications the position within the domain from the scroll view's anchor position
2587 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignalV2 5 [%.2f, %.2f]", this, -mScrollPostPosition.x, -mScrollPostPosition.y);
2588 mScrollCompletedSignalV2.Emit( -mScrollPostPosition );
2593 void ScrollView::GestureContinuing(const Vector2& panDelta, const Vector2& scaleDelta, float rotationDelta)
2595 mPanDelta.x+= panDelta.x;
2596 mPanDelta.y+= panDelta.y;
2597 mScaleDelta.x*= scaleDelta.x;
2598 mScaleDelta.y*= scaleDelta.y;
2599 mRotationDelta+= rotationDelta;
2601 // Save the velocity, there is a bug in PanGesture
2602 // Whereby the Gesture::Finished's velocity is either:
2603 // NaN (due to time delta of zero between the last two events)
2604 // or 0 (due to position being the same between the last two events)
2606 // Axis Auto Lock - locks the panning to the horizontal or vertical axis if the pan
2607 // appears mostly horizontal or mostly vertical respectively.
2610 mLockAxis = GetLockAxis(mPanDelta.GetVectorXY(), mLockAxis, mAxisAutoLockGradient);
2611 } // end if mAxisAutoLock
2614 // TODO: Upgrade to use a more powerful gesture detector (one that supports multiple touches on pan - so works as pan and flick gesture)
2615 // TODO: Reimplement Scaling (pinching 2+ points)
2616 // TODO: Reimplment Rotation (pinching 2+ points)
2617 // BUG: Gesture::Finished doesn't always return velocity on release (due to
2618 // timeDelta between last two events being 0 sometimes, or posiiton being the same)
2619 void ScrollView::OnPan(PanGesture gesture)
2621 // Guard against destruction during signal emission
2622 // Note that Emit() methods are called indirectly e.g. from within ScrollView::OnGestureEx()
2623 Actor self( Self() );
2627 DALI_LOG_SCROLL_STATE("[0x%X] Pan Ignored, Insensitive", this);
2629 // If another callback on the same original signal disables sensitivity,
2630 // this callback will still be called, so we must suppress it.
2634 // translate Gesture input to get useful data...
2635 switch(gesture.state)
2637 case Gesture::Started:
2639 DALI_LOG_SCROLL_STATE("[0x%X] Pan Started", this);
2640 UpdateLocalScrollProperties();
2643 self.SetProperty( mPropertyPanning, true );
2644 self.SetProperty( mPropertyScrollStartPagePosition, Vector3(gesture.position.x, gesture.position.y, 0.0f) );
2646 UpdateMainInternalConstraint();
2650 case Gesture::Continuing:
2654 DALI_LOG_SCROLL_STATE("[0x%X] Pan Continuing", this);
2655 GestureContinuing(gesture.screenDisplacement, Vector2::ZERO, 0.0f);
2659 // If we do not think we are panning, then we should not do anything here
2665 case Gesture::Finished:
2666 case Gesture::Cancelled:
2670 DALI_LOG_SCROLL_STATE("[0x%X] Pan %s", this, ( ( gesture.state == Gesture::Finished ) ? "Finished" : "Cancelled" ) );
2672 UpdateLocalScrollProperties();
2673 mLastVelocity = gesture.velocity;
2675 self.SetProperty( mPropertyPanning, false );
2677 if( mScrollMainInternalPrePositionConstraint )
2679 self.RemoveConstraint(mScrollMainInternalPrePositionConstraint);
2682 if( mOvershootIndicator )
2684 mOvershootIndicator->ClearOvershoot();
2689 // If we do not think we are panning, then we should not do anything here
2695 case Gesture::Possible:
2696 case Gesture::Clear:
2698 // Nothing to do, not needed.
2702 } // end switch(gesture.state)
2704 OnGestureEx(gesture.state);
2707 void ScrollView::OnGestureEx(Gesture::State state)
2709 // call necessary signals for application developer
2711 if(state == Gesture::Started)
2713 Vector3 currentScrollPosition = GetCurrentScrollPosition();
2714 Self().SetProperty(mPropertyScrolling, true);
2716 DALI_LOG_SCROLL_STATE("[0x%X] mScrollStartedSignalV2 2 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
2717 mScrollStartedSignalV2.Emit( currentScrollPosition );
2719 else if( (state == Gesture::Finished) ||
2720 (state == Gesture::Cancelled) ) // Finished/default
2722 // when all the gestures have finished, we finish the transform.
2723 // so if a user decides to pan (1 gesture), and then pan+zoom (2 gestures)
2724 // then stop panning (back to 1 gesture), and then stop zooming (0 gestures).
2725 // this is the point we end, and perform necessary snapping.
2726 mGestureStackDepth--;
2727 if(mGestureStackDepth==0)
2729 // no flick if we have not exceeded min flick distance
2730 if( (fabsf(mPanDelta.x) < mMinFlickDistance.x)
2731 && (fabsf(mPanDelta.y) < mMinFlickDistance.y) )
2733 // reset flick velocity
2734 mLastVelocity = Vector2::ZERO;
2740 DALI_LOG_SCROLL_STATE("[0x%X] mGestureStackDepth[%d]", this, mGestureStackDepth);
2745 void ScrollView::UpdateTransform()
2747 // TODO: notify clamps using property notifications (or see if we need this, can deprecate it)
2750 void ScrollView::FinishTransform()
2752 // at this stage internal x and x scroll position should have followed prescroll position exactly
2753 Actor self = Self();
2755 PreAnimatedScrollSetup();
2757 // convert pixels/millisecond to pixels per second
2758 bool animating = SnapWithVelocity(mLastVelocity * 1000.0f);
2762 // if not animating, then this pan has completed right now.
2763 SetScrollUpdateNotification(false);
2765 Self().SetProperty(mPropertyScrolling, false);
2767 if( fabs(mScrollPrePosition.x - mScrollTargetPosition.x) > Math::MACHINE_EPSILON_10 )
2769 SnapInternalXTo(mScrollTargetPosition.x);
2771 if( fabs(mScrollPrePosition.y - mScrollTargetPosition.y) > Math::MACHINE_EPSILON_10 )
2773 SnapInternalYTo(mScrollTargetPosition.y);
2775 Vector3 currentScrollPosition = GetCurrentScrollPosition();
2776 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignalV2 6 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
2777 mScrollCompletedSignalV2.Emit( currentScrollPosition );
2781 Vector3 ScrollView::GetOvershoot(Vector3& position) const
2783 Vector3 size = Self().GetCurrentSize();
2786 const RulerDomain rulerDomainX = mRulerX->GetDomain();
2787 const RulerDomain rulerDomainY = mRulerY->GetDomain();
2789 if(mRulerX->IsEnabled() && rulerDomainX.enabled)
2791 const float left = rulerDomainX.min - position.x;
2792 const float right = size.width - rulerDomainX.max - position.x;
2799 overshoot.x = right;
2803 if(mRulerY->IsEnabled() && rulerDomainY.enabled)
2805 const float top = rulerDomainY.min - position.y;
2806 const float bottom = size.height - rulerDomainY.max - position.y;
2813 overshoot.y = bottom;
2820 bool ScrollView::OnAccessibilityPan(PanGesture gesture)
2822 // Keep track of whether this is an AccessibilityPan
2823 mInAccessibilityPan = true;
2825 mInAccessibilityPan = false;
2830 void ScrollView::ClampPosition(Vector3& position) const
2832 ClampState3 clamped;
2833 ClampPosition(position, clamped);
2836 void ScrollView::ClampPosition(Vector3& position, ClampState3 &clamped) const
2838 Vector3 size = Self().GetCurrentSize();
2840 // determine size of viewport relative to current scaled size.
2841 // e.g. if you're zoomed in 200%, then each pixel on screen is only 0.5 pixels on subject.
2842 if(fabsf(mScrollPostScale.x) > Math::MACHINE_EPSILON_0)
2844 size.x /= mScrollPostScale.x;
2847 if(fabsf(mScrollPostScale.y) > Math::MACHINE_EPSILON_0)
2849 size.y /= mScrollPostScale.y;
2852 position.x = -mRulerX->Clamp(-position.x, size.width, 1.0f, clamped.x); // NOTE: X & Y rulers think in -ve coordinate system.
2853 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.
2855 clamped.z = NotClamped;
2858 void ScrollView::WrapPosition(Vector3& position) const
2862 const RulerDomain rulerDomainX = mRulerX->GetDomain();
2863 const RulerDomain rulerDomainY = mRulerY->GetDomain();
2865 if(mRulerX->IsEnabled())
2867 position.x = -WrapInDomain(-position.x, rulerDomainX.min, rulerDomainX.max);
2870 if(mRulerY->IsEnabled())
2872 position.y = -WrapInDomain(-position.y, rulerDomainY.min, rulerDomainY.max);
2877 void ScrollView::ClampScale(Vector3& scale) const
2879 ClampState3 clamped;
2880 ClampScale(scale, clamped);
2883 void ScrollView::ClampScale(Vector3& scale, ClampState3 &clamped) const
2885 scale.x = mRulerScaleX->Clamp(scale.x, 0.0f, 1.0f, clamped.x);
2886 scale.y = mRulerScaleY->Clamp(scale.y, 0.0f, 1.0f, clamped.y);
2887 clamped.z = NotClamped;
2890 void ScrollView::UpdateMainInternalConstraint()
2892 // TODO: Only update the constraints which have changed, rather than remove all and add all again.
2893 // Requires a dali-core ApplyConstraintAt, or a ReplaceConstraint. The former is probably more flexible.
2894 Actor self = Self();
2895 PanGestureDetector detector( GetPanGestureDetector() );
2897 if(mScrollMainInternalPositionConstraint)
2899 self.RemoveConstraint(mScrollMainInternalPositionConstraint);
2900 self.RemoveConstraint(mScrollMainInternalDeltaConstraint);
2901 self.RemoveConstraint(mScrollMainInternalFinalConstraint);
2902 self.RemoveConstraint(mScrollMainInternalRelativeConstraint);
2903 self.RemoveConstraint(mScrollMainInternalXConstraint);
2904 self.RemoveConstraint(mScrollMainInternalYConstraint);
2906 if( mScrollMainInternalPrePositionConstraint )
2908 self.RemoveConstraint(mScrollMainInternalPrePositionConstraint);
2911 // TODO: It's probably better to use a local displacement value as this will give a displacement when scrolling just commences
2912 // but we need to make sure than the gesture system gives displacement since last frame (60Hz), not displacement since last touch event (90Hz).
2914 // 1. First calculate the pre-position (this is the scroll position if no clamping has taken place)
2915 Vector2 initialPanMask = Vector2(mRulerX->IsEnabled() ? 1.0f : 0.0f, mRulerY->IsEnabled() ? 1.0f : 0.0f);
2917 if( mLockAxis == LockVertical )
2919 initialPanMask.y = 0.0f;
2921 else if( mLockAxis == LockHorizontal )
2923 initialPanMask.x = 0.0f;
2925 Constraint constraint;
2929 constraint = Constraint::New<Vector3>( mPropertyPrePosition,
2930 Source( detector, PanGestureDetector::LOCAL_POSITION ),
2931 Source( detector, PanGestureDetector::LOCAL_DISPLACEMENT ),
2932 Source( self, Actor::SIZE ),
2933 InternalPrePositionConstraint( initialPanMask, mAxisAutoLock, mAxisAutoLockGradient, mLockAxis, mMaxOvershoot, mRulerX->GetDomain(), mRulerY->GetDomain() ) );
2934 mScrollMainInternalPrePositionConstraint = self.ApplyConstraint( constraint );
2937 // 2. Second calculate the clamped position (actual position)
2938 constraint = Constraint::New<Vector3>( mPropertyPosition,
2939 LocalSource( mPropertyPrePosition ),
2940 LocalSource( mPropertyPositionMin ),
2941 LocalSource( mPropertyPositionMax ),
2942 Source( self, Actor::SIZE ),
2943 InternalPositionConstraint( mRulerX->GetDomain(),
2944 mRulerY->GetDomain(), mWrapMode ) );
2945 mScrollMainInternalPositionConstraint = self.ApplyConstraint( constraint );
2947 constraint = Constraint::New<Vector3>( mPropertyPositionDelta,
2948 LocalSource( mPropertyPosition ),
2949 LocalSource( mPropertyDomainOffset ),
2950 InternalPositionDeltaConstraint );
2951 mScrollMainInternalDeltaConstraint = self.ApplyConstraint( constraint );
2953 constraint = Constraint::New<Vector3>( mPropertyFinal,
2954 LocalSource( mPropertyPosition ),
2955 LocalSource( mPropertyOvershootX ),
2956 LocalSource( mPropertyOvershootY ),
2957 InternalFinalConstraint( FinalDefaultAlphaFunction,
2958 FinalDefaultAlphaFunction ) );
2959 mScrollMainInternalFinalConstraint = self.ApplyConstraint( constraint );
2961 constraint = Constraint::New<Vector3>( mPropertyRelativePosition,
2962 LocalSource( mPropertyPosition ),
2963 LocalSource( mPropertyPositionMin ),
2964 LocalSource( mPropertyPositionMax ),
2965 LocalSource( Actor::SIZE ),
2966 InternalRelativePositionConstraint );
2967 mScrollMainInternalRelativeConstraint = self.ApplyConstraint( constraint );
2969 constraint = Constraint::New<float>( mPropertyX,
2970 LocalSource( mPropertyPrePosition ),
2971 InternalXConstraint );
2972 mScrollMainInternalXConstraint = self.ApplyConstraint( constraint );
2974 constraint = Constraint::New<float>( mPropertyY,
2975 LocalSource( mPropertyPrePosition ),
2976 InternalYConstraint );
2977 mScrollMainInternalYConstraint = self.ApplyConstraint( constraint );
2979 // When panning we want to make sure overshoot values are affected by pre position and post position
2980 SetOvershootConstraintsEnabled(!mWrapMode);
2983 void ScrollView::SetOvershootConstraintsEnabled(bool enabled)
2985 Actor self( Self() );
2986 // remove and reset, it may now be in wrong order with the main internal constraints
2987 if( mScrollMainInternalOvershootXConstraint )
2989 self.RemoveConstraint(mScrollMainInternalOvershootXConstraint);
2990 mScrollMainInternalOvershootXConstraint.Reset();
2991 self.RemoveConstraint(mScrollMainInternalOvershootYConstraint);
2992 mScrollMainInternalOvershootYConstraint.Reset();
2996 Constraint constraint = Constraint::New<float>( mPropertyOvershootX,
2997 LocalSource( mPropertyPrePosition ),
2998 LocalSource( mPropertyPosition ),
2999 LocalSource( mPropertyCanScrollHorizontal ),
3000 OvershootXConstraint(mMaxOvershoot.x) );
3001 mScrollMainInternalOvershootXConstraint = self.ApplyConstraint( constraint );
3003 constraint = Constraint::New<float>( mPropertyOvershootY,
3004 LocalSource( mPropertyPrePosition ),
3005 LocalSource( mPropertyPosition ),
3006 LocalSource( mPropertyCanScrollVertical ),
3007 OvershootYConstraint(mMaxOvershoot.y) );
3008 mScrollMainInternalOvershootYConstraint = self.ApplyConstraint( constraint );
3012 self.SetProperty(mPropertyOvershootX, 0.0f);
3013 self.SetProperty(mPropertyOvershootY, 0.0f);
3017 void ScrollView::SetInternalConstraints()
3019 // Internal constraints (applied to target ScrollBase Actor itself) /////////
3020 UpdateMainInternalConstraint();
3022 // User definable constraints to apply to all child actors //////////////////
3023 Actor self = Self();
3025 // LocalSource - The Actors to be moved.
3026 // self - The ScrollView
3028 // Apply some default constraints to ScrollView.
3029 // Movement + Scaling + Wrap function
3031 Constraint constraint;
3033 // MoveScaledActor (scrolling/zooming)
3034 constraint = Constraint::New<Vector3>( Actor::POSITION,
3035 Source( self, mPropertyPosition ),
3036 Source( self, mPropertyScale ),
3037 MoveScaledActorConstraint );
3038 constraint.SetRemoveAction(Constraint::Discard);
3039 ApplyConstraintToBoundActors(constraint);
3041 // ScaleActor (scrolling/zooming)
3042 constraint = Constraint::New<Vector3>( Actor::SCALE,
3043 Source( self, mPropertyScale ),
3044 ScaleActorConstraint );
3045 constraint.SetRemoveAction(Constraint::Discard);
3046 ApplyConstraintToBoundActors(constraint);
3048 // WrapActor (wrap functionality)
3049 constraint = Constraint::New<Vector3>( Actor::POSITION,
3050 LocalSource( Actor::SCALE ),
3051 LocalSource( Actor::ANCHOR_POINT ),
3052 LocalSource( Actor::SIZE ),
3053 Source( self, mPropertyPositionMin ),
3054 Source( self, mPropertyPositionMax ),
3055 Source( self, mPropertyWrap ),
3056 WrapActorConstraint );
3057 constraint.SetRemoveAction(Constraint::Discard);
3058 ApplyConstraintToBoundActors(constraint);
3061 } // namespace Internal
3063 } // namespace Toolkit