2 * Copyright (c) 2021 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-toolkit/internal/controls/scrollable/scroll-view/scroll-view-impl.h>
22 #include <dali/devel-api/actors/actor-devel.h>
23 #include <dali/devel-api/common/stage.h>
24 #include <dali/devel-api/events/pan-gesture-devel.h>
25 #include <dali/devel-api/object/property-helper-devel.h>
26 #include <dali/integration-api/debug.h>
27 #include <dali/public-api/animation/constraints.h>
28 #include <dali/public-api/events/touch-event.h>
29 #include <dali/public-api/events/wheel-event.h>
30 #include <dali/public-api/object/property-map.h>
31 #include <dali/public-api/object/type-registry-helper.h>
32 #include <dali/public-api/object/type-registry.h>
33 #include <cstring> // for strcmp
36 #include <dali-toolkit/devel-api/controls/scroll-bar/scroll-bar.h>
37 #include <dali-toolkit/internal/controls/scrollable/scroll-view/scroll-overshoot-indicator-impl.h>
38 #include <dali-toolkit/internal/controls/scrollable/scroll-view/scroll-view-effect-impl.h>
39 #include <dali-toolkit/public-api/controls/scrollable/scroll-view/scroll-mode.h>
40 #include <dali-toolkit/public-api/controls/scrollable/scroll-view/scroll-view-constraints.h>
41 #include <dali-toolkit/public-api/controls/scrollable/scroll-view/scroll-view.h>
43 //#define ENABLED_SCROLL_STATE_LOGGING
45 #ifdef ENABLED_SCROLL_STATE_LOGGING
46 #define DALI_LOG_SCROLL_STATE(format, ...) Dali::Integration::Log::LogMessageWithFunctionLine(Dali::Integration::Log::DebugInfo, "%s:%d " format "\n", __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)
48 #define DALI_LOG_SCROLL_STATE(format, ...)
51 // TODO: Change to two class system:
52 // 1. DraggableActor (is an actor which can be dragged anywhere, can be set to range using the ruler)
53 // 2. ScrollView (contains a draggable actor that can a) be dragged in the negative X, and Y domain, b) has a hitArea for touches)
54 // TODO: external components (page and status overlays).
56 // TODO: upgrade Vector2/3 to support returning Unit vectors, normals, & cross product (dot product is already provided)
62 constexpr float DEFAULT_SLOW_SNAP_ANIMATION_DURATION(0.5f); ///< Default Drag-Release animation time.
63 constexpr float DEFAULT_FAST_SNAP_ANIMATION_DURATION(0.25f); ///< Default Drag-Flick animation time.
64 constexpr float DEFAULT_SNAP_OVERSHOOT_DURATION(0.5f); ///< Default Overshoot snapping animation time.
65 constexpr float DEFAULT_MAX_OVERSHOOT(100.0f); ///< Default maximum allowed overshoot in pixels
67 constexpr float DEFAULT_AXIS_AUTO_LOCK_GRADIENT(0.36f); ///< Default Axis-AutoLock gradient threshold. default is 0.36:1 (20 degrees)
68 constexpr float DEFAULT_FRICTION_COEFFICIENT(1.0f); ///< Default Friction Co-efficient. (in stage diagonals per second)
69 constexpr float DEFAULT_FLICK_SPEED_COEFFICIENT(1.0f); ///< Default Flick speed coefficient (multiples input touch velocity)
70 constexpr float DEFAULT_MAX_FLICK_SPEED(3.0f); ///< Default Maximum flick speed. (in stage diagonals per second)
72 constexpr Dali::Vector2 DEFAULT_MIN_FLICK_DISTANCE(30.0f, 30.0f); ///< minimum distance for pan before flick allowed
73 constexpr float DEFAULT_MIN_FLICK_SPEED_THRESHOLD(500.0f); ///< Minimum pan speed required for flick in pixels/s
75 constexpr float FREE_FLICK_SPEED_THRESHOLD = 200.0f; ///< Free-Flick threshold in pixels/ms
76 constexpr float AUTOLOCK_AXIS_MINIMUM_DISTANCE2 = 100.0f; ///< Auto-lock axis after minimum distance squared.
77 constexpr float FLICK_ORTHO_ANGLE_RANGE = 75.0f; ///< degrees. (if >45, then supports diagonal flicking)
79 constexpr Dali::Vector2 DEFAULT_WHEEL_SCROLL_DISTANCE_STEP_PROPORTION(0.17f, 0.1f); ///< The step of horizontal scroll distance in the proportion of stage size for each wheel event received.
81 constexpr unsigned long MINIMUM_TIME_BETWEEN_DOWN_AND_UP_FOR_RESET(150u);
82 constexpr float TOUCH_DOWN_TIMER_INTERVAL = 100.0f;
83 constexpr float DEFAULT_SCROLL_UPDATE_DISTANCE(30.0f); ///< Default distance to travel in pixels for scroll update signal
85 const std::string INTERNAL_MAX_POSITION_PROPERTY_NAME("internalMaxPosition");
87 // Helpers ////////////////////////////////////////////////////////////////////////////////////////
90 * Find the vector (distance) from (a) to (b)
91 * in domain (start) to (end)
92 * (\ / start) (\ / end)
95 * @note assumes both (a) and (b) are already with the domain
98 * @param[in] a the current point
99 * @param[in] b the target point
100 * @param[in] start the start of the domain
101 * @param[in] end the end of the domain
102 * @param[in] bias whether to only take the right direction or the left direction,
103 * or the shortest direction.
104 * @return the shortest direction and distance
106 float VectorInDomain(float a, float b, float start, float end, Dali::Toolkit::DirectionBias bias)
108 if(bias == Dali::Toolkit::DIRECTION_BIAS_NONE)
110 return Dali::ShortestDistanceInDomain(a, b, start, end);
113 float size = end - start;
119 if(bias == Dali::Toolkit::DIRECTION_BIAS_RIGHT) // going right, take the vector.
125 float aRight = a + size;
132 if(bias == Dali::Toolkit::DIRECTION_BIAS_LEFT) // going left, take the vector.
138 float aLeft = a - size;
145 * Returns the position of the anchor within actor
147 * @param actor The Actor
148 * @param anchor The Anchor point of interest.
149 * @return The position of the Anchor
151 Dali::Vector3 GetPositionOfAnchor(Dali::Actor& actor, const Dali::Vector3& anchor)
153 Dali::Vector3 childPosition = actor.GetCurrentProperty<Dali::Vector3>(Dali::Actor::Property::POSITION);
154 Dali::Vector3 childAnchor = -actor.GetCurrentProperty<Dali::Vector3>(Dali::Actor::Property::ANCHOR_POINT) + anchor;
155 Dali::Vector3 childSize = actor.GetCurrentProperty<Dali::Vector3>(Dali::Actor::Property::SIZE);
157 return childPosition + childAnchor * childSize;
161 * Returns the closest actor to the given position
162 * @param[in] actor The scrollview actor
163 * @param[in] internalActor The internal actor (to ignore)
164 * @param[in] position The given position
165 * @param[in] dirX Direction to search in
166 * @param[in] dirY Direction to search in
167 * @param[in] dirZ Direction to search in
168 * @return the closest child actor
170 using FindDirection = Dali::Toolkit::Internal::ScrollView::FindDirection;
172 Actor FindClosestActorToPosition(
173 CustomActor actor, Actor internalActor, const Vector3& position, FindDirection dirX, FindDirection dirY, FindDirection dirZ)
176 float closestDistance2 = 0.0f;
177 Vector3 actualPosition = position;
179 unsigned int numChildren = actor.GetChildCount();
181 for(unsigned int i = 0; i < numChildren; ++i)
183 Actor child = actor.GetChildAt(i);
185 if(internalActor == child) // ignore internal actor.
190 Vector3 childPosition = GetPositionOfAnchor(child, AnchorPoint::CENTER);
192 Vector3 delta = childPosition - actualPosition;
194 // X-axis checking (only find Actors to the [dirX] of actualPosition)
195 if(dirX > FindDirection::All) // != All,None
197 FindDirection deltaH = delta.x > 0 ? FindDirection::Right : FindDirection::Left;
204 // Y-axis checking (only find Actors to the [dirY] of actualPosition)
205 if(dirY > FindDirection::All) // != All,None
207 FindDirection deltaV = delta.y > 0 ? FindDirection::Down : FindDirection::Up;
214 // Z-axis checking (only find Actors to the [dirZ] of actualPosition)
215 if(dirZ > FindDirection::All) // != All,None
217 FindDirection deltaV = delta.y > 0 ? FindDirection::In : FindDirection::Out;
224 // compare child to closest child in terms of distance.
225 float distance2 = 0.0f;
227 // distance2 = the Square of the relevant dimensions of delta
228 if(dirX != FindDirection::None)
230 distance2 += delta.x * delta.x;
233 if(dirY != FindDirection::None)
235 distance2 += delta.y * delta.y;
238 if(dirZ != FindDirection::None)
240 distance2 += delta.z * delta.z;
243 if(closestChild) // Next time.
245 if(distance2 < closestDistance2)
247 closestChild = child;
248 closestDistance2 = distance2;
253 closestChild = child;
254 closestDistance2 = distance2;
261 // AlphaFunctions /////////////////////////////////////////////////////////////////////////////////
264 * ConstantDecelerationAlphaFunction
265 * Newtoninan distance for constant deceleration
266 * v = 1 - t, s = t - 1/2 t^2
267 * when t = 0, s = 0.0 (min distance)
268 * when t = 1, s = 0.5 (max distance)
269 * progress = s / (max-min) = 2t - t^2
271 * @param[in] offset The input progress
272 * @return The output progress
274 float ConstantDecelerationAlphaFunction(float progress)
276 return progress * 2.0f - progress * progress;
281 * @param[in] size The size to clamp to
282 * @param[in] rulerX The horizontal ruler
283 * @param[in] rulerY The vertical ruler
284 * @param[in,out] position The position to clamp
285 * @param[out] clamped the clamped state
287 void ClampPosition(const Vector3& size, Dali::Toolkit::RulerPtr rulerX, Dali::Toolkit::RulerPtr rulerY, Vector2& position, Dali::Toolkit::ClampState2D& clamped)
289 position.x = -rulerX->Clamp(-position.x, size.width, 1.0f, clamped.x); // NOTE: X & Y rulers think in -ve coordinate system.
290 position.y = -rulerY->Clamp(-position.y, size.height, 1.0f, clamped.y); // That is scrolling RIGHT (e.g. 100.0, 0.0) means moving LEFT.
294 * TODO: In situations where axes are different (X snap, Y free)
295 * Each axis should really have their own independent animation (time and equation)
296 * Consider, X axis snapping to nearest grid point (EaseOut over fixed time)
297 * Consider, Y axis simulating physics to arrive at a point (Physics equation over variable time)
298 * Currently, the axes have been split however, they both use the same EaseOut equation.
300 * @param[in] scrollView The main scrollview
301 * @param[in] rulerX The X ruler
302 * @param[in] rulerY The Y ruler
303 * @param[in] lockAxis Which axis (if any) is locked.
304 * @param[in] velocity Current pan velocity
305 * @param[in] maxOvershoot Maximum overshoot
306 * @param[in] inAcessibilityPan True if we are currently panning with accessibility
307 * @param[out] positionSnap The target position of snap animation
308 * @param[out] positionDuration The duration of the snap animation
309 * @param[out] alphaFunction The snap animation alpha function
310 * @param[out] isFlick if we are flicking or not
311 * @param[out] isFreeFlick if we are free flicking or not
313 void SnapWithVelocity(
314 Dali::Toolkit::Internal::ScrollView& scrollView,
315 Dali::Toolkit::RulerPtr rulerX,
316 Dali::Toolkit::RulerPtr rulerY,
317 Dali::Toolkit::Internal::ScrollView::LockAxis lockAxis,
319 Vector2 maxOvershoot,
320 Vector2& positionSnap,
321 Vector2& positionDuration,
322 AlphaFunction& alphaFunction,
323 bool inAccessibilityPan,
327 // Animator takes over now, touches are assumed not to interfere.
328 // And if touches do interfere, then we'll stop animation, update PrePosition
329 // to current mScroll's properties, and then resume.
330 // Note: For Flicking this may work a bit different...
332 float angle = atan2(velocity.y, velocity.x);
333 float speed2 = velocity.LengthSquared();
336 FindDirection horizontal = FindDirection::None;
337 FindDirection vertical = FindDirection::None;
339 using LockAxis = Dali::Toolkit::Internal::ScrollView::LockAxis;
341 // orthoAngleRange = Angle tolerance within the Exact N,E,S,W direction
342 // that will be accepted as a general N,E,S,W flick direction.
344 const float orthoAngleRange = FLICK_ORTHO_ANGLE_RANGE * M_PI / 180.0f;
345 const float flickSpeedThreshold2 = scrollView.GetMinimumSpeedForFlick() * scrollView.GetMinimumSpeedForFlick();
347 // Flick logic X Axis
349 if(rulerX->IsEnabled() && lockAxis != LockAxis::LockHorizontal)
351 horizontal = FindDirection::All;
353 if(speed2 > flickSpeedThreshold2 || // exceeds flick threshold
354 inAccessibilityPan) // With AccessibilityPan its easier to move between snap positions
356 if((angle >= -orthoAngleRange) && (angle < orthoAngleRange)) // Swiping East
358 biasX = 0.0f, horizontal = FindDirection::Left;
360 // This guards against an error where no movement occurs, due to the flick finishing
361 // before the update-thread has advanced mScrollPostPosition past the the previous snap point.
362 positionSnap.x += 1.0f;
364 else if((angle >= M_PI - orthoAngleRange) || (angle < -M_PI + orthoAngleRange)) // Swiping West
366 biasX = 1.0f, horizontal = FindDirection::Right;
368 // This guards against an error where no movement occurs, due to the flick finishing
369 // before the update-thread has advanced mScrollPostPosition past the the previous snap point.
370 positionSnap.x -= 1.0f;
375 // Flick logic Y Axis
377 if(rulerY->IsEnabled() && lockAxis != LockAxis::LockVertical)
379 vertical = FindDirection::All;
381 if(speed2 > flickSpeedThreshold2 || // exceeds flick threshold
382 inAccessibilityPan) // With AccessibilityPan its easier to move between snap positions
384 if((angle >= M_PI_2 - orthoAngleRange) && (angle < M_PI_2 + orthoAngleRange)) // Swiping South
386 biasY = 0.0f, vertical = FindDirection::Up;
388 else if((angle >= -M_PI_2 - orthoAngleRange) && (angle < -M_PI_2 + orthoAngleRange)) // Swiping North
390 biasY = 1.0f, vertical = FindDirection::Down;
395 // isFlick: Whether this gesture is a flick or not.
396 isFlick = (horizontal != FindDirection::All || vertical != FindDirection::All);
397 // isFreeFlick: Whether this gesture is a flick under free panning criteria.
398 isFreeFlick = velocity.LengthSquared() > (FREE_FLICK_SPEED_THRESHOLD * FREE_FLICK_SPEED_THRESHOLD);
400 if(isFlick || isFreeFlick)
402 positionDuration = Vector2::ONE * scrollView.GetScrollFlickDuration();
403 alphaFunction = scrollView.GetScrollFlickAlphaFunction();
406 // Calculate next positionSnap ////////////////////////////////////////////////////////////
408 if(scrollView.GetActorAutoSnap())
410 Vector3 size = scrollView.Self().GetCurrentProperty<Vector3>(Actor::Property::SIZE);
412 Actor child = scrollView.FindClosestActorToPosition(Vector3(size.width * 0.5f, size.height * 0.5f, 0.0f), horizontal, vertical);
414 if(!child && isFlick)
416 // If we conducted a direction limited search and found no actor, then just snap to the closest actor.
417 child = scrollView.FindClosestActorToPosition(Vector3(size.width * 0.5f, size.height * 0.5f, 0.0f));
422 Vector2 position = scrollView.Self().GetCurrentProperty<Vector2>(Toolkit::ScrollView::Property::SCROLL_POSITION);
424 // Get center-point of the Actor.
425 Vector3 childPosition = GetPositionOfAnchor(child, AnchorPoint::CENTER);
427 if(rulerX->IsEnabled())
429 positionSnap.x = position.x - childPosition.x + size.width * 0.5f;
431 if(rulerY->IsEnabled())
433 positionSnap.y = position.y - childPosition.y + size.height * 0.5f;
438 Vector2 startPosition = positionSnap;
439 positionSnap.x = -rulerX->Snap(-positionSnap.x, biasX); // NOTE: X & Y rulers think in -ve coordinate system.
440 positionSnap.y = -rulerY->Snap(-positionSnap.y, biasY); // That is scrolling RIGHT (e.g. 100.0, 0.0) means moving LEFT.
442 Dali::Toolkit::ClampState2D clamped;
443 Vector3 size = scrollView.Self().GetCurrentProperty<Vector3>(Actor::Property::SIZE);
444 Vector2 clampDelta(Vector2::ZERO);
445 ClampPosition(size, rulerX, rulerY, positionSnap, clamped);
447 if((rulerX->GetType() == Dali::Toolkit::Ruler::FREE || rulerY->GetType() == Dali::Toolkit::Ruler::FREE) &&
448 isFreeFlick && !scrollView.GetActorAutoSnap())
450 // Calculate target position based on velocity of flick.
452 // a = Deceleration (Set to diagonal stage length * friction coefficient)
453 // u = Initial Velocity (Flick velocity)
454 // v = 0 (Final Velocity)
455 // t = Time (Velocity / Deceleration)
456 Vector2 stageSize = Stage::GetCurrent().GetSize();
457 float stageLength = Vector3(stageSize.x, stageSize.y, 0.0f).Length();
458 float a = (stageLength * scrollView.GetFrictionCoefficient());
459 Vector3 u = Vector3(velocity.x, velocity.y, 0.0f) * scrollView.GetFlickSpeedCoefficient();
460 float speed = u.Length();
463 // TODO: Change this to a decay function. (faster you flick, the slower it should be)
464 speed = std::min(speed, stageLength * scrollView.GetMaxFlickSpeed());
466 alphaFunction = ConstantDecelerationAlphaFunction;
470 if(rulerX->IsEnabled() && rulerX->GetType() == Dali::Toolkit::Ruler::FREE)
472 positionSnap.x += t * u.x * 0.5f;
475 if(rulerY->IsEnabled() && rulerY->GetType() == Dali::Toolkit::Ruler::FREE)
477 positionSnap.y += t * u.y * 0.5f;
480 clampDelta = positionSnap;
481 ClampPosition(size, rulerX, rulerY, positionSnap, clamped);
483 if((positionSnap - startPosition).LengthSquared() > Math::MACHINE_EPSILON_0)
485 clampDelta -= positionSnap;
486 clampDelta.x = clampDelta.x > 0.0f ? std::min(clampDelta.x, maxOvershoot.x) : std::max(clampDelta.x, -maxOvershoot.x);
487 clampDelta.y = clampDelta.y > 0.0f ? std::min(clampDelta.y, maxOvershoot.y) : std::max(clampDelta.y, -maxOvershoot.y);
491 clampDelta = Vector2::ZERO;
494 // If Axis is Free and has velocity, then calculate time taken
495 // to reach target based on velocity in axis.
496 if(rulerX->IsEnabled() && rulerX->GetType() == Dali::Toolkit::Ruler::FREE)
498 float deltaX = fabsf(startPosition.x - positionSnap.x);
500 if(fabsf(u.x) > Math::MACHINE_EPSILON_1)
502 positionDuration.x = fabsf(deltaX / u.x);
506 positionDuration.x = 0;
510 if(rulerY->IsEnabled() && rulerY->GetType() == Dali::Toolkit::Ruler::FREE)
512 float deltaY = fabsf(startPosition.y - positionSnap.y);
514 if(fabsf(u.y) > Math::MACHINE_EPSILON_1)
516 positionDuration.y = fabsf(deltaY / u.y);
520 positionDuration.y = 0;
525 if(scrollView.IsOvershootEnabled())
527 // Scroll to the end of the overshoot only when overshoot is enabled.
528 positionSnap += clampDelta;
532 } // unnamed namespace
544 return Toolkit::ScrollView::New();
547 // Setup properties, signals and actions using the type-registry.
548 DALI_TYPE_REGISTRATION_BEGIN(Toolkit::ScrollView, Toolkit::Scrollable, Create)
550 DALI_PROPERTY_REGISTRATION(Toolkit, ScrollView, "wrapEnabled", BOOLEAN, WRAP_ENABLED)
551 DALI_PROPERTY_REGISTRATION(Toolkit, ScrollView, "panningEnabled", BOOLEAN, PANNING_ENABLED)
552 DALI_PROPERTY_REGISTRATION(Toolkit, ScrollView, "axisAutoLockEnabled", BOOLEAN, AXIS_AUTO_LOCK_ENABLED)
553 DALI_PROPERTY_REGISTRATION(Toolkit, ScrollView, "wheelScrollDistanceStep", VECTOR2, WHEEL_SCROLL_DISTANCE_STEP)
554 DALI_PROPERTY_REGISTRATION(Toolkit, ScrollView, "scrollMode", MAP, SCROLL_MODE)
556 DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ScrollView, "scrollPosition", VECTOR2, SCROLL_POSITION)
557 DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ScrollView, "scrollPrePosition", VECTOR2, SCROLL_PRE_POSITION)
558 DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, ScrollView, "scrollPrePositionX", SCROLL_PRE_POSITION_X, SCROLL_PRE_POSITION, 0)
559 DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, ScrollView, "scrollPrePositionY", SCROLL_PRE_POSITION_Y, SCROLL_PRE_POSITION, 1)
560 DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ScrollView, "scrollPrePositionMax", VECTOR2, SCROLL_PRE_POSITION_MAX)
561 DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, ScrollView, "scrollPrePositionMaxX", SCROLL_PRE_POSITION_MAX_X, SCROLL_PRE_POSITION_MAX, 0)
562 DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, ScrollView, "scrollPrePositionMaxY", SCROLL_PRE_POSITION_MAX_Y, SCROLL_PRE_POSITION_MAX, 1)
563 DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ScrollView, "overshootX", FLOAT, OVERSHOOT_X)
564 DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ScrollView, "overshootY", FLOAT, OVERSHOOT_Y)
565 DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ScrollView, "scrollFinal", VECTOR2, SCROLL_FINAL)
566 DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, ScrollView, "scrollFinalX", SCROLL_FINAL_X, SCROLL_FINAL, 0)
567 DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, ScrollView, "scrollFinalY", SCROLL_FINAL_Y, SCROLL_FINAL, 1)
568 DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ScrollView, "wrap", BOOLEAN, WRAP)
569 DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ScrollView, "panning", BOOLEAN, PANNING)
570 DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ScrollView, "scrolling", BOOLEAN, SCROLLING)
571 DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ScrollView, "scrollDomainSize", VECTOR2, SCROLL_DOMAIN_SIZE)
572 DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, ScrollView, "scrollDomainSizeX", SCROLL_DOMAIN_SIZE_X, SCROLL_DOMAIN_SIZE, 0)
573 DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, ScrollView, "scrollDomainSizeY", SCROLL_DOMAIN_SIZE_Y, SCROLL_DOMAIN_SIZE, 1)
574 DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ScrollView, "scrollDomainOffset", VECTOR2, SCROLL_DOMAIN_OFFSET)
575 DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ScrollView, "scrollPositionDelta", VECTOR2, SCROLL_POSITION_DELTA)
576 DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ScrollView, "startPagePosition", VECTOR3, START_PAGE_POSITION)
578 DALI_SIGNAL_REGISTRATION(Toolkit, ScrollView, "valueChanged", SIGNAL_SNAP_STARTED)
580 DALI_TYPE_REGISTRATION_END()
584 ///////////////////////////////////////////////////////////////////////////////////////////////////
586 ///////////////////////////////////////////////////////////////////////////////////////////////////
588 Dali::Toolkit::ScrollView ScrollView::New()
590 // Create the implementation
591 ScrollViewPtr scrollView(new ScrollView());
593 // Pass ownership to CustomActor via derived handle
594 Dali::Toolkit::ScrollView handle(*scrollView);
596 // Second-phase init of the implementation
597 // This can only be done after the CustomActor connection has been made...
598 scrollView->Initialize();
603 ScrollView::ScrollView()
604 : ScrollBase(ControlBehaviour(DISABLE_STYLE_CHANGE_SIGNALS)), // Enable size negotiation
606 mGestureStackDepth(0),
607 mScrollStateFlags(0),
608 mLockAxis(LockPossible),
609 mScrollUpdateDistance(DEFAULT_SCROLL_UPDATE_DISTANCE),
610 mMaxOvershoot(DEFAULT_MAX_OVERSHOOT, DEFAULT_MAX_OVERSHOOT),
611 mUserMaxOvershoot(DEFAULT_MAX_OVERSHOOT, DEFAULT_MAX_OVERSHOOT),
612 mSnapOvershootDuration(DEFAULT_SNAP_OVERSHOOT_DURATION),
613 mSnapOvershootAlphaFunction(AlphaFunction::EASE_OUT),
614 mSnapDuration(DEFAULT_SLOW_SNAP_ANIMATION_DURATION),
615 mSnapAlphaFunction(AlphaFunction::EASE_OUT),
616 mMinFlickDistance(DEFAULT_MIN_FLICK_DISTANCE),
617 mFlickSpeedThreshold(DEFAULT_MIN_FLICK_SPEED_THRESHOLD),
618 mFlickDuration(DEFAULT_FAST_SNAP_ANIMATION_DURATION),
619 mFlickAlphaFunction(AlphaFunction::EASE_OUT),
620 mAxisAutoLockGradient(DEFAULT_AXIS_AUTO_LOCK_GRADIENT),
621 mFrictionCoefficient(DEFAULT_FRICTION_COEFFICIENT),
622 mFlickSpeedCoefficient(DEFAULT_FLICK_SPEED_COEFFICIENT),
623 mMaxFlickSpeed(DEFAULT_MAX_FLICK_SPEED),
624 mWheelScrollDistanceStep(Vector2::ZERO),
625 mInAccessibilityPan(false),
627 mScrollInterrupted(false),
630 mTouchDownTimeoutReached(false),
631 mActorAutoSnapEnabled(false),
632 mAutoResizeContainerEnabled(false),
634 mAxisAutoLock(false),
636 mDefaultMaxOvershoot(true),
637 mCanScrollHorizontal(true),
638 mCanScrollVertical(true),
639 mTransientScrollBar(true)
643 void ScrollView::OnInitialize()
647 // Internal Actor, used to hide actors from enumerations.
648 // Also actors added to Internal actor appear as overlays e.g. ScrollBar components.
649 mInternalActor = Actor::New();
650 self.Add(mInternalActor);
652 mInternalActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
653 mInternalActor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER);
654 mInternalActor.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS);
658 mScrollPostPosition = mScrollPrePosition = Vector2::ZERO;
660 mWheelScrollDistanceStep = Stage::GetCurrent().GetSize() * DEFAULT_WHEEL_SCROLL_DISTANCE_STEP_PROPORTION;
662 mGestureStackDepth = 0;
664 self.TouchedSignal().Connect(this, &ScrollView::OnTouch);
665 EnableGestureDetection(GestureType::Value(GestureType::PAN));
667 // By default we'll allow the user to freely drag the scroll view,
668 // while disabling the other rulers.
669 RulerPtr ruler = new DefaultRuler();
673 self.SetProperty(Toolkit::Scrollable::Property::CAN_SCROLL_VERTICAL, mCanScrollVertical);
674 self.SetProperty(Toolkit::Scrollable::Property::CAN_SCROLL_HORIZONTAL, mCanScrollHorizontal);
676 UpdatePropertyDomain();
677 mConstraints.SetInternalConstraints(*this);
679 // Connect wheel event
680 self.WheelEventSignal().Connect(this, &ScrollView::OnWheelEvent);
682 DevelControl::SetAccessibilityConstructor(Self(), [](Dali::Actor actor) {
683 return std::unique_ptr<Dali::Accessibility::Accessible>(
684 new AccessibleImpl(actor, Dali::Accessibility::Role::SCROLL_PANE));
688 void ScrollView::OnSceneConnection(int depth)
690 DALI_LOG_SCROLL_STATE("[0x%X]", this);
694 SetScrollSensitive(false);
695 SetScrollSensitive(true);
698 if(IsOvershootEnabled())
700 // try and make sure property notifications are set
701 EnableScrollOvershoot(true);
704 ScrollBase::OnSceneConnection(depth);
707 void ScrollView::OnSceneDisconnection()
709 DALI_LOG_SCROLL_STATE("[0x%X]", this);
713 ScrollBase::OnSceneDisconnection();
716 ScrollView::~ScrollView()
718 DALI_LOG_SCROLL_STATE("[0x%X]", this);
721 void ScrollView::ApplyEffect(Toolkit::ScrollViewEffect effect)
723 Dali::Toolkit::ScrollView self = Dali::Toolkit::ScrollView::DownCast(Self());
725 // Assertion check to ensure effect doesn't already exist in this scrollview
726 bool effectAlreadyExistsInScrollView(false);
727 for(ScrollViewEffectIter iter = mEffects.begin(); iter != mEffects.end(); ++iter)
731 effectAlreadyExistsInScrollView = true;
736 DALI_ASSERT_ALWAYS(!effectAlreadyExistsInScrollView);
738 // add effect to effects list
739 mEffects.push_back(effect);
741 // invoke Attachment request to ScrollView first
742 GetImpl(effect).Attach(self);
745 void ScrollView::RemoveEffect(Toolkit::ScrollViewEffect effect)
747 Dali::Toolkit::ScrollView self = Dali::Toolkit::ScrollView::DownCast(Self());
749 // remove effect from effects list
750 bool effectExistedInScrollView(false);
751 for(ScrollViewEffectIter iter = mEffects.begin(); iter != mEffects.end(); ++iter)
755 mEffects.erase(iter);
756 effectExistedInScrollView = true;
761 // Assertion check to ensure effect existed.
762 DALI_ASSERT_ALWAYS(effectExistedInScrollView);
764 // invoke Detachment request to ScrollView last
765 GetImpl(effect).Detach(self);
768 void ScrollView::RemoveAllEffects()
770 Dali::Toolkit::ScrollView self = Dali::Toolkit::ScrollView::DownCast(Self());
772 for(ScrollViewEffectIter effectIter = mEffects.begin(); effectIter != mEffects.end(); ++effectIter)
774 Toolkit::ScrollViewEffect effect = *effectIter;
776 // invoke Detachment request to ScrollView last
777 GetImpl(effect).Detach(self);
783 void ScrollView::ApplyConstraintToChildren(Constraint constraint)
785 ApplyConstraintToBoundActors(constraint);
788 void ScrollView::RemoveConstraintsFromChildren()
790 RemoveConstraintsFromBoundActors();
793 void ScrollView::SetRulerX(RulerPtr ruler)
797 UpdatePropertyDomain();
798 mConstraints.UpdateMainInternalConstraint(*this);
801 void ScrollView::SetRulerY(RulerPtr ruler)
805 UpdatePropertyDomain();
806 mConstraints.UpdateMainInternalConstraint(*this);
809 void ScrollView::UpdatePropertyDomain()
812 Vector3 size = self.GetTargetSize();
813 Vector2 min = mMinScroll;
814 Vector2 max = mMaxScroll;
815 bool scrollPositionChanged = false;
816 bool domainChanged = false;
818 bool canScrollVertical = false;
819 bool canScrollHorizontal = false;
820 UpdateLocalScrollProperties();
821 if(mRulerX->IsEnabled())
823 const Toolkit::RulerDomain& rulerDomain = mRulerX->GetDomain();
824 if(fabsf(min.x - rulerDomain.min) > Math::MACHINE_EPSILON_100 || fabsf(max.x - rulerDomain.max) > Math::MACHINE_EPSILON_100)
826 domainChanged = true;
827 min.x = rulerDomain.min;
828 max.x = rulerDomain.max;
830 // make sure new scroll value is within new domain
831 if(mScrollPrePosition.x < min.x || mScrollPrePosition.x > max.x)
833 scrollPositionChanged = true;
834 mScrollPrePosition.x = Clamp(mScrollPrePosition.x, -(max.x - size.x), -min.x);
837 if((fabsf(rulerDomain.max - rulerDomain.min) - size.x) > Math::MACHINE_EPSILON_100)
839 canScrollHorizontal = true;
842 else if(fabs(min.x) > Math::MACHINE_EPSILON_100 || fabs(max.x) > Math::MACHINE_EPSILON_100)
844 // need to reset to 0
845 domainChanged = true;
848 canScrollHorizontal = false;
851 if(mRulerY->IsEnabled())
853 const Toolkit::RulerDomain& rulerDomain = mRulerY->GetDomain();
854 if(fabsf(min.y - rulerDomain.min) > Math::MACHINE_EPSILON_100 || fabsf(max.y - rulerDomain.max) > Math::MACHINE_EPSILON_100)
856 domainChanged = true;
857 min.y = rulerDomain.min;
858 max.y = rulerDomain.max;
860 // make sure new scroll value is within new domain
861 if(mScrollPrePosition.y < min.y || mScrollPrePosition.y > max.y)
863 scrollPositionChanged = true;
864 mScrollPrePosition.y = Clamp(mScrollPrePosition.y, -(max.y - size.y), -min.y);
867 if((fabsf(rulerDomain.max - rulerDomain.min) - size.y) > Math::MACHINE_EPSILON_100)
869 canScrollVertical = true;
872 else if(fabs(min.y) > Math::MACHINE_EPSILON_100 || fabs(max.y) > Math::MACHINE_EPSILON_100)
874 // need to reset to 0
875 domainChanged = true;
878 canScrollVertical = false;
881 // avoid setting properties if possible, otherwise this will cause an entire update as well as triggering constraints using each property we update
882 if(mCanScrollVertical != canScrollVertical)
884 mCanScrollVertical = canScrollVertical;
885 self.SetProperty(Toolkit::Scrollable::Property::CAN_SCROLL_VERTICAL, canScrollVertical);
887 if(mCanScrollHorizontal != canScrollHorizontal)
889 mCanScrollHorizontal = canScrollHorizontal;
890 self.SetProperty(Toolkit::Scrollable::Property::CAN_SCROLL_HORIZONTAL, canScrollHorizontal);
892 if(scrollPositionChanged)
894 DALI_LOG_SCROLL_STATE("[0x%X] Domain Changed, setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y);
895 self.SetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, mScrollPrePosition);
901 self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MIN, mMinScroll);
902 self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX, mMaxScroll);
906 void ScrollView::SetScrollSensitive(bool sensitive)
909 PanGestureDetector panGesture(GetPanGestureDetector());
911 DALI_LOG_SCROLL_STATE("[0x%X] sensitive: before:[%d] setting[%d]", this, int(mSensitive), int(sensitive));
913 if((!mSensitive) && (sensitive))
915 mSensitive = sensitive;
916 panGesture.Attach(self);
918 else if((mSensitive) && (!sensitive))
920 DALI_LOG_SCROLL_STATE("[0x%X] BEFORE: panning:[%d]", this, int(mPanning));
922 // while the scroll view is panning, the state needs to be reset.
925 PanGesture cancelGesture = DevelPanGesture::New(GestureState::CANCELLED);
926 OnPan(cancelGesture);
929 panGesture.Detach(self);
930 mSensitive = sensitive;
932 mGestureStackDepth = 0;
933 DALI_LOG_SCROLL_STATE("[0x%X] AFTER: panning:[%d]", this, int(mPanning));
937 void ScrollView::SetMaxOvershoot(float overshootX, float overshootY)
939 mMaxOvershoot.x = overshootX;
940 mMaxOvershoot.y = overshootY;
941 mUserMaxOvershoot = mMaxOvershoot;
942 mDefaultMaxOvershoot = false;
943 mConstraints.UpdateMainInternalConstraint(*this);
946 bool ScrollView::GetActorAutoSnap()
948 return mActorAutoSnapEnabled;
951 void ScrollView::SetAutoResize(bool enable)
953 mAutoResizeContainerEnabled = enable;
954 // TODO: This needs a lot of issues to be addressed before working.
957 void ScrollView::SetWrapMode(bool enable)
960 Self().SetProperty(Toolkit::ScrollView::Property::WRAP, enable);
963 void ScrollView::SetAxisAutoLock(bool enable)
965 mAxisAutoLock = enable;
966 mConstraints.UpdateMainInternalConstraint(*this);
969 void ScrollView::SetAxisAutoLockGradient(float gradient)
971 DALI_ASSERT_DEBUG(gradient >= 0.0f && gradient <= 1.0f);
972 mAxisAutoLockGradient = gradient;
973 mConstraints.UpdateMainInternalConstraint(*this);
976 void ScrollView::SetFrictionCoefficient(float friction)
978 DALI_ASSERT_DEBUG(friction > 0.0f);
979 mFrictionCoefficient = friction;
982 unsigned int ScrollView::GetCurrentPage() const
984 // in case animation is currently taking place.
985 Vector2 position = GetPropertyPosition();
988 unsigned int page = 0;
989 unsigned int pagesPerVolume = 1;
990 unsigned int volume = 0;
992 // if rulerX is enabled, then get page count (columns)
993 page = mRulerX->GetPageFromPosition(-position.x, mWrapMode);
994 volume = mRulerY->GetPageFromPosition(-position.y, mWrapMode);
995 pagesPerVolume = mRulerX->GetTotalPages();
997 return volume * pagesPerVolume + page;
1000 Vector2 ScrollView::GetCurrentScrollPosition() const
1002 return -GetPropertyPosition();
1005 void ScrollView::TransformTo(const Vector2& position,
1006 DirectionBias horizontalBias,
1007 DirectionBias verticalBias)
1009 TransformTo(position, mSnapDuration, mSnapAlphaFunction, horizontalBias, verticalBias);
1012 void ScrollView::TransformTo(const Vector2& position, float duration, AlphaFunction alpha, DirectionBias horizontalBias, DirectionBias verticalBias)
1014 // If this is called while the timer is running, then cancel it
1015 StopTouchDownTimer();
1019 // Guard against destruction during signal emission
1020 // Note that Emit() methods are called indirectly e.g. from within ScrollView::AnimateTo()
1021 Toolkit::ScrollView handle(GetOwner());
1023 DALI_LOG_SCROLL_STATE("[0x%X] pos[%.2f,%.2f], duration[%.2f] bias[%d, %d]",
1028 int(horizontalBias),
1031 Vector2 currentScrollPosition = GetCurrentScrollPosition();
1032 self.SetProperty(Toolkit::ScrollView::Property::START_PAGE_POSITION, Vector3(currentScrollPosition));
1034 if(mScrolling) // are we interrupting a current scroll?
1036 // set mScrolling to false, in case user has code that interrogates mScrolling Getter() in complete.
1038 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignal 1 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
1039 mScrollCompletedSignal.Emit(currentScrollPosition);
1042 if(mPanning) // are we interrupting a current pan?
1044 DALI_LOG_SCROLL_STATE("[0x%X] Interrupting Pan, set to false", this);
1046 mGestureStackDepth = 0;
1047 self.SetProperty(Toolkit::ScrollView::Property::PANNING, false);
1049 if(mConstraints.mScrollMainInternalPrePositionConstraint)
1051 mConstraints.mScrollMainInternalPrePositionConstraint.Remove();
1055 self.SetProperty(Toolkit::ScrollView::Property::SCROLLING, true);
1058 DALI_LOG_SCROLL_STATE("[0x%X] mScrollStartedSignal 1 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
1059 mScrollStartedSignal.Emit(currentScrollPosition);
1060 bool animating = AnimateTo(-position,
1061 Vector2::ONE * duration,
1070 // if not animating, then this pan has completed right now.
1071 self.SetProperty(Toolkit::ScrollView::Property::SCROLLING, false);
1074 // If we have no duration, then in the next update frame, we will be at the position specified as we just set.
1075 // In this scenario, we cannot return the currentScrollPosition as this is out-of-date and should instead return the requested final position
1076 Vector2 completedPosition(currentScrollPosition);
1077 if(duration <= Math::MACHINE_EPSILON_10)
1079 completedPosition = position;
1082 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignal 2 [%.2f, %.2f]", this, completedPosition.x, completedPosition.y);
1083 SetScrollUpdateNotification(false);
1084 mScrollCompletedSignal.Emit(completedPosition);
1088 void ScrollView::ScrollTo(const Vector2& position)
1090 ScrollTo(position, mSnapDuration);
1093 void ScrollView::ScrollTo(const Vector2& position, float duration)
1095 ScrollTo(position, duration, DIRECTION_BIAS_NONE, DIRECTION_BIAS_NONE);
1098 void ScrollView::ScrollTo(const Vector2& position, float duration, AlphaFunction alpha)
1100 ScrollTo(position, duration, alpha, DIRECTION_BIAS_NONE, DIRECTION_BIAS_NONE);
1103 void ScrollView::ScrollTo(const Vector2& position, float duration, DirectionBias horizontalBias, DirectionBias verticalBias)
1105 ScrollTo(position, duration, mSnapAlphaFunction, horizontalBias, verticalBias);
1108 void ScrollView::ScrollTo(const Vector2& position, float duration, AlphaFunction alpha, DirectionBias horizontalBias, DirectionBias verticalBias)
1110 DALI_LOG_SCROLL_STATE("[0x%X] position[%.2f, %.2f] duration[%.2f], bias[%d, %d]", this, position.x, position.y, duration, int(horizontalBias), int(verticalBias));
1111 TransformTo(position, duration, alpha, horizontalBias, verticalBias);
1114 void ScrollView::ScrollTo(unsigned int page)
1116 ScrollTo(page, mSnapDuration);
1119 void ScrollView::ScrollTo(unsigned int page, float duration, DirectionBias bias)
1122 unsigned int volume;
1123 unsigned int libraries;
1125 // The position to scroll to is continuous and linear
1126 // unless a domain has been enabled on the X axis.
1127 // or if WrapMode has been enabled.
1128 bool carryX = mRulerX->GetDomain().enabled | mWrapMode;
1129 bool carryY = mRulerY->GetDomain().enabled | mWrapMode;
1131 position.x = mRulerX->GetPositionFromPage(page, volume, carryX);
1132 position.y = mRulerY->GetPositionFromPage(volume, libraries, carryY);
1134 ScrollTo(position, duration, bias, bias);
1137 void ScrollView::ScrollTo(Actor& actor)
1139 ScrollTo(actor, mSnapDuration);
1142 void ScrollView::ScrollTo(Actor& actor, float duration)
1144 DALI_ASSERT_ALWAYS(actor.GetParent() == Self());
1146 Actor self = Self();
1147 Vector3 size = self.GetCurrentProperty<Vector3>(Actor::Property::SIZE);
1148 Vector3 position = actor.GetCurrentProperty<Vector3>(Actor::Property::POSITION);
1149 Vector2 prePosition = GetPropertyPrePosition();
1150 position.GetVectorXY() -= prePosition;
1152 ScrollTo(Vector2(position.x - size.width * 0.5f, position.y - size.height * 0.5f), duration);
1155 Actor ScrollView::FindClosestActor()
1157 Actor self = Self();
1158 Vector3 size = self.GetCurrentProperty<Vector3>(Actor::Property::SIZE);
1160 return FindClosestActorToPosition(Vector3(size.width * 0.5f, size.height * 0.5f, 0.0f));
1163 Actor ScrollView::FindClosestActorToPosition(const Vector3& position, FindDirection dirX, FindDirection dirY, FindDirection dirZ)
1165 return ::FindClosestActorToPosition(Self(), mInternalActor, position, dirX, dirY, dirZ);
1168 bool ScrollView::ScrollToSnapPoint()
1170 DALI_LOG_SCROLL_STATE("[0x%X]", this);
1171 Vector2 stationaryVelocity = Vector2(0.0f, 0.0f);
1172 return SnapWithVelocity(stationaryVelocity);
1175 bool ScrollView::SnapWithVelocity(Vector2 velocity)
1177 Vector2 positionSnap = mScrollPrePosition;
1178 Vector2 positionDuration = Vector2::ONE * mSnapDuration;
1179 AlphaFunction alphaFunction = mSnapAlphaFunction;
1183 ::SnapWithVelocity(*this, mRulerX, mRulerY, mLockAxis, velocity, mMaxOvershoot, positionSnap, positionDuration, alphaFunction, mInAccessibilityPan, isFlick, isFreeFlick);
1185 bool animating = AnimateTo(positionSnap, positionDuration, alphaFunction, false, DIRECTION_BIAS_NONE, DIRECTION_BIAS_NONE, isFlick || isFreeFlick ? FLICK : SNAP);
1190 void ScrollView::StopAnimation(void)
1192 // Clear Snap animation if exists.
1193 StopAnimation(mInternalXAnimation);
1194 StopAnimation(mInternalYAnimation);
1195 mScrollStateFlags = 0;
1196 // remove scroll animation flags
1197 HandleStoppedAnimation();
1200 void ScrollView::StopAnimation(Animation& animation)
1209 bool ScrollView::AnimateTo(const Vector2& position, const Vector2& positionDuration, AlphaFunction alpha, bool findShortcuts, DirectionBias horizontalBias, DirectionBias verticalBias, SnapType snapType)
1211 // Here we perform an animation on a number of properties (depending on which have changed)
1212 // The animation is applied to all ScrollBases
1213 Actor self = Self();
1214 mScrollTargetPosition = position;
1215 float totalDuration = 0.0f;
1217 bool positionChanged = (mScrollTargetPosition != mScrollPostPosition);
1221 totalDuration = std::max(totalDuration, positionDuration.x);
1222 totalDuration = std::max(totalDuration, positionDuration.y);
1226 // try to animate for a frame, on some occasions update will be changing scroll value while event side thinks it hasnt changed
1227 totalDuration = 0.01f;
1228 positionChanged = true;
1233 // Position Delta ///////////////////////////////////////////////////////
1236 mConstraints.UpdateMainInternalConstraint(*this);
1237 if(mWrapMode && findShortcuts)
1239 // In Wrap Mode, the shortest distance is a little less intuitive...
1240 const RulerDomain rulerDomainX = mRulerX->GetDomain();
1241 const RulerDomain rulerDomainY = mRulerY->GetDomain();
1243 if(mRulerX->IsEnabled())
1245 float dir = VectorInDomain(-mScrollPrePosition.x, -mScrollTargetPosition.x, rulerDomainX.min, rulerDomainX.max, horizontalBias);
1246 mScrollTargetPosition.x = mScrollPrePosition.x + -dir;
1249 if(mRulerY->IsEnabled())
1251 float dir = VectorInDomain(-mScrollPrePosition.y, -mScrollTargetPosition.y, rulerDomainY.min, rulerDomainY.max, verticalBias);
1252 mScrollTargetPosition.y = mScrollPrePosition.y + -dir;
1256 // note we have two separate animations for X & Y, this deals with sliding diagonally and hitting
1257 // a horizonal/vertical wall.delay
1258 AnimateInternalXTo(mScrollTargetPosition.x, positionDuration.x, alpha);
1259 AnimateInternalYTo(mScrollTargetPosition.y, positionDuration.y, alpha);
1261 if(!(mScrollStateFlags & SCROLL_ANIMATION_FLAGS))
1263 DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollTargetPosition.x, mScrollTargetPosition.y);
1264 self.SetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, mScrollTargetPosition);
1265 mScrollPrePosition = mScrollTargetPosition;
1266 mScrollPostPosition = mScrollTargetPosition;
1267 WrapPosition(mScrollPostPosition);
1270 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);
1271 DALI_LOG_SCROLL_STATE("[0x%X] SCROLL_PRE_POSITION[%.2f, %.2f], SCROLL_POSITION[%.2f, %.2f]", this, self.GetCurrentProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION).Get<Vector2>().x, self.GetCurrentProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION).Get<Vector2>().y, self.GetCurrentProperty(Toolkit::ScrollView::Property::SCROLL_POSITION).Get<Vector2>().x, self.GetCurrentProperty(Toolkit::ScrollView::Property::SCROLL_POSITION).Get<Vector2>().y);
1274 SetScrollUpdateNotification(true);
1276 // Always send a snap event when AnimateTo is called.
1277 Toolkit::ScrollView::SnapEvent snapEvent;
1278 snapEvent.type = snapType;
1279 snapEvent.position = -mScrollTargetPosition;
1280 snapEvent.duration = totalDuration;
1282 DALI_LOG_SCROLL_STATE("[0x%X] mSnapStartedSignal [%.2f, %.2f]", this, snapEvent.position.x, snapEvent.position.y);
1283 mSnapStartedSignal.Emit(snapEvent);
1285 return (mScrollStateFlags & SCROLL_ANIMATION_FLAGS) != 0;
1288 void ScrollView::EnableScrollOvershoot(bool enable)
1292 if(!mOvershootIndicator)
1294 mOvershootIndicator = ScrollOvershootIndicator::New();
1297 mOvershootIndicator->AttachToScrollable(*this);
1301 mMaxOvershoot = mUserMaxOvershoot;
1303 if(mOvershootIndicator)
1305 mOvershootIndicator->DetachFromScrollable(*this);
1309 mConstraints.UpdateMainInternalConstraint(*this);
1312 void ScrollView::AddOverlay(Actor actor)
1314 actor.SetProperty(Actor::Property::DRAW_MODE, DrawMode::OVERLAY_2D);
1315 mInternalActor.Add(actor);
1318 void ScrollView::RemoveOverlay(Actor actor)
1320 mInternalActor.Remove(actor);
1323 void ScrollView::SetOvershootSize(const Vector2& size)
1325 mOvershootSize = size;
1326 if(IsOvershootEnabled() && mOvershootIndicator)
1328 mOvershootIndicator->AttachToScrollable(*this);
1332 void ScrollView::SetOvershootEffectColor(const Vector4& color)
1334 mOvershootEffectColor = color;
1335 if(mOvershootIndicator)
1337 mOvershootIndicator->SetOvershootEffectColor(color);
1341 void ScrollView::SetScrollingDirection(Radian direction, Radian threshold)
1343 PanGestureDetector panGesture(GetPanGestureDetector());
1345 // First remove just in case we have some set, then add.
1346 panGesture.RemoveDirection(direction);
1347 panGesture.AddDirection(direction, threshold);
1350 void ScrollView::RemoveScrollingDirection(Radian direction)
1352 PanGestureDetector panGesture(GetPanGestureDetector());
1353 panGesture.RemoveDirection(direction);
1356 Toolkit::ScrollView::SnapStartedSignalType& ScrollView::SnapStartedSignal()
1358 return mSnapStartedSignal;
1361 bool ScrollView::AccessibleImpl::ScrollToChild(Actor child)
1363 auto scrollView = Dali::Toolkit::ScrollView::DownCast(Self());
1364 if(Toolkit::GetImpl(scrollView).FindClosestActor() == child)
1369 // FIXME: ScrollTo does not work (snaps back to original position)
1370 scrollView.ScrollTo(child, scrollView.GetScrollFlickDuration());
1374 void ScrollView::FindAndUnbindActor(Actor child)
1379 Vector2 ScrollView::GetPropertyPrePosition() const
1381 Vector2 position = Self().GetCurrentProperty<Vector2>(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION);
1382 WrapPosition(position);
1386 Vector2 ScrollView::GetPropertyPosition() const
1388 Vector2 position = Self().GetCurrentProperty<Vector2>(Toolkit::ScrollView::Property::SCROLL_POSITION);
1389 WrapPosition(position);
1394 void ScrollView::HandleStoppedAnimation()
1396 SetScrollUpdateNotification(false);
1399 void ScrollView::HandleSnapAnimationFinished()
1401 // Emit Signal that scrolling has completed.
1403 Actor self = Self();
1404 self.SetProperty(Toolkit::ScrollView::Property::SCROLLING, false);
1406 Vector2 deltaPosition(mScrollPrePosition);
1408 UpdateLocalScrollProperties();
1409 WrapPosition(mScrollPrePosition);
1410 DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y);
1411 self.SetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, mScrollPrePosition);
1413 Vector2 currentScrollPosition = GetCurrentScrollPosition();
1414 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignal 3 current[%.2f, %.2f], mScrollTargetPosition[%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y, -mScrollTargetPosition.x, -mScrollTargetPosition.y);
1415 mScrollCompletedSignal.Emit(currentScrollPosition);
1417 mDomainOffset += deltaPosition - mScrollPostPosition;
1418 self.SetProperty(Toolkit::ScrollView::Property::SCROLL_DOMAIN_OFFSET, mDomainOffset);
1419 HandleStoppedAnimation();
1422 void ScrollView::SetScrollUpdateNotification(bool enabled)
1424 Actor self = Self();
1425 if(mScrollXUpdateNotification)
1427 // disconnect now to avoid a notification before removed from update thread
1428 mScrollXUpdateNotification.NotifySignal().Disconnect(this, &ScrollView::OnScrollUpdateNotification);
1429 self.RemovePropertyNotification(mScrollXUpdateNotification);
1430 mScrollXUpdateNotification.Reset();
1432 if(enabled && !mScrollUpdatedSignal.Empty())
1434 // Only set up the notification when the application has connected to the updated signal
1435 mScrollXUpdateNotification = self.AddPropertyNotification(Toolkit::ScrollView::Property::SCROLL_POSITION, 0, StepCondition(mScrollUpdateDistance, 0.0f));
1436 mScrollXUpdateNotification.NotifySignal().Connect(this, &ScrollView::OnScrollUpdateNotification);
1438 if(mScrollYUpdateNotification)
1440 // disconnect now to avoid a notification before removed from update thread
1441 mScrollYUpdateNotification.NotifySignal().Disconnect(this, &ScrollView::OnScrollUpdateNotification);
1442 self.RemovePropertyNotification(mScrollYUpdateNotification);
1443 mScrollYUpdateNotification.Reset();
1445 if(enabled && !mScrollUpdatedSignal.Empty())
1447 // Only set up the notification when the application has connected to the updated signal
1448 mScrollYUpdateNotification = self.AddPropertyNotification(Toolkit::ScrollView::Property::SCROLL_POSITION, 1, StepCondition(mScrollUpdateDistance, 0.0f));
1449 mScrollYUpdateNotification.NotifySignal().Connect(this, &ScrollView::OnScrollUpdateNotification);
1453 void ScrollView::OnScrollUpdateNotification(Dali::PropertyNotification& source)
1455 // Guard against destruction during signal emission
1456 Toolkit::ScrollView handle(GetOwner());
1458 Vector2 currentScrollPosition = GetCurrentScrollPosition();
1459 mScrollUpdatedSignal.Emit(currentScrollPosition);
1462 bool ScrollView::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor)
1464 Dali::BaseHandle handle(object);
1466 bool connected(true);
1467 Toolkit::ScrollView view = Toolkit::ScrollView::DownCast(handle);
1469 if(0 == strcmp(signalName.c_str(), SIGNAL_SNAP_STARTED))
1471 view.SnapStartedSignal().Connect(tracker, functor);
1475 // signalName does not match any signal
1482 void ScrollView::OnSizeAnimation(Animation& animation, const Vector3& targetSize)
1484 // need to update domain properties for new size
1485 UpdatePropertyDomain();
1488 void ScrollView::OnSizeSet(const Vector3& size)
1490 // need to update domain properties for new size
1491 if(mDefaultMaxOvershoot)
1493 mUserMaxOvershoot.x = size.x * 0.5f;
1494 mUserMaxOvershoot.y = size.y * 0.5f;
1495 if(!IsOvershootEnabled())
1497 mMaxOvershoot = mUserMaxOvershoot;
1500 UpdatePropertyDomain();
1501 mConstraints.UpdateMainInternalConstraint(*this);
1502 if(IsOvershootEnabled())
1504 mOvershootIndicator->Reset();
1507 ScrollBase::OnSizeSet(size);
1510 void ScrollView::OnChildAdd(Actor& child)
1512 ScrollBase::OnChildAdd(child);
1514 Dali::Toolkit::ScrollBar scrollBar = Dali::Toolkit::ScrollBar::DownCast(child);
1517 mScrollBar = scrollBar;
1518 scrollBar.SetProperty(Dali::Actor::Property::NAME, "ScrollBar");
1520 mInternalActor.Add(scrollBar);
1521 if(scrollBar.GetScrollDirection() == Toolkit::ScrollBar::HORIZONTAL)
1523 scrollBar.SetScrollPropertySource(Self(),
1524 Toolkit::ScrollView::Property::SCROLL_PRE_POSITION_X,
1525 Toolkit::Scrollable::Property::SCROLL_POSITION_MIN_X,
1526 Toolkit::ScrollView::Property::SCROLL_PRE_POSITION_MAX_X,
1527 Toolkit::ScrollView::Property::SCROLL_DOMAIN_SIZE_X);
1531 scrollBar.SetScrollPropertySource(Self(),
1532 Toolkit::ScrollView::Property::SCROLL_PRE_POSITION_Y,
1533 Toolkit::Scrollable::Property::SCROLL_POSITION_MIN_Y,
1534 Toolkit::ScrollView::Property::SCROLL_PRE_POSITION_MAX_Y,
1535 Toolkit::ScrollView::Property::SCROLL_DOMAIN_SIZE_Y);
1538 if(mTransientScrollBar)
1540 // Show the scroll-indicator for a brief period
1541 Property::Map emptyMap;
1542 scrollBar.DoAction("ShowTransientIndicator", emptyMap);
1545 else if(mAlterChild)
1551 void ScrollView::OnChildRemove(Actor& child)
1553 // TODO: Actor needs a RemoveConstraint method to take out an individual constraint.
1556 ScrollBase::OnChildRemove(child);
1559 void ScrollView::StartTouchDownTimer()
1561 if(!mTouchDownTimer)
1563 mTouchDownTimer = Timer::New(TOUCH_DOWN_TIMER_INTERVAL);
1564 mTouchDownTimer.TickSignal().Connect(this, &ScrollView::OnTouchDownTimeout);
1567 mTouchDownTimer.Start();
1570 void ScrollView::StopTouchDownTimer()
1574 mTouchDownTimer.Stop();
1578 bool ScrollView::OnTouchDownTimeout()
1580 DALI_LOG_SCROLL_STATE("[0x%X]", this);
1582 mTouchDownTimeoutReached = true;
1584 unsigned int currentScrollStateFlags(mScrollStateFlags); // Cleared in StopAnimation so keep local copy for comparison
1585 if(currentScrollStateFlags & (SCROLL_ANIMATION_FLAGS | SNAP_ANIMATION_FLAGS))
1587 DALI_LOG_SCROLL_STATE("[0x%X] Scrolling Or snapping flags set, stopping animation", this);
1590 if(currentScrollStateFlags & SCROLL_ANIMATION_FLAGS)
1592 DALI_LOG_SCROLL_STATE("[0x%X] Scrolling flags set, emitting signal", this);
1594 mScrollInterrupted = true;
1595 // reset domain offset as scrolling from original plane.
1596 mDomainOffset = Vector2::ZERO;
1597 Self().SetProperty(Toolkit::ScrollView::Property::SCROLL_DOMAIN_OFFSET, Vector2::ZERO);
1599 UpdateLocalScrollProperties();
1600 Vector2 currentScrollPosition = GetCurrentScrollPosition();
1601 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignal 4 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
1602 mScrollCompletedSignal.Emit(currentScrollPosition);
1609 bool ScrollView::OnTouch(Actor actor, const TouchEvent& touch)
1613 DALI_LOG_SCROLL_STATE("[0x%X], Not Sensitive, ignoring", this);
1615 // Ignore this touch event, if scrollview is insensitive.
1619 // Ignore events with multiple-touch points
1620 if(touch.GetPointCount() != 1)
1622 DALI_LOG_SCROLL_STATE("[0x%X], multiple touch, ignoring", this);
1627 const PointState::Type pointState = touch.GetState(0);
1628 if(pointState == PointState::DOWN)
1630 DALI_LOG_SCROLL_STATE("[0x%X] Down", this);
1632 if(mGestureStackDepth == 0)
1634 mTouchDownTime = touch.GetTime();
1636 // This allows time for a pan-gesture to start, to avoid breaking snap-animation behavior with fast flicks.
1637 // If touch-down does not become a pan (after timeout interval), then snap-animation can be interrupted.
1638 mTouchDownTimeoutReached = false;
1639 mScrollInterrupted = false;
1640 StartTouchDownTimer();
1643 else if((pointState == PointState::UP) ||
1644 ((pointState == PointState::INTERRUPTED) && (touch.GetHitActor(0) == Self())))
1646 DALI_LOG_SCROLL_STATE("[0x%X] %s", this, ((pointState == PointState::UP) ? "Up" : "Interrupted"));
1648 StopTouchDownTimer();
1650 // if the user touches and releases without enough movement to go
1651 // into a gesture state, then we should snap to nearest point.
1652 // otherwise our scroll could be stopped (interrupted) half way through an animation.
1653 if(mGestureStackDepth == 0 && mTouchDownTimeoutReached)
1655 if((pointState == PointState::INTERRUPTED) ||
1656 ((touch.GetTime() - mTouchDownTime) >= MINIMUM_TIME_BETWEEN_DOWN_AND_UP_FOR_RESET))
1658 // Reset the velocity only if down was received a while ago
1659 mLastVelocity = Vector2(0.0f, 0.0f);
1662 UpdateLocalScrollProperties();
1663 // Only finish the transform if scrolling was interrupted on down or if we are scrolling
1664 if(mScrollInterrupted || mScrolling)
1666 DALI_LOG_SCROLL_STATE("[0x%X] Calling FinishTransform", this);
1671 mTouchDownTimeoutReached = false;
1672 mScrollInterrupted = false;
1678 bool ScrollView::OnWheelEvent(Actor actor, const WheelEvent& event)
1682 // Ignore this wheel event, if scrollview is insensitive.
1686 Vector2 targetScrollPosition = GetPropertyPosition();
1688 if(mRulerX->IsEnabled() && !mRulerY->IsEnabled())
1690 // If only the ruler in the X axis is enabled, scroll in the X axis.
1691 if(mRulerX->GetType() == Ruler::FREE)
1693 // Free panning mode
1694 targetScrollPosition.x += event.GetDelta() * mWheelScrollDistanceStep.x;
1695 ClampPosition(targetScrollPosition);
1696 ScrollTo(-targetScrollPosition);
1698 else if(!mScrolling)
1700 // Snap mode, only respond to the event when the previous snap animation is finished.
1701 ScrollTo(GetCurrentPage() - event.GetDelta());
1706 // If the ruler in the Y axis is enabled, scroll in the Y axis.
1707 if(mRulerY->GetType() == Ruler::FREE)
1709 // Free panning mode
1710 targetScrollPosition.y += event.GetDelta() * mWheelScrollDistanceStep.y;
1711 ClampPosition(targetScrollPosition);
1712 ScrollTo(-targetScrollPosition);
1714 else if(!mScrolling)
1716 // Snap mode, only respond to the event when the previous snap animation is finished.
1717 ScrollTo(GetCurrentPage() - event.GetDelta() * mRulerX->GetTotalPages());
1724 void ScrollView::ResetScrolling()
1726 Actor self = Self();
1727 self.GetCurrentProperty(Toolkit::ScrollView::Property::SCROLL_POSITION).Get(mScrollPostPosition);
1728 mScrollPrePosition = mScrollPostPosition;
1729 DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPostPosition.x, mScrollPostPosition.y);
1730 self.SetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, mScrollPostPosition);
1733 void ScrollView::UpdateLocalScrollProperties()
1735 Actor self = Self();
1736 self.GetCurrentProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION).Get(mScrollPrePosition);
1737 self.GetCurrentProperty(Toolkit::ScrollView::Property::SCROLL_POSITION).Get(mScrollPostPosition);
1740 // private functions
1742 void ScrollView::PreAnimatedScrollSetup()
1744 // SCROLL_PRE_POSITION is our unclamped property with wrapping
1745 // SCROLL_POSITION is our final scroll position after clamping
1747 Actor self = Self();
1749 Vector2 deltaPosition(mScrollPostPosition);
1750 WrapPosition(mScrollPostPosition);
1751 mDomainOffset += deltaPosition - mScrollPostPosition;
1752 Self().SetProperty(Toolkit::ScrollView::Property::SCROLL_DOMAIN_OFFSET, mDomainOffset);
1754 if(mScrollStateFlags & SCROLL_X_STATE_MASK)
1756 // already performing animation on internal x position
1757 StopAnimation(mInternalXAnimation);
1760 if(mScrollStateFlags & SCROLL_Y_STATE_MASK)
1762 // already performing animation on internal y position
1763 StopAnimation(mInternalYAnimation);
1766 mScrollStateFlags = 0;
1768 // Update Actor position with this wrapped value.
1771 void ScrollView::FinaliseAnimatedScroll()
1773 // TODO - common animation finishing code in here
1776 void ScrollView::AnimateInternalXTo(float position, float duration, AlphaFunction alpha)
1778 StopAnimation(mInternalXAnimation);
1780 if(duration > Math::MACHINE_EPSILON_10)
1782 Actor self = Self();
1783 DALI_LOG_SCROLL_STATE("[0x%X], Animating from[%.2f] to[%.2f]", this, self.GetCurrentProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION).Get<Vector2>().x, position);
1784 mInternalXAnimation = Animation::New(duration);
1785 DALI_LOG_SCROLL_STATE("[0x%X], mInternalXAnimation[0x%X]", this, mInternalXAnimation.GetObjectPtr());
1786 mInternalXAnimation.FinishedSignal().Connect(this, &ScrollView::OnScrollAnimationFinished);
1787 mInternalXAnimation.AnimateTo(Property(self, Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, 0), position, alpha, TimePeriod(duration));
1788 mInternalXAnimation.Play();
1790 // erase current state flags
1791 mScrollStateFlags &= ~SCROLL_X_STATE_MASK;
1792 // add internal animation state flag
1793 mScrollStateFlags |= AnimatingInternalX;
1797 void ScrollView::AnimateInternalYTo(float position, float duration, AlphaFunction alpha)
1799 StopAnimation(mInternalYAnimation);
1801 if(duration > Math::MACHINE_EPSILON_10)
1803 Actor self = Self();
1804 DALI_LOG_SCROLL_STATE("[0x%X], Animating from[%.2f] to[%.2f]", this, self.GetCurrentProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION).Get<Vector2>().y, position);
1805 mInternalYAnimation = Animation::New(duration);
1806 DALI_LOG_SCROLL_STATE("[0x%X], mInternalYAnimation[0x%X]", this, mInternalYAnimation.GetObjectPtr());
1807 mInternalYAnimation.FinishedSignal().Connect(this, &ScrollView::OnScrollAnimationFinished);
1808 mInternalYAnimation.AnimateTo(Property(self, Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, 1), position, alpha, TimePeriod(duration));
1809 mInternalYAnimation.Play();
1811 // erase current state flags
1812 mScrollStateFlags &= ~SCROLL_Y_STATE_MASK;
1813 // add internal animation state flag
1814 mScrollStateFlags |= AnimatingInternalY;
1818 void ScrollView::OnScrollAnimationFinished(Animation& source)
1820 // Guard against destruction during signal emission
1821 // Note that ScrollCompletedSignal is emitted from HandleSnapAnimationFinished()
1822 Toolkit::ScrollView handle(GetOwner());
1824 bool scrollingFinished = false;
1826 // update our local scroll positions
1827 UpdateLocalScrollProperties();
1829 if(source == mInternalXAnimation)
1831 DALI_LOG_SCROLL_STATE("[0x%X] mInternalXAnimation[0x%X], expected[%.2f], actual[%.2f], post[%.2f]", this, mInternalXAnimation.GetObjectPtr(), mScrollTargetPosition.x, Self().GetCurrentProperty(SCROLL_PRE_POSITION).Get<Vector2>().x, mScrollPostPosition.x);
1833 if(!(mScrollStateFlags & AnimatingInternalY))
1835 scrollingFinished = true;
1837 mInternalXAnimation.Reset();
1838 // wrap pre scroll x position and set it
1841 const RulerDomain rulerDomain = mRulerX->GetDomain();
1842 mScrollPrePosition.x = -WrapInDomain(-mScrollPrePosition.x, rulerDomain.min, rulerDomain.max);
1843 DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y);
1844 handle.SetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, mScrollPrePosition);
1846 SnapInternalXTo(mScrollPostPosition.x);
1849 if(source == mInternalYAnimation)
1851 DALI_LOG_SCROLL_STATE("[0x%X] mInternalYAnimation[0x%X], expected[%.2f], actual[%.2f], post[%.2f]", this, mInternalYAnimation.GetObjectPtr(), mScrollTargetPosition.y, DevelHandle::GetProperty(Self(), SCROLL_PRE_POSITION).Get<Vector2>().y, mScrollPostPosition.y);
1853 if(!(mScrollStateFlags & AnimatingInternalX))
1855 scrollingFinished = true;
1857 mInternalYAnimation.Reset();
1860 // wrap pre scroll y position and set it
1861 const RulerDomain rulerDomain = mRulerY->GetDomain();
1862 mScrollPrePosition.y = -WrapInDomain(-mScrollPrePosition.y, rulerDomain.min, rulerDomain.max);
1863 DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y);
1864 handle.SetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, mScrollPrePosition);
1866 SnapInternalYTo(mScrollPostPosition.y);
1869 DALI_LOG_SCROLL_STATE("[0x%X] scrollingFinished[%d] Animation[0x%X]", this, scrollingFinished, source.GetObjectPtr());
1871 if(scrollingFinished)
1873 HandleSnapAnimationFinished();
1877 void ScrollView::OnSnapInternalPositionFinished(Animation& source)
1879 Actor self = Self();
1880 UpdateLocalScrollProperties();
1881 if(source == mInternalXAnimation)
1883 DALI_LOG_SCROLL_STATE("[0x%X] Finished X PostPosition Animation", this);
1885 // clear internal x animation flags
1886 mScrollStateFlags &= ~SCROLL_X_STATE_MASK;
1887 mInternalXAnimation.Reset();
1888 WrapPosition(mScrollPrePosition);
1890 if(source == mInternalYAnimation)
1892 DALI_LOG_SCROLL_STATE("[0x%X] Finished Y PostPosition Animation", this);
1894 mScrollStateFlags &= ~SCROLL_Y_STATE_MASK;
1895 mInternalYAnimation.Reset();
1896 WrapPosition(mScrollPrePosition);
1900 void ScrollView::SnapInternalXTo(float position)
1902 Actor self = Self();
1904 StopAnimation(mInternalXAnimation);
1906 // erase current state flags
1907 mScrollStateFlags &= ~SCROLL_X_STATE_MASK;
1909 // if internal x not equal to inputed parameter, animate it
1910 float duration = std::min(fabsf((position - mScrollPrePosition.x) / mMaxOvershoot.x) * mSnapOvershootDuration, mSnapOvershootDuration);
1911 DALI_LOG_SCROLL_STATE("[0x%X] duration[%.2f]", this, duration);
1912 if(duration > Math::MACHINE_EPSILON_1)
1914 DALI_LOG_SCROLL_STATE("[0x%X] Starting X Snap Animation to[%.2f]", this, position);
1916 mInternalXAnimation = Animation::New(duration);
1917 mInternalXAnimation.FinishedSignal().Connect(this, &ScrollView::OnSnapInternalPositionFinished);
1918 mInternalXAnimation.AnimateTo(Property(self, Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, 0), position);
1919 mInternalXAnimation.Play();
1921 // add internal animation state flag
1922 mScrollStateFlags |= SnappingInternalX;
1926 void ScrollView::SnapInternalYTo(float position)
1928 Actor self = Self();
1930 StopAnimation(mInternalYAnimation);
1932 // erase current state flags
1933 mScrollStateFlags &= ~SCROLL_Y_STATE_MASK;
1935 // if internal y not equal to inputed parameter, animate it
1936 float duration = std::min(fabsf((position - mScrollPrePosition.y) / mMaxOvershoot.y) * mSnapOvershootDuration, mSnapOvershootDuration);
1937 DALI_LOG_SCROLL_STATE("[0x%X] duration[%.2f]", this, duration);
1938 if(duration > Math::MACHINE_EPSILON_1)
1940 DALI_LOG_SCROLL_STATE("[0x%X] Starting Y Snap Animation to[%.2f]", this, position);
1942 mInternalYAnimation = Animation::New(duration);
1943 mInternalYAnimation.FinishedSignal().Connect(this, &ScrollView::OnSnapInternalPositionFinished);
1944 mInternalYAnimation.AnimateTo(Property(self, Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, 1), position);
1945 mInternalYAnimation.Play();
1947 // add internal animation state flag
1948 mScrollStateFlags |= SnappingInternalY;
1952 void ScrollView::GestureStarted()
1954 // we handle the first gesture.
1955 // if we're currently doing a gesture and receive another
1956 // we continue and combine the effects of the gesture instead of reseting.
1957 if(mGestureStackDepth++ == 0)
1959 Actor self = Self();
1960 StopTouchDownTimer();
1962 mPanDelta = Vector2::ZERO;
1963 mLastVelocity = Vector2::ZERO;
1966 mLockAxis = LockPossible;
1969 if(mScrollStateFlags & SCROLL_X_STATE_MASK)
1971 StopAnimation(mInternalXAnimation);
1973 if(mScrollStateFlags & SCROLL_Y_STATE_MASK)
1975 StopAnimation(mInternalYAnimation);
1977 mScrollStateFlags = 0;
1979 if(mScrolling) // are we interrupting a current scroll?
1981 // set mScrolling to false, in case user has code that interrogates mScrolling Getter() in complete.
1983 // send negative scroll position since scroll internal scroll position works as an offset for actors,
1984 // give applications the position within the domain from the scroll view's anchor position
1985 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignal 5 [%.2f, %.2f]", this, -mScrollPostPosition.x, -mScrollPostPosition.y);
1986 mScrollCompletedSignal.Emit(-mScrollPostPosition);
1991 void ScrollView::GestureContinuing(const Vector2& panDelta)
1993 mPanDelta.x += panDelta.x;
1994 mPanDelta.y += panDelta.y;
1996 // Save the velocity, there is a bug in PanGesture
1997 // Whereby the GestureState::FINISHED's velocity is either:
1998 // NaN (due to time delta of zero between the last two events)
1999 // or 0 (due to position being the same between the last two events)
2001 // Axis Auto Lock - locks the panning to the horizontal or vertical axis if the pan
2002 // appears mostly horizontal or mostly vertical respectively.
2005 mLockAxis = GetLockAxis(mPanDelta, mLockAxis, mAxisAutoLockGradient);
2006 } // end if mAxisAutoLock
2009 // TODO: Upgrade to use a more powerful gesture detector (one that supports multiple touches on pan - so works as pan and flick gesture)
2010 // BUG: GestureState::FINISHED doesn't always return velocity on release (due to
2011 // timeDelta between last two events being 0 sometimes, or posiiton being the same)
2012 void ScrollView::OnPan(const PanGesture& gesture)
2014 // Guard against destruction during signal emission
2015 // Note that Emit() methods are called indirectly e.g. from within ScrollView::OnGestureEx()
2020 DALI_LOG_SCROLL_STATE("[0x%X] Pan Ignored, Insensitive", this);
2022 // If another callback on the same original signal disables sensitivity,
2023 // this callback will still be called, so we must suppress it.
2027 // translate Gesture input to get useful data...
2028 switch(gesture.GetState())
2030 case GestureState::STARTED:
2032 DALI_LOG_SCROLL_STATE("[0x%X] Pan Started", this);
2033 const Vector2& position = gesture.GetPosition();
2034 mPanStartPosition = position - gesture.GetDisplacement();
2035 UpdateLocalScrollProperties();
2038 self.SetProperty(Toolkit::ScrollView::Property::PANNING, true);
2039 self.SetProperty(Toolkit::ScrollView::Property::START_PAGE_POSITION, Vector3(position.x, position.y, 0.0f));
2041 mConstraints.UpdateMainInternalConstraint(*this);
2042 Toolkit::ScrollBar scrollBar = mScrollBar.GetHandle();
2043 if(scrollBar && mTransientScrollBar)
2045 Vector3 size = Self().GetCurrentProperty<Vector3>(Actor::Property::SIZE);
2046 const Toolkit::RulerDomain& rulerDomainX = mRulerX->GetDomain();
2047 const Toolkit::RulerDomain& rulerDomainY = mRulerY->GetDomain();
2049 if((rulerDomainX.max > size.width) || (rulerDomainY.max > size.height))
2051 scrollBar.ShowIndicator();
2057 case GestureState::CONTINUING:
2061 DALI_LOG_SCROLL_STATE("[0x%X] Pan Continuing", this);
2062 GestureContinuing(gesture.GetScreenDisplacement());
2066 // If we do not think we are panning, then we should not do anything here
2072 case GestureState::FINISHED:
2073 case GestureState::CANCELLED:
2077 DALI_LOG_SCROLL_STATE("[0x%X] Pan %s", this, ((gesture.GetState() == GestureState::FINISHED) ? "Finished" : "Cancelled"));
2079 UpdateLocalScrollProperties();
2080 mLastVelocity = gesture.GetVelocity();
2082 self.SetProperty(Toolkit::ScrollView::Property::PANNING, false);
2084 if(mConstraints.mScrollMainInternalPrePositionConstraint)
2086 mConstraints.mScrollMainInternalPrePositionConstraint.Remove();
2089 Toolkit::ScrollBar scrollBar = mScrollBar.GetHandle();
2090 if(scrollBar && mTransientScrollBar)
2092 scrollBar.HideIndicator();
2097 // If we do not think we are panning, then we should not do anything here
2103 case GestureState::POSSIBLE:
2104 case GestureState::CLEAR:
2106 // Nothing to do, not needed.
2110 } // end switch(gesture.state)
2112 OnGestureEx(gesture.GetState());
2115 void ScrollView::OnGestureEx(GestureState state)
2117 // call necessary signals for application developer
2119 if(state == GestureState::STARTED)
2121 Vector2 currentScrollPosition = GetCurrentScrollPosition();
2122 Self().SetProperty(Toolkit::ScrollView::Property::SCROLLING, true);
2124 DALI_LOG_SCROLL_STATE("[0x%X] mScrollStartedSignal 2 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
2125 mScrollStartedSignal.Emit(currentScrollPosition);
2127 else if((state == GestureState::FINISHED) ||
2128 (state == GestureState::CANCELLED)) // Finished/default
2130 // when all the gestures have finished, we finish the transform.
2131 // so if a user decides to pan (1 gesture), and then pan+zoom (2 gestures)
2132 // then stop panning (back to 1 gesture), and then stop zooming (0 gestures).
2133 // this is the point we end, and perform necessary snapping.
2134 mGestureStackDepth--;
2135 if(mGestureStackDepth == 0)
2137 // no flick if we have not exceeded min flick distance
2138 if((fabsf(mPanDelta.x) < mMinFlickDistance.x) && (fabsf(mPanDelta.y) < mMinFlickDistance.y))
2140 // reset flick velocity
2141 mLastVelocity = Vector2::ZERO;
2147 DALI_LOG_SCROLL_STATE("[0x%X] mGestureStackDepth[%d]", this, mGestureStackDepth);
2152 void ScrollView::FinishTransform()
2154 // at this stage internal x and x scroll position should have followed prescroll position exactly
2155 Actor self = Self();
2157 PreAnimatedScrollSetup();
2159 // convert pixels/millisecond to pixels per second
2160 bool animating = SnapWithVelocity(mLastVelocity * 1000.0f);
2164 // if not animating, then this pan has completed right now.
2165 SetScrollUpdateNotification(false);
2167 Self().SetProperty(Toolkit::ScrollView::Property::SCROLLING, false);
2169 if(fabs(mScrollPrePosition.x - mScrollTargetPosition.x) > Math::MACHINE_EPSILON_10)
2171 SnapInternalXTo(mScrollTargetPosition.x);
2173 if(fabs(mScrollPrePosition.y - mScrollTargetPosition.y) > Math::MACHINE_EPSILON_10)
2175 SnapInternalYTo(mScrollTargetPosition.y);
2177 Vector2 currentScrollPosition = GetCurrentScrollPosition();
2178 DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignal 6 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y);
2179 mScrollCompletedSignal.Emit(currentScrollPosition);
2183 Vector2 ScrollView::GetOvershoot(Vector2& position) const
2185 Vector3 size = Self().GetCurrentProperty<Vector3>(Actor::Property::SIZE);
2188 const RulerDomain rulerDomainX = mRulerX->GetDomain();
2189 const RulerDomain rulerDomainY = mRulerY->GetDomain();
2191 if(mRulerX->IsEnabled() && rulerDomainX.enabled)
2193 const float left = rulerDomainX.min - position.x;
2194 const float right = size.width - rulerDomainX.max - position.x;
2201 overshoot.x = right;
2205 if(mRulerY->IsEnabled() && rulerDomainY.enabled)
2207 const float top = rulerDomainY.min - position.y;
2208 const float bottom = size.height - rulerDomainY.max - position.y;
2215 overshoot.y = bottom;
2222 bool ScrollView::OnAccessibilityPan(PanGesture gesture)
2224 // Keep track of whether this is an AccessibilityPan
2225 mInAccessibilityPan = true;
2227 mInAccessibilityPan = false;
2232 void ScrollView::ClampPosition(Vector2& position) const
2234 ClampState2D clamped;
2235 ClampPosition(position, clamped);
2238 void ScrollView::ClampPosition(Vector2& position, ClampState2D& clamped) const
2240 Vector3 size = Self().GetCurrentProperty<Vector3>(Actor::Property::SIZE);
2242 ::ClampPosition(size, mRulerX, mRulerY, position, clamped);
2245 void ScrollView::WrapPosition(Vector2& position) const
2249 const RulerDomain rulerDomainX = mRulerX->GetDomain();
2250 const RulerDomain rulerDomainY = mRulerY->GetDomain();
2252 if(mRulerX->IsEnabled())
2254 position.x = -WrapInDomain(-position.x, rulerDomainX.min, rulerDomainX.max);
2257 if(mRulerY->IsEnabled())
2259 position.y = -WrapInDomain(-position.y, rulerDomainY.min, rulerDomainY.max);
2264 void ScrollView::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value)
2266 Toolkit::ScrollView scrollView = Toolkit::ScrollView::DownCast(Dali::BaseHandle(object));
2270 ScrollView& scrollViewImpl(GetImpl(scrollView));
2273 case Toolkit::ScrollView::Property::WRAP_ENABLED:
2275 scrollViewImpl.SetWrapMode(value.Get<bool>());
2278 case Toolkit::ScrollView::Property::PANNING_ENABLED:
2280 scrollViewImpl.SetScrollSensitive(value.Get<bool>());
2283 case Toolkit::ScrollView::Property::AXIS_AUTO_LOCK_ENABLED:
2285 scrollViewImpl.SetAxisAutoLock(value.Get<bool>());
2288 case Toolkit::ScrollView::Property::WHEEL_SCROLL_DISTANCE_STEP:
2290 scrollViewImpl.SetWheelScrollDistanceStep(value.Get<Vector2>());
2293 case Toolkit::ScrollView::Property::SCROLL_MODE:
2295 const Property::Map* map = value.GetMap();
2298 scrollViewImpl.SetScrollMode(*map);
2305 Property::Value ScrollView::GetProperty(BaseObject* object, Property::Index index)
2307 Property::Value value;
2309 Toolkit::ScrollView scrollView = Toolkit::ScrollView::DownCast(Dali::BaseHandle(object));
2313 ScrollView& scrollViewImpl(GetImpl(scrollView));
2316 case Toolkit::ScrollView::Property::WRAP_ENABLED:
2318 value = scrollViewImpl.GetWrapMode();
2321 case Toolkit::ScrollView::Property::PANNING_ENABLED:
2323 value = scrollViewImpl.GetScrollSensitive();
2326 case Toolkit::ScrollView::Property::AXIS_AUTO_LOCK_ENABLED:
2328 value = scrollViewImpl.GetAxisAutoLock();
2331 case Toolkit::ScrollView::Property::WHEEL_SCROLL_DISTANCE_STEP:
2333 value = scrollViewImpl.GetWheelScrollDistanceStep();
2342 void ScrollView::SetScrollMode(const Property::Map& scrollModeMap)
2344 Toolkit::RulerPtr rulerX, rulerY;
2346 // Check the scroll mode in the X axis
2347 bool xAxisScrollEnabled = true;
2348 Property::Value* valuePtr = scrollModeMap.Find(Toolkit::ScrollMode::X_AXIS_SCROLL_ENABLED, "xAxisScrollEnabled");
2349 if(valuePtr && valuePtr->GetType() == Property::BOOLEAN)
2351 valuePtr->Get(xAxisScrollEnabled);
2354 if(!xAxisScrollEnabled)
2356 // Default ruler and disabled
2357 rulerX = new Toolkit::DefaultRuler();
2362 valuePtr = scrollModeMap.Find(Toolkit::ScrollMode::X_AXIS_SNAP_TO_INTERVAL, "xAxisSnapToInterval");
2363 float xAxisSnapToInterval = 0.0f;
2364 if(valuePtr && valuePtr->Get(xAxisSnapToInterval))
2366 // Fixed ruler and enabled
2367 rulerX = new Toolkit::FixedRuler(xAxisSnapToInterval);
2371 // Default ruler and enabled
2372 rulerX = new Toolkit::DefaultRuler();
2375 valuePtr = scrollModeMap.Find(Toolkit::ScrollMode::X_AXIS_SCROLL_BOUNDARY, "xAxisScrollBoundary");
2376 float xAxisScrollBoundary = 0.0f;
2377 if(valuePtr && valuePtr->Get(xAxisScrollBoundary))
2379 // By default ruler domain is disabled unless set
2380 rulerX->SetDomain(Toolkit::RulerDomain(0, xAxisScrollBoundary, true));
2384 // Check the scroll mode in the Y axis
2385 bool yAxisScrollEnabled = true;
2386 valuePtr = scrollModeMap.Find(Toolkit::ScrollMode::Y_AXIS_SCROLL_ENABLED, "yAxisScrollEnabled");
2387 if(valuePtr && valuePtr->GetType() == Property::BOOLEAN)
2389 valuePtr->Get(yAxisScrollEnabled);
2392 if(!yAxisScrollEnabled)
2394 // Default ruler and disabled
2395 rulerY = new Toolkit::DefaultRuler();
2400 valuePtr = scrollModeMap.Find(Toolkit::ScrollMode::Y_AXIS_SNAP_TO_INTERVAL, "yAxisSnapToInterval");
2401 float yAxisSnapToInterval = 0.0f;
2402 if(valuePtr && valuePtr->Get(yAxisSnapToInterval))
2404 // Fixed ruler and enabled
2405 rulerY = new Toolkit::FixedRuler(yAxisSnapToInterval);
2409 // Default ruler and enabled
2410 rulerY = new Toolkit::DefaultRuler();
2413 valuePtr = scrollModeMap.Find(Toolkit::ScrollMode::Y_AXIS_SCROLL_BOUNDARY, "yAxisScrollBoundary");
2414 float yAxisScrollBoundary = 0.0f;
2415 if(valuePtr && valuePtr->Get(yAxisScrollBoundary))
2417 // By default ruler domain is disabled unless set
2418 rulerY->SetDomain(Toolkit::RulerDomain(0, yAxisScrollBoundary, true));
2426 ScrollView::LockAxis GetLockAxis(const Vector2& panDelta, ScrollView::LockAxis currentLockAxis, float lockGradient)
2428 if(panDelta.LengthSquared() > AUTOLOCK_AXIS_MINIMUM_DISTANCE2 &&
2429 currentLockAxis == ScrollView::LockPossible)
2431 float dx = fabsf(panDelta.x);
2432 float dy = fabsf(panDelta.y);
2433 if(dx * lockGradient >= dy)
2435 // 0.36:1 gradient to the horizontal (deviate < 20 degrees)
2436 currentLockAxis = ScrollView::LockVertical;
2438 else if(dy * lockGradient > dx)
2440 // 0.36:1 gradient to the vertical (deviate < 20 degrees)
2441 currentLockAxis = ScrollView::LockHorizontal;
2445 currentLockAxis = ScrollView::LockNone;
2448 return currentLockAxis;
2451 } // namespace Internal
2453 } // namespace Toolkit