2 * Copyright (c) 2020 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/item-view/item-view-impl.h>
22 #include <cstring> // for strcmp
24 #include <dali/public-api/actors/layer.h>
25 #include <dali/devel-api/actors/actor-devel.h>
26 #include <dali/public-api/animation/constraint.h>
27 #include <dali/public-api/animation/constraints.h>
28 #include <dali/devel-api/common/stage.h>
29 #include <dali/public-api/events/wheel-event.h>
30 #include <dali/public-api/events/touch-event.h>
31 #include <dali/public-api/object/type-registry.h>
32 #include <dali/public-api/object/type-registry-helper.h>
33 #include <dali/devel-api/object/property-helper-devel.h>
36 #include <dali-toolkit/devel-api/controls/scroll-bar/scroll-bar.h>
37 #include <dali-toolkit/public-api/controls/scrollable/item-view/item-factory.h>
38 #include <dali-toolkit/public-api/controls/scrollable/item-view/default-item-layout.h>
39 #include <dali-toolkit/public-api/controls/scrollable/item-view/default-item-layout-property.h>
40 #include <dali-toolkit/internal/controls/scrollable/item-view/grid-layout.h>
41 #include <dali-toolkit/internal/controls/scrollable/item-view/depth-layout.h>
42 #include <dali-toolkit/internal/controls/scrollable/item-view/spiral-layout.h>
43 #include <dali-toolkit/internal/controls/scrollable/bouncing-effect-actor.h>
48 namespace // Unnamed namespace
51 const float DEFAULT_MINIMUM_SWIPE_SPEED = 1.0f;
52 const float DEFAULT_MINIMUM_SWIPE_DISTANCE = 3.0f;
53 const float DEFAULT_WHEEL_SCROLL_DISTANCE_STEP_PROPORTION = 0.1f;
55 const float DEFAULT_MINIMUM_SWIPE_DURATION = 0.45f;
56 const float DEFAULT_MAXIMUM_SWIPE_DURATION = 2.6f;
58 const float DEFAULT_REFRESH_INTERVAL_LAYOUT_POSITIONS = 20.0f; // 1 updates per 20 items
59 const int WHEEL_EVENT_FINISHED_TIME_OUT = 500; // 0.5 second
61 const float DEFAULT_ANCHORING_DURATION = 1.0f; // 1 second
63 const float MILLISECONDS_PER_SECONDS = 1000.0f;
65 const float OVERSHOOT_BOUNCE_ACTOR_RESIZE_THRESHOLD = 180.0f;
66 const Vector4 OVERSHOOT_OVERLAY_NINE_PATCH_BORDER(0.0f, 0.0f, 1.0f, 12.0f);
67 const float DEFAULT_KEYBOARD_FOCUS_SCROLL_DURATION = 0.2f;
69 const unsigned int OVERSHOOT_SIZE_CONSTRAINT_TAG(42);
72 * Local helper to convert pan distance (in actor coordinates) to the layout-specific scrolling direction
74 float CalculateScrollDistance(Vector2 panDistance, Toolkit::ItemLayout& layout)
76 Radian scrollDirection(layout.GetScrollDirection());
78 float cosTheta = cosf(scrollDirection);
79 float sinTheta = sinf(scrollDirection);
81 return panDistance.x * sinTheta + panDistance.y * cosTheta;
84 // Overshoot overlay constraints
85 struct OvershootOverlaySizeConstraint
87 OvershootOverlaySizeConstraint( float height )
88 : mOvershootHeight( height )
92 void operator()( Vector3& current, const PropertyInputContainer& inputs )
94 const Vector2& parentScrollDirection = inputs[0]->GetVector2();
95 const Toolkit::ControlOrientation::Type& layoutOrientation = static_cast<Toolkit::ControlOrientation::Type>(inputs[1]->GetInteger());
96 const Vector3& parentSize = inputs[2]->GetVector3();
98 if(Toolkit::IsVertical(layoutOrientation))
100 current.width = fabsf(parentScrollDirection.y) > Math::MACHINE_EPSILON_1 ? parentSize.x : parentSize.y;
104 current.width = fabsf(parentScrollDirection.x) > Math::MACHINE_EPSILON_1 ? parentSize.y : parentSize.x;
107 current.height = ( current.width > OVERSHOOT_BOUNCE_ACTOR_RESIZE_THRESHOLD ) ? mOvershootHeight : mOvershootHeight*0.5f;
110 float mOvershootHeight;
113 void OvershootOverlayRotationConstraint( Quaternion& current, const PropertyInputContainer& inputs )
115 const Vector2& parentScrollDirection = inputs[0]->GetVector2();
116 const Toolkit::ControlOrientation::Type& layoutOrientation = static_cast<Toolkit::ControlOrientation::Type>(inputs[1]->GetInteger());
117 const float parentOvershoot = inputs[2]->GetFloat();
119 float multiplier = 0;
120 if(Toolkit::IsVertical(layoutOrientation))
122 if(fabsf(parentScrollDirection.y) <= Math::MACHINE_EPSILON_1)
124 if( (layoutOrientation == Toolkit::ControlOrientation::Up && parentOvershoot < Math::MACHINE_EPSILON_0)
125 || (layoutOrientation == Toolkit::ControlOrientation::Down && parentOvershoot > Math::MACHINE_EPSILON_0) )
134 else if( (parentOvershoot > Math::MACHINE_EPSILON_0 && parentScrollDirection.y > Math::MACHINE_EPSILON_0)
135 || (parentOvershoot < Math::MACHINE_EPSILON_0 && parentScrollDirection.y < Math::MACHINE_EPSILON_0) )
146 if(fabsf(parentScrollDirection.x) <= Math::MACHINE_EPSILON_1)
148 if( (layoutOrientation == Toolkit::ControlOrientation::Left && parentOvershoot > Math::MACHINE_EPSILON_0)
149 ||(layoutOrientation == Toolkit::ControlOrientation::Right && parentOvershoot < Math::MACHINE_EPSILON_0) )
158 else if( (parentOvershoot > Math::MACHINE_EPSILON_0 && parentScrollDirection.x > Math::MACHINE_EPSILON_0)
159 || (parentOvershoot < Math::MACHINE_EPSILON_0 && parentScrollDirection.x < Math::MACHINE_EPSILON_0) )
169 current = Quaternion( Radian( multiplier * Math::PI ), Vector3::ZAXIS );
172 void OvershootOverlayPositionConstraint( Vector3& current, const PropertyInputContainer& inputs )
174 const Vector3& parentSize = inputs[0]->GetVector3();
175 const Vector2& parentScrollDirection = inputs[1]->GetVector2();
176 const Toolkit::ControlOrientation::Type& layoutOrientation = static_cast<Toolkit::ControlOrientation::Type>(inputs[2]->GetInteger());
177 const float parentOvershoot = inputs[3]->GetFloat();
179 Vector3 relativeOffset;
181 if(Toolkit::IsVertical(layoutOrientation))
183 if(fabsf(parentScrollDirection.y) <= Math::MACHINE_EPSILON_1)
185 if( (layoutOrientation == Toolkit::ControlOrientation::Up && parentOvershoot < Math::MACHINE_EPSILON_0)
186 || (layoutOrientation == Toolkit::ControlOrientation::Down && parentOvershoot > Math::MACHINE_EPSILON_0) )
188 relativeOffset = Vector3(1.0f, 0.0f, 0.0f);
192 relativeOffset =Vector3(0.0f, 1.0f, 0.0f);
195 else if( (parentOvershoot > Math::MACHINE_EPSILON_0 && parentScrollDirection.y > Math::MACHINE_EPSILON_0)
196 || (parentOvershoot < Math::MACHINE_EPSILON_0 && parentScrollDirection.y < Math::MACHINE_EPSILON_0) )
198 relativeOffset = Vector3(0.0f, 0.0f, 0.0f);
202 relativeOffset = Vector3(1.0f, 1.0f, 0.0f);
207 if(fabsf(parentScrollDirection.x) <= Math::MACHINE_EPSILON_1)
209 if( (layoutOrientation == Toolkit::ControlOrientation::Left && parentOvershoot < Math::MACHINE_EPSILON_0)
210 || (layoutOrientation == Toolkit::ControlOrientation::Right && parentOvershoot > Math::MACHINE_EPSILON_0) )
212 relativeOffset = Vector3(0.0f, 0.0f, 0.0f);
216 relativeOffset = Vector3(1.0f, 1.0f, 0.0f);
219 else if( (parentOvershoot > Math::MACHINE_EPSILON_0 && parentScrollDirection.x > Math::MACHINE_EPSILON_0)
220 || (parentOvershoot < Math::MACHINE_EPSILON_0 && parentScrollDirection.x < Math::MACHINE_EPSILON_0) )
222 relativeOffset = Vector3(0.0f, 1.0f, 0.0f);
226 relativeOffset = Vector3(1.0f, 0.0f, 0.0f);
230 current = relativeOffset * parentSize;
233 void OvershootOverlayVisibilityConstraint( bool& current, const PropertyInputContainer& inputs )
235 current = inputs[0]->GetBoolean();
238 } // unnamed namespace
249 namespace // unnamed namespace
254 DALI_TYPE_REGISTRATION_BEGIN( Toolkit::ItemView, Toolkit::Scrollable, NULL)
256 DALI_PROPERTY_REGISTRATION( Toolkit, ItemView, "minimumSwipeSpeed", FLOAT, MINIMUM_SWIPE_SPEED )
257 DALI_PROPERTY_REGISTRATION( Toolkit, ItemView, "minimumSwipeDistance", FLOAT, MINIMUM_SWIPE_DISTANCE )
258 DALI_PROPERTY_REGISTRATION( Toolkit, ItemView, "wheelScrollDistanceStep", FLOAT, WHEEL_SCROLL_DISTANCE_STEP )
259 DALI_PROPERTY_REGISTRATION( Toolkit, ItemView, "snapToItemEnabled", BOOLEAN, SNAP_TO_ITEM_ENABLED )
260 DALI_PROPERTY_REGISTRATION( Toolkit, ItemView, "refreshInterval", FLOAT, REFRESH_INTERVAL )
261 DALI_PROPERTY_REGISTRATION( Toolkit, ItemView, "layout", ARRAY, LAYOUT )
264 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "layoutPosition", FLOAT, LAYOUT_POSITION)
265 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "scrollSpeed", FLOAT, SCROLL_SPEED)
266 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "overshoot", FLOAT, OVERSHOOT)
267 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "scrollDirection", VECTOR2, SCROLL_DIRECTION)
268 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "layoutOrientation", INTEGER, LAYOUT_ORIENTATION)
269 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "scrollContentSize", FLOAT, SCROLL_CONTENT_SIZE)
271 DALI_SIGNAL_REGISTRATION( Toolkit, ItemView, "layoutActivated", LAYOUT_ACTIVATED_SIGNAL )
273 DALI_ACTION_REGISTRATION( Toolkit, ItemView, "stopScrolling", ACTION_STOP_SCROLLING )
275 DALI_ACTION_REGISTRATION( Toolkit, ItemView, "enableRefresh", ACTION_ENABLE_REFRESH )
276 DALI_ACTION_REGISTRATION( Toolkit, ItemView, "disableRefresh", ACTION_DISABLE_REFRESH )
278 DALI_TYPE_REGISTRATION_END()
280 const ItemIter FindItemById( ItemContainer& items, ItemId id )
282 for( ItemIter iter = items.begin(); items.end() != iter; ++iter )
284 if( iter->first == id )
293 void InsertToItemContainer( ItemContainer& items, Item item )
295 if( items.end() == FindItemById( items, item.first ) )
297 ItemIter iterToInsert = std::lower_bound( items.begin(), items.end(), item );
298 items.insert( iterToInsert, item );
304 * Helper to apply size constraint to mOvershootOverlay
305 * @param[in] overshootOverlay The overshootOverlay actor
306 * @param[in] The required height
308 void ApplyOvershootSizeConstraint( Actor overshootOverlay, float height )
310 Constraint constraint = Constraint::New<Vector3>( overshootOverlay, Actor::Property::SIZE, OvershootOverlaySizeConstraint( height ) );
311 constraint.AddSource( ParentSource( Dali::Toolkit::ItemView::Property::SCROLL_DIRECTION ) );
312 constraint.AddSource( ParentSource( Dali::Toolkit::ItemView::Property::LAYOUT_ORIENTATION ) );
313 constraint.AddSource( ParentSource( Dali::Actor::Property::SIZE ) );
314 constraint.SetTag( OVERSHOOT_SIZE_CONSTRAINT_TAG );
318 } // unnamed namespace
320 Dali::Toolkit::ItemView ItemView::New(ItemFactory& factory)
322 // Create the implementation
323 ItemViewPtr itemView(new ItemView(factory));
325 // Pass ownership to CustomActor via derived handle
326 Dali::Toolkit::ItemView handle(*itemView);
328 // Second-phase init of the implementation
329 // This can only be done after the CustomActor connection has been made...
330 itemView->Initialize();
335 ItemView::ItemView(ItemFactory& factory)
336 : Scrollable( ControlBehaviour( DISABLE_SIZE_NEGOTIATION | DISABLE_STYLE_CHANGE_SIGNALS | REQUIRES_KEYBOARD_NAVIGATION_SUPPORT ) ),
337 mItemFactory(factory),
338 mItemsParentOrigin(ParentOrigin::CENTER),
339 mItemsAnchorPoint(AnchorPoint::CENTER),
340 mTotalPanDisplacement(Vector2::ZERO),
342 mAnchoringDuration(DEFAULT_ANCHORING_DURATION),
343 mRefreshIntervalLayoutPositions(0.0f),
344 mMinimumSwipeSpeed(DEFAULT_MINIMUM_SWIPE_SPEED),
345 mMinimumSwipeDistance(DEFAULT_MINIMUM_SWIPE_DISTANCE),
346 mWheelScrollDistanceStep(0.0f),
347 mScrollDistance(0.0f),
349 mScrollOvershoot(0.0f),
350 mGestureState(GestureState::CLEAR),
351 mAnimatingOvershootOn(false),
352 mAnimateOvershootOff(false),
353 mAnchoringEnabled(false),
354 mRefreshOrderHint(true/*Refresh item 0 first*/),
357 mRefreshEnabled(true),
358 mRefreshNotificationEnabled(true),
363 void ItemView::OnInitialize()
365 Scrollable::OnInitialize();
369 Vector2 stageSize = Stage::GetCurrent().GetSize();
370 mWheelScrollDistanceStep = stageSize.y * DEFAULT_WHEEL_SCROLL_DISTANCE_STEP_PROPORTION;
372 self.TouchedSignal().Connect( this, &ItemView::OnTouch );
373 EnableGestureDetection(GestureType::Value(GestureType::PAN));
375 mWheelEventFinishedTimer = Timer::New( WHEEL_EVENT_FINISHED_TIME_OUT );
376 mWheelEventFinishedTimer.TickSignal().Connect( this, &ItemView::OnWheelEventFinished );
378 SetRefreshInterval(DEFAULT_REFRESH_INTERVAL_LAYOUT_POSITIONS);
380 // Connect wheel event
381 self.WheelEventSignal().Connect( this, &ItemView::OnWheelEvent );
383 DevelControl::SetAccessibilityConstructor(self, [](Dali::Actor actor)
385 return std::unique_ptr<Dali::Accessibility::Accessible>(new AccessibleImpl(actor, Dali::Accessibility::Role::SCROLL_PANE));
389 ItemView::~ItemView()
393 unsigned int ItemView::GetLayoutCount() const
395 return mLayouts.size();
398 void ItemView::AddLayout(ItemLayout& layout)
400 mLayouts.push_back(ItemLayoutPtr(&layout));
403 void ItemView::RemoveLayout(unsigned int layoutIndex)
405 DALI_ASSERT_ALWAYS(layoutIndex < mLayouts.size());
407 if (mActiveLayout == mLayouts[layoutIndex].Get())
409 mActiveLayout = NULL;
412 mLayouts.erase(mLayouts.begin() + layoutIndex);
415 ItemLayoutPtr ItemView::GetLayout(unsigned int layoutIndex) const
417 return mLayouts[layoutIndex];
420 ItemLayoutPtr ItemView::GetActiveLayout() const
422 return ItemLayoutPtr(mActiveLayout);
425 float ItemView::GetCurrentLayoutPosition(unsigned int itemId) const
427 return Self().GetCurrentProperty< float >( Toolkit::ItemView::Property::LAYOUT_POSITION ) + static_cast<float>( itemId );
430 void ItemView::ActivateLayout(unsigned int layoutIndex, const Vector3& targetSize, float durationSeconds)
432 DALI_ASSERT_ALWAYS(layoutIndex < mLayouts.size());
434 mRefreshEnabled = false;
438 // The ItemView size should match the active layout size
439 self.SetProperty( Actor::Property::SIZE, targetSize);
440 mActiveLayoutTargetSize = targetSize;
442 // Switch to the new layout
443 mActiveLayout = mLayouts[layoutIndex].Get();
445 // Move the items to the new layout positions...
447 for (ConstItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
449 unsigned int itemId = iter->first;
450 Actor actor = iter->second;
452 // Remove constraints from previous layout
453 actor.RemoveConstraints();
455 mActiveLayout->ApplyConstraints(actor, itemId, targetSize, Self() );
458 mActiveLayout->GetItemSize( itemId, targetSize, size );
459 actor.SetProperty( Actor::Property::SIZE, size.GetVectorXY() );
462 // Refresh the new layout
463 ItemRange range = GetItemRange(*mActiveLayout, targetSize, GetCurrentLayoutPosition(0), false/* don't reserve extra*/);
464 AddActorsWithinRange( range, targetSize );
466 // Scroll to an appropriate layout position
468 bool scrollAnimationNeeded(false);
469 float firstItemScrollPosition(0.0f);
471 float current = GetCurrentLayoutPosition(0);
472 float minimum = ClampFirstItemPosition(current, targetSize, *mActiveLayout);
474 if (current < minimum)
476 scrollAnimationNeeded = true;
477 firstItemScrollPosition = minimum;
479 else if (mAnchoringEnabled)
481 scrollAnimationNeeded = true;
482 firstItemScrollPosition = mActiveLayout->GetClosestAnchorPosition(current);
485 if (scrollAnimationNeeded)
487 RemoveAnimation(mScrollAnimation);
488 mScrollAnimation = Animation::New(durationSeconds);
489 mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), firstItemScrollPosition, AlphaFunction::EASE_OUT );
490 mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnLayoutActivationScrollFinished);
491 mScrollAnimation.Play();
495 // Emit the layout activated signal
496 mLayoutActivatedSignal.Emit();
499 AnimateScrollOvershoot(0.0f);
500 mScrollOvershoot = 0.0f;
502 Radian scrollDirection(mActiveLayout->GetScrollDirection());
503 self.SetProperty(Toolkit::ItemView::Property::SCROLL_DIRECTION, Vector2(sinf(scrollDirection), cosf(scrollDirection)));
504 self.SetProperty(Toolkit::ItemView::Property::LAYOUT_ORIENTATION, static_cast<int>(mActiveLayout->GetOrientation()));
505 self.SetProperty(Toolkit::ItemView::Property::SCROLL_SPEED, mScrollSpeed);
507 CalculateDomainSize(targetSize);
510 void ItemView::DeactivateCurrentLayout()
514 for (ConstItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
516 Actor actor = iter->second;
517 actor.RemoveConstraints();
520 mActiveLayout = NULL;
524 void ItemView::OnRefreshNotification(PropertyNotification& source)
526 if( mRefreshNotificationEnabled )
528 // Cancel scroll animation to prevent any fighting of setting the scroll position property by scroll bar during fast scroll.
529 if(!mRefreshEnabled && mScrollAnimation)
531 RemoveAnimation(mScrollAnimation);
534 // Only cache extra items when it is not a fast scroll
535 DoRefresh(GetCurrentLayoutPosition(0), mRefreshEnabled || mScrollAnimation);
539 void ItemView::Refresh()
541 for (ConstItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter )
543 ReleaseActor( iter->first, iter->second );
547 DoRefresh(GetCurrentLayoutPosition(0), true);
550 void ItemView::DoRefresh(float currentLayoutPosition, bool cacheExtra)
554 ItemRange range = GetItemRange(*mActiveLayout, mActiveLayoutTargetSize, currentLayoutPosition, cacheExtra/*reserve extra*/);
555 RemoveActorsOutsideRange( range );
556 AddActorsWithinRange( range, Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ) );
558 mScrollUpdatedSignal.Emit( Vector2(0.0f, currentLayoutPosition) );
562 void ItemView::SetMinimumSwipeSpeed(float speed)
564 mMinimumSwipeSpeed = speed;
567 float ItemView::GetMinimumSwipeSpeed() const
569 return mMinimumSwipeSpeed;
572 void ItemView::SetMinimumSwipeDistance(float distance)
574 mMinimumSwipeDistance = distance;
577 float ItemView::GetMinimumSwipeDistance() const
579 return mMinimumSwipeDistance;
582 void ItemView::SetWheelScrollDistanceStep(float step)
584 mWheelScrollDistanceStep = step;
587 float ItemView::GetWheelScrollDistanceStep() const
589 return mWheelScrollDistanceStep;
592 void ItemView::SetAnchoring(bool enabled)
594 mAnchoringEnabled = enabled;
597 bool ItemView::GetAnchoring() const
599 return mAnchoringEnabled;
602 void ItemView::SetAnchoringDuration(float durationSeconds)
604 mAnchoringDuration = durationSeconds;
607 float ItemView::GetAnchoringDuration() const
609 return mAnchoringDuration;
612 void ItemView::SetRefreshInterval(float intervalLayoutPositions)
614 if( !Equals(mRefreshIntervalLayoutPositions, intervalLayoutPositions) )
616 mRefreshIntervalLayoutPositions = intervalLayoutPositions;
619 if(mRefreshNotification)
621 self.RemovePropertyNotification(mRefreshNotification);
623 mRefreshNotification = self.AddPropertyNotification( Toolkit::ItemView::Property::LAYOUT_POSITION, StepCondition(mRefreshIntervalLayoutPositions, 0.0f) );
624 mRefreshNotification.NotifySignal().Connect( this, &ItemView::OnRefreshNotification );
628 float ItemView::GetRefreshInterval() const
630 return mRefreshIntervalLayoutPositions;
633 void ItemView::SetRefreshEnabled(bool enabled)
635 mRefreshEnabled = enabled;
638 Actor ItemView::GetItem(unsigned int itemId) const
642 for ( ConstItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter )
644 if( iter->first == itemId )
646 actor = iter->second;
654 unsigned int ItemView::GetItemId( Actor actor ) const
656 unsigned int itemId( 0 );
658 for ( ConstItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter )
660 if( iter->second == actor )
662 itemId = iter->first;
670 void ItemView::InsertItem( Item newItem, float durationSeconds )
673 Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
675 Actor displacedActor;
676 ItemIter afterDisplacedIter = mItemPool.end();
678 ItemIter foundIter = FindItemById( mItemPool, newItem.first );
679 if( mItemPool.end() != foundIter )
681 SetupActor( newItem, layoutSize );
682 Self().Add( newItem.second );
684 displacedActor = foundIter->second;
685 foundIter->second = newItem.second;
687 afterDisplacedIter = ++foundIter;
691 // Inserting before the existing item range?
692 ItemIter iter = mItemPool.begin();
693 if( iter != mItemPool.end() &&
694 iter->first > newItem.first )
696 displacedActor = iter->second;
697 iter = mItemPool.erase( iter ); // iter is still valid after the erase
699 afterDisplacedIter = iter;
705 // Move the existing actors to make room
706 for( ItemIter iter = afterDisplacedIter; mItemPool.end() != iter; ++iter )
708 Actor temp = iter->second;
709 iter->second = displacedActor;
710 displacedActor = temp;
712 iter->second.RemoveConstraints();
713 mActiveLayout->ApplyConstraints( iter->second, iter->first, layoutSize, Self() );
717 ItemContainer::reverse_iterator lastIter = mItemPool.rbegin();
718 if ( lastIter != mItemPool.rend() )
720 ItemId lastId = lastIter->first;
721 Item lastItem( lastId + 1, displacedActor );
722 InsertToItemContainer( mItemPool, lastItem );
724 lastItem.second.RemoveConstraints();
725 mActiveLayout->ApplyConstraints( lastItem.second, lastItem.first, layoutSize, Self() );
729 CalculateDomainSize( layoutSize );
731 mAddingItems = false;
734 void ItemView::InsertItems( const ItemContainer& newItems, float durationSeconds )
737 Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
739 // Insert from lowest id to highest
740 ItemContainer sortedItems(newItems);
741 std::sort( sortedItems.begin(), sortedItems.end() );
743 for( ItemIter iter = sortedItems.begin(); sortedItems.end() != iter; ++iter )
745 Self().Add( iter->second );
747 ItemIter foundIter = FindItemById( mItemPool, iter->first );
748 if( mItemPool.end() != foundIter )
750 Actor moveMe = foundIter->second;
751 foundIter->second = iter->second;
753 // Move the existing actors to make room
754 for( ItemIter iter = ++foundIter; mItemPool.end() != iter; ++iter )
756 Actor temp = iter->second;
757 iter->second = moveMe;
762 ItemId lastId = mItemPool.rbegin()->first;
763 Item lastItem( lastId + 1, moveMe );
764 InsertToItemContainer( mItemPool, lastItem );
768 InsertToItemContainer( mItemPool, *iter );
772 // Relayout everything
773 for (ItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
776 if( std::binary_search( sortedItems.begin(), sortedItems.end(), *iter ) )
778 SetupActor( *iter, layoutSize );
782 iter->second.RemoveConstraints();
783 mActiveLayout->ApplyConstraints( iter->second, iter->first, layoutSize, Self() );
787 CalculateDomainSize( layoutSize );
789 mAddingItems = false;
792 void ItemView::RemoveItem( unsigned int itemId, float durationSeconds )
794 bool actorsReordered = RemoveActor( itemId );
795 if( actorsReordered )
797 ReapplyAllConstraints();
803 void ItemView::RemoveItems( const ItemIdContainer& itemIds, float durationSeconds )
805 bool actorsReordered( false );
807 // Remove from highest id to lowest
808 ItemIdContainer sortedItems(itemIds);
809 std::sort( sortedItems.begin(), sortedItems.end() );
811 for( ItemIdContainer::reverse_iterator iter = sortedItems.rbegin(); sortedItems.rend() != iter; ++iter )
813 if( RemoveActor( *iter ) )
815 actorsReordered = true;
819 if( actorsReordered )
821 ReapplyAllConstraints();
827 bool ItemView::RemoveActor(unsigned int itemId)
829 bool reordered( false );
831 ItemIter removeIter = FindItemById( mItemPool, itemId );
832 if( removeIter != mItemPool.end() )
834 ReleaseActor(itemId, removeIter->second);
838 // Removing before the existing item range?
839 ItemIter iter = mItemPool.begin();
840 if( iter != mItemPool.end() &&
841 iter->first > itemId )
843 // In order to decrement the first visible item ID
844 InsertToItemContainer( mItemPool, Item(iter->first - 1, Actor()) );
846 removeIter = mItemPool.begin();
850 if( removeIter != mItemPool.end() )
854 // Adjust the remaining item IDs, for example if item 2 is removed:
855 // Initial actors: After insert:
856 // ID 1 - ActorA ID 1 - ActorA
857 // ID 2 - ActorB ID 2 - ActorC (previously ID 3)
858 // ID 3 - ActorC ID 3 - ActorB (previously ID 4)
860 for (ItemIter iter = removeIter; iter != mItemPool.end(); ++iter)
862 if( iter->first < mItemPool.rbegin()->first )
864 iter->second = ( iter + 1 )->second;
868 mItemPool.erase( iter );
877 void ItemView::ReplaceItem( Item replacementItem, float durationSeconds )
880 Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
882 SetupActor( replacementItem, layoutSize );
883 Self().Add( replacementItem.second );
885 const ItemIter iter = FindItemById( mItemPool, replacementItem.first );
886 if( mItemPool.end() != iter )
888 ReleaseActor(iter->first, iter->second);
889 iter->second = replacementItem.second;
893 InsertToItemContainer( mItemPool, replacementItem );
896 CalculateDomainSize( layoutSize );
898 mAddingItems = false;
901 void ItemView::ReplaceItems( const ItemContainer& replacementItems, float durationSeconds )
903 for( ConstItemIter iter = replacementItems.begin(); replacementItems.end() != iter; ++iter )
905 ReplaceItem( *iter, durationSeconds );
909 void ItemView::RemoveActorsOutsideRange( ItemRange range )
911 // Remove unwanted actors from the ItemView & ItemPool
912 for (ItemIter iter = mItemPool.begin(); iter != mItemPool.end(); )
914 unsigned int current = iter->first;
916 if( ! range.Within( current ) )
918 ReleaseActor(iter->first, iter->second);
920 iter = mItemPool.erase( iter ); // iter is still valid after the erase
929 void ItemView::AddActorsWithinRange( ItemRange range, const Vector3& layoutSize )
931 range.end = std::min(mItemFactory.GetNumberOfItems(), range.end);
933 // The order of addition depends on the scroll direction.
934 if (mRefreshOrderHint)
936 for (unsigned int itemId = range.begin; itemId < range.end; ++itemId)
938 AddNewActor( itemId, layoutSize );
943 for (unsigned int itemId = range.end; itemId > range.begin; --itemId)
945 AddNewActor( itemId-1, layoutSize );
949 // Total number of items may change dynamically.
950 // Always recalculate the domain size to reflect that.
951 CalculateDomainSize(Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ));
954 void ItemView::AddNewActor( unsigned int itemId, const Vector3& layoutSize )
958 if( mItemPool.end() == FindItemById( mItemPool, itemId ) )
960 Actor actor = mItemFactory.NewItem( itemId );
964 Item newItem( itemId, actor );
966 InsertToItemContainer( mItemPool, newItem );
968 SetupActor( newItem, layoutSize );
973 mAddingItems = false;
976 void ItemView::SetupActor( Item item, const Vector3& layoutSize )
978 item.second.SetProperty( Actor::Property::PARENT_ORIGIN, mItemsParentOrigin );
979 item.second.SetProperty( Actor::Property::ANCHOR_POINT, mItemsAnchorPoint );
984 mActiveLayout->GetItemSize( item.first, mActiveLayoutTargetSize, size );
985 item.second.SetProperty( Actor::Property::SIZE, size.GetVectorXY() );
987 mActiveLayout->ApplyConstraints( item.second, item.first, layoutSize, Self() );
991 void ItemView::ReleaseActor( ItemId item, Actor actor )
993 Self().Remove( actor );
994 mItemFactory.ItemReleased(item, actor);
997 ItemRange ItemView::GetItemRange(ItemLayout& layout, const Vector3& layoutSize, float layoutPosition, bool reserveExtra)
999 unsigned int itemCount = mItemFactory.GetNumberOfItems();
1001 ItemRange available(0u, itemCount);
1003 ItemRange range = layout.GetItemsWithinArea( layoutPosition, layoutSize );
1007 // Add the reserve items for scrolling
1008 unsigned int extra = layout.GetReserveItemCount(layoutSize);
1009 range.begin = (range.begin >= extra) ? (range.begin - extra) : 0u;
1013 return range.Intersection(available);
1016 void ItemView::OnChildAdd(Actor& child)
1020 // We don't want to do this downcast check for any item added by ItemView itself.
1021 Dali::Toolkit::ScrollBar scrollBar = Dali::Toolkit::ScrollBar::DownCast(child);
1024 scrollBar.SetScrollPropertySource(Self(),
1025 Toolkit::ItemView::Property::LAYOUT_POSITION,
1026 Toolkit::Scrollable::Property::SCROLL_POSITION_MIN_Y,
1027 Toolkit::Scrollable::Property::SCROLL_POSITION_MAX_Y,
1028 Toolkit::ItemView::Property::SCROLL_CONTENT_SIZE);
1032 Scrollable::OnChildAdd( child );
1035 bool ItemView::OnWheelEvent(Actor actor, const WheelEvent& event)
1037 // Respond the wheel event to scroll
1040 Actor self = Self();
1041 const Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
1042 float layoutPositionDelta = GetCurrentLayoutPosition(0) - (event.GetDelta() * mWheelScrollDistanceStep * mActiveLayout->GetScrollSpeedFactor());
1043 float firstItemScrollPosition = ClampFirstItemPosition(layoutPositionDelta, layoutSize, *mActiveLayout);
1045 self.SetProperty(Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1047 mScrollStartedSignal.Emit(GetCurrentScrollPosition());
1048 mRefreshEnabled = true;
1051 if (mWheelEventFinishedTimer.IsRunning())
1053 mWheelEventFinishedTimer.Stop();
1056 mWheelEventFinishedTimer.Start();
1061 bool ItemView::OnWheelEventFinished()
1065 RemoveAnimation(mScrollAnimation);
1067 // No more wheel events coming. Do the anchoring if enabled.
1068 mScrollAnimation = DoAnchoring();
1069 if (mScrollAnimation)
1071 mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
1072 mScrollAnimation.Play();
1076 mScrollOvershoot = 0.0f;
1077 AnimateScrollOvershoot(0.0f);
1079 mScrollCompletedSignal.Emit(GetCurrentScrollPosition());
1086 void ItemView::ReapplyAllConstraints()
1088 Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
1090 for (ConstItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
1092 unsigned int id = iter->first;
1093 Actor actor = iter->second;
1095 actor.RemoveConstraints();
1096 mActiveLayout->ApplyConstraints(actor, id, layoutSize, Self());
1100 void ItemView::OnItemsRemoved()
1102 CalculateDomainSize(Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ));
1104 // Adjust scroll-position after an item is removed
1107 float firstItemScrollPosition = ClampFirstItemPosition(GetCurrentLayoutPosition(0), Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ), *mActiveLayout);
1108 Self().SetProperty( Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1112 float ItemView::ClampFirstItemPosition( float targetPosition, const Vector3& targetSize, ItemLayout& layout, bool updateOvershoot )
1114 Actor self = Self();
1115 float minLayoutPosition = layout.GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), targetSize);
1116 float clamppedPosition = std::min(0.0f, std::max(minLayoutPosition, targetPosition));
1117 self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX, Vector2(0.0f, -minLayoutPosition));
1119 if( updateOvershoot )
1121 mScrollOvershoot = targetPosition - clamppedPosition;
1124 return clamppedPosition;
1127 bool ItemView::OnTouch( Actor actor, const TouchEvent& touch )
1129 // Ignore events with multiple-touch points
1130 if (touch.GetPointCount() != 1)
1135 if ( touch.GetState( 0 ) == PointState::DOWN )
1137 // Cancel ongoing scrolling etc.
1138 mGestureState = GestureState::CLEAR;
1140 mScrollDistance = 0.0f;
1141 mScrollSpeed = 0.0f;
1142 Self().SetProperty(Toolkit::ItemView::Property::SCROLL_SPEED, mScrollSpeed);
1144 mScrollOvershoot = 0.0f;
1145 AnimateScrollOvershoot(0.0f);
1147 if(mScrollAnimation)
1149 mScrollCompletedSignal.Emit(GetCurrentScrollPosition());
1152 RemoveAnimation(mScrollAnimation);
1155 return false; // Do not consume as we're potentially scrolling (detecting pan gestures)
1158 void ItemView::OnPan( const PanGesture& gesture )
1160 Actor self = Self();
1161 const Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
1163 RemoveAnimation(mScrollAnimation);
1165 // Short-circuit if there is no active layout
1168 mGestureState = GestureState::CLEAR;
1172 mGestureState = gesture.GetState();
1174 switch (mGestureState)
1176 case GestureState::FINISHED:
1179 if (fabsf(mScrollDistance) > mMinimumSwipeDistance &&
1180 mScrollSpeed > mMinimumSwipeSpeed)
1182 float direction = (mScrollDistance < 0.0f) ? -1.0f : 1.0f;
1184 mRefreshOrderHint = true;
1186 float currentLayoutPosition = GetCurrentLayoutPosition(0);
1187 float firstItemScrollPosition = ClampFirstItemPosition(currentLayoutPosition + mScrollSpeed * direction,
1191 if (mAnchoringEnabled)
1193 firstItemScrollPosition = mActiveLayout->GetClosestAnchorPosition(firstItemScrollPosition);
1196 RemoveAnimation(mScrollAnimation);
1198 float flickAnimationDuration = Clamp( mActiveLayout->GetItemFlickAnimationDuration() * std::max(1.0f, fabsf(firstItemScrollPosition - GetCurrentLayoutPosition(0)))
1199 , DEFAULT_MINIMUM_SWIPE_DURATION, DEFAULT_MAXIMUM_SWIPE_DURATION);
1201 mScrollAnimation = Animation::New(flickAnimationDuration);
1202 mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION ), firstItemScrollPosition, AlphaFunction::EASE_OUT );
1203 mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::SCROLL_SPEED), 0.0f, AlphaFunction::EASE_OUT );
1207 // Check whether it has already scrolled to the end
1208 if( fabs(currentLayoutPosition - firstItemScrollPosition) < Math::MACHINE_EPSILON_0 )
1210 AnimateScrollOvershoot( 0.0f );
1211 RemoveAnimation( mScrollAnimation );
1215 // Anchoring may be triggered when there was no swipe
1216 if (!mScrollAnimation)
1218 mScrollAnimation = DoAnchoring();
1221 // Reset the overshoot if no scroll animation.
1222 if (!mScrollAnimation)
1224 mScrollCompletedSignal.Emit(GetCurrentScrollPosition());
1226 AnimateScrollOvershoot(0.0f, false);
1231 case GestureState::STARTED: // Fall through
1233 mTotalPanDisplacement = Vector2::ZERO;
1234 mScrollStartedSignal.Emit(GetCurrentScrollPosition());
1235 mRefreshEnabled = true;
1238 case GestureState::CONTINUING:
1240 const Vector2& displacement = gesture.GetDisplacement();
1241 mScrollDistance = CalculateScrollDistance(displacement, *mActiveLayout);
1242 mScrollSpeed = Clamp((gesture.GetSpeed() * gesture.GetSpeed() * mActiveLayout->GetFlickSpeedFactor() * MILLISECONDS_PER_SECONDS), 0.0f, mActiveLayout->GetMaximumSwipeSpeed());
1244 // Refresh order depends on the direction of the scroll; negative is towards the last item.
1245 mRefreshOrderHint = mScrollDistance < 0.0f;
1247 float layoutPositionDelta = GetCurrentLayoutPosition(0) + (mScrollDistance * mActiveLayout->GetScrollSpeedFactor());
1249 float firstItemScrollPosition = ClampFirstItemPosition(layoutPositionDelta, layoutSize, *mActiveLayout);
1251 float currentOvershoot = self.GetCurrentProperty< float >( Toolkit::ItemView::Property::OVERSHOOT );
1253 self.SetProperty(Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1255 if( ( firstItemScrollPosition >= 0.0f &&
1256 currentOvershoot < 1.0f ) ||
1257 ( firstItemScrollPosition <= mActiveLayout->GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), layoutSize) &&
1258 currentOvershoot > -1.0f ) )
1260 mTotalPanDisplacement += displacement;
1263 mScrollOvershoot = CalculateScrollOvershoot();
1265 // If the view is moved in a direction against the overshoot indicator, then the indicator should be animated off.
1266 // First make sure we are not in an animation, otherwise a previously started
1267 // off-animation will be overwritten as the user continues scrolling.
1270 // Check if the movement is against the current overshoot amount (if we are currently displaying the indicator).
1271 if( ( ( mScrollOvershoot > Math::MACHINE_EPSILON_0 ) && ( mScrollDistance < -Math::MACHINE_EPSILON_0 ) ) ||
1272 ( ( mScrollOvershoot < Math::MACHINE_EPSILON_0 ) && ( mScrollDistance > Math::MACHINE_EPSILON_0 ) ) )
1274 // The user has moved against the indicator direction.
1275 // First, we reset the total displacement. This means the overshoot amount will become zero the next frame,
1276 // and if the user starts dragging in the overshoot direction again, the indicator will appear once more.
1277 mTotalPanDisplacement = Vector2::ZERO;
1278 // Animate the overshoot indicator off.
1279 AnimateScrollOvershoot( 0.0f, false );
1283 // Only set the property directly if we are not animating the overshoot away,
1284 // as otherwise this will overwrite the animation generated value.
1285 self.SetProperty( Toolkit::ItemView::Property::OVERSHOOT, mScrollOvershoot );
1291 case GestureState::CANCELLED:
1293 mScrollAnimation = DoAnchoring();
1301 if (mScrollAnimation)
1303 mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
1304 mScrollAnimation.Play();
1308 bool ItemView::OnAccessibilityPan(PanGesture gesture)
1314 Actor ItemView::GetNextKeyboardFocusableActor(Actor actor, Toolkit::Control::KeyboardFocus::Direction direction, bool loopEnabled)
1316 Actor nextFocusActor;
1320 if(!actor || actor == this->Self())
1322 nextFocusActor = GetItem(nextItemID);
1324 else if(actor && actor.GetParent() == this->Self())
1326 int itemID = GetItemId(actor);
1327 nextItemID = mActiveLayout->GetNextFocusItemID(itemID, mItemFactory.GetNumberOfItems(), direction, loopEnabled);
1328 nextFocusActor = GetItem(nextItemID);
1329 if(nextFocusActor == actor)
1331 // need to pass NULL actor back to focus manager
1332 nextFocusActor.Reset();
1333 return nextFocusActor;
1336 float layoutPosition = mActiveLayout->GetClosestAnchorPosition( GetCurrentLayoutPosition(0) );
1337 Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
1340 // likely the current item is not buffered, so not in our item pool, probably best to get first viewable item
1341 ItemRange viewableItems = mActiveLayout->GetItemsWithinArea(layoutPosition, layoutSize);
1342 nextItemID = viewableItems.begin;
1343 nextFocusActor = GetItem(nextItemID);
1346 return nextFocusActor;
1349 void ItemView::OnKeyboardFocusChangeCommitted(Actor commitedFocusableActor)
1351 // only in this function if our chosen focus actor was actually used
1352 if(commitedFocusableActor)
1354 int nextItemID = GetItemId(commitedFocusableActor);
1355 float layoutPosition = GetCurrentLayoutPosition(0);
1356 Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
1358 float scrollTo = mActiveLayout->GetClosestOnScreenLayoutPosition(nextItemID, layoutPosition, layoutSize);
1359 ScrollTo(Vector2(0.0f, scrollTo), DEFAULT_KEYBOARD_FOCUS_SCROLL_DURATION);
1363 void ItemView::AccessibleImpl::EnsureChildVisible(Actor child)
1365 EnsureSelfVisible();
1366 auto itemView = Dali::Toolkit::ItemView::DownCast(self);
1367 Toolkit::GetImpl(itemView).OnKeyboardFocusChangeCommitted(child);
1370 Animation ItemView::DoAnchoring()
1372 Animation anchoringAnimation;
1373 Actor self = Self();
1375 if (mActiveLayout && mAnchoringEnabled)
1377 float anchorPosition = mActiveLayout->GetClosestAnchorPosition( GetCurrentLayoutPosition(0) );
1379 anchoringAnimation = Animation::New(mAnchoringDuration);
1380 anchoringAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), anchorPosition, AlphaFunction::EASE_OUT );
1381 anchoringAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::SCROLL_SPEED), 0.0f, AlphaFunction::EASE_OUT );
1384 AnimateScrollOvershoot(0.0f);
1388 return anchoringAnimation;
1391 void ItemView::OnScrollFinished(Animation& source)
1393 Actor self = Self();
1395 RemoveAnimation(mScrollAnimation); // mScrollAnimation is used to query whether we're scrolling
1397 mScrollCompletedSignal.Emit(GetCurrentScrollPosition());
1399 if(mIsFlicking && fabsf(mScrollOvershoot) > Math::MACHINE_EPSILON_1)
1401 AnimateScrollOvershoot( mScrollOvershoot > 0.0f ? 1.0f : -1.0f, true);
1405 // Reset the overshoot
1406 AnimateScrollOvershoot( 0.0f );
1408 mIsFlicking = false;
1410 mScrollOvershoot = 0.0f;
1413 void ItemView::OnLayoutActivationScrollFinished(Animation& source)
1415 RemoveAnimation(mScrollAnimation);
1416 mRefreshEnabled = true;
1417 DoRefresh(GetCurrentLayoutPosition(0), true);
1419 // Emit the layout activated signal
1420 mLayoutActivatedSignal.Emit();
1423 void ItemView::OnOvershootOnFinished(Animation& animation)
1425 mAnimatingOvershootOn = false;
1426 mScrollOvershootAnimation.FinishedSignal().Disconnect(this, &ItemView::OnOvershootOnFinished);
1427 RemoveAnimation(mScrollOvershootAnimation);
1428 if(mAnimateOvershootOff)
1430 AnimateScrollOvershoot(0.0f);
1432 mInAnimation = false;
1435 void ItemView::ScrollToItem(unsigned int itemId, float durationSeconds)
1437 Actor self = Self();
1438 const Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
1439 float firstItemScrollPosition = ClampFirstItemPosition(mActiveLayout->GetItemScrollToPosition(itemId), layoutSize, *mActiveLayout);
1441 if(durationSeconds > 0.0f)
1443 RemoveAnimation(mScrollAnimation);
1444 mScrollAnimation = Animation::New(durationSeconds);
1445 mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), firstItemScrollPosition, mScrollToAlphaFunction );
1446 mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
1447 mScrollAnimation.Play();
1451 self.SetProperty( Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1452 AnimateScrollOvershoot(0.0f);
1455 mScrollStartedSignal.Emit(GetCurrentScrollPosition());
1456 mRefreshEnabled = true;
1459 void ItemView::RemoveAnimation(Animation& animation)
1463 // Cease animating, and reset handle.
1469 void ItemView::CalculateDomainSize(const Vector3& layoutSize)
1471 Actor self = Self();
1473 Vector3 firstItemPosition(Vector3::ZERO);
1474 Vector3 lastItemPosition(Vector3::ZERO);
1478 firstItemPosition = mActiveLayout->GetItemPosition( 0,0,layoutSize );
1480 float minLayoutPosition = mActiveLayout->GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), layoutSize);
1481 lastItemPosition = mActiveLayout->GetItemPosition( fabs(minLayoutPosition),fabs(minLayoutPosition),layoutSize );
1485 if(IsHorizontal(mActiveLayout->GetOrientation()))
1487 domainSize = fabs(firstItemPosition.x - lastItemPosition.x);
1491 domainSize = fabs(firstItemPosition.y - lastItemPosition.y);
1494 self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MIN, Vector2::ZERO);
1495 self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX, Vector2(0.0f, -minLayoutPosition));
1497 self.SetProperty(Toolkit::ItemView::Property::SCROLL_CONTENT_SIZE, domainSize);
1499 bool isLayoutScrollable = IsLayoutScrollable(layoutSize);
1500 self.SetProperty(Toolkit::Scrollable::Property::CAN_SCROLL_VERTICAL, isLayoutScrollable);
1501 self.SetProperty(Toolkit::Scrollable::Property::CAN_SCROLL_HORIZONTAL, false);
1505 bool ItemView::IsLayoutScrollable(const Vector3& layoutSize)
1507 Actor self = Self();
1509 float currentLayoutPosition = ClampFirstItemPosition( GetCurrentLayoutPosition(0), layoutSize, *mActiveLayout, false );
1510 float forwardClampedPosition = ClampFirstItemPosition( currentLayoutPosition + 1.0, layoutSize, *mActiveLayout, false );
1511 float backwardClampedPosition = ClampFirstItemPosition( currentLayoutPosition - 1.0, layoutSize, *mActiveLayout, false );
1513 return (fabs(forwardClampedPosition - backwardClampedPosition) > Math::MACHINE_EPSILON_0);
1516 float ItemView::GetScrollPosition(float layoutPosition, const Vector3& layoutSize) const
1518 Vector3 firstItemPosition( mActiveLayout->GetItemPosition(0, layoutPosition, layoutSize ) );
1519 return IsHorizontal(mActiveLayout->GetOrientation()) ? firstItemPosition.x: firstItemPosition.y;
1522 Vector2 ItemView::GetCurrentScrollPosition() const
1524 return Vector2(0.0f, GetScrollPosition(GetCurrentLayoutPosition(0), Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE )));
1527 void ItemView::AddOverlay(Actor actor)
1529 actor.SetProperty( Actor::Property::DRAW_MODE, DrawMode::OVERLAY_2D );
1533 void ItemView::RemoveOverlay(Actor actor)
1535 Self().Remove(actor);
1538 void ItemView::ScrollTo(const Vector2& position, float duration)
1540 Actor self = Self();
1541 const Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
1543 float firstItemScrollPosition = ClampFirstItemPosition(position.y, layoutSize, *mActiveLayout);
1547 RemoveAnimation(mScrollAnimation);
1548 mScrollAnimation = Animation::New(duration);
1549 mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), firstItemScrollPosition, mScrollToAlphaFunction );
1550 mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
1551 mScrollAnimation.Play();
1555 self.SetProperty( Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1556 AnimateScrollOvershoot(0.0f);
1559 mScrollStartedSignal.Emit(GetCurrentScrollPosition());
1560 mRefreshEnabled = true;
1563 void ItemView::SetOvershootSize( const Vector2& size )
1565 mOvershootSize = size;
1567 if( mOvershootOverlay )
1569 // Remove old & add new size constraint
1570 mOvershootOverlay.RemoveConstraints( OVERSHOOT_SIZE_CONSTRAINT_TAG );
1571 ApplyOvershootSizeConstraint( mOvershootOverlay, mOvershootSize.height );
1575 void ItemView::SetOvershootEffectColor( const Vector4& color )
1577 mOvershootEffectColor = color;
1578 if( mOvershootOverlay )
1580 mOvershootOverlay.SetProperty( Actor::Property::COLOR, color );
1584 void ItemView::EnableScrollOvershoot( bool enable )
1586 Actor self = Self();
1589 if( !mOvershootOverlay )
1591 Property::Index effectOvershootPropertyIndex = Property::INVALID_INDEX;
1592 mOvershootOverlay = CreateBouncingEffectActor( effectOvershootPropertyIndex );
1593 mOvershootOverlay.SetProperty( Actor::Property::COLOR,mOvershootEffectColor);
1594 mOvershootOverlay.SetProperty( Actor::Property::PARENT_ORIGIN,ParentOrigin::TOP_LEFT );
1595 mOvershootOverlay.SetProperty( Actor::Property::ANCHOR_POINT,AnchorPoint::TOP_LEFT);
1596 mOvershootOverlay.SetProperty( Actor::Property::DRAW_MODE, DrawMode::OVERLAY_2D );
1597 self.Add(mOvershootOverlay);
1599 ApplyOvershootSizeConstraint( mOvershootOverlay, mOvershootSize.height );
1601 Constraint constraint = Constraint::New<Quaternion>( mOvershootOverlay, Actor::Property::ORIENTATION, OvershootOverlayRotationConstraint );
1602 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::SCROLL_DIRECTION ) );
1603 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_ORIENTATION ) );
1604 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::OVERSHOOT ) );
1607 constraint = Constraint::New<Vector3>( mOvershootOverlay, Actor::Property::POSITION, OvershootOverlayPositionConstraint );
1608 constraint.AddSource( ParentSource( Actor::Property::SIZE ) );
1609 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::SCROLL_DIRECTION ) );
1610 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_ORIENTATION ) );
1611 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::OVERSHOOT ) );
1614 constraint = Constraint::New<bool>( mOvershootOverlay, Actor::Property::VISIBLE, OvershootOverlayVisibilityConstraint );
1615 constraint.AddSource( ParentSource( Toolkit::Scrollable::Property::CAN_SCROLL_VERTICAL ) );
1618 constraint = Constraint::New<float>( mOvershootOverlay, effectOvershootPropertyIndex, EqualToConstraint() );
1619 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::OVERSHOOT ) );
1625 if( mOvershootOverlay )
1627 self.Remove(mOvershootOverlay);
1628 mOvershootOverlay.Reset();
1633 float ItemView::CalculateScrollOvershoot()
1635 float overshoot = 0.0f;
1639 // The overshoot must be calculated from the accumulated pan gesture displacement
1640 // since the pan gesture starts.
1641 Actor self = Self();
1642 float scrollDistance = CalculateScrollDistance(mTotalPanDisplacement, *mActiveLayout) * mActiveLayout->GetScrollSpeedFactor();
1643 float positionDelta = GetCurrentLayoutPosition(0) + scrollDistance;
1644 float minLayoutPosition = mActiveLayout->GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ));
1645 self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX, Vector2(0.0f, -minLayoutPosition));
1646 float clamppedPosition = std::min(0.0f, std::max(minLayoutPosition, positionDelta));
1647 overshoot = positionDelta - clamppedPosition;
1650 return overshoot > 0.0f ? std::min(overshoot, 1.0f) : std::max(overshoot, -1.0f);
1653 void ItemView::AnimateScrollOvershoot(float overshootAmount, bool animateBack)
1655 bool animatingOn = fabsf(overshootAmount) > Math::MACHINE_EPSILON_1;
1657 // make sure we animate back if needed
1658 mAnimateOvershootOff = animateBack || (!animatingOn && mAnimatingOvershootOn);
1660 if( mAnimatingOvershootOn )
1662 // animating on, do not allow animate off
1666 Actor self = Self();
1668 if(mOvershootAnimationSpeed > Math::MACHINE_EPSILON_0)
1670 float currentOvershoot = self.GetCurrentProperty< float >( Toolkit::ItemView::Property::OVERSHOOT );
1671 float duration = 0.0f;
1673 if (mOvershootOverlay)
1675 duration = mOvershootOverlay.GetCurrentProperty< Vector3 >( Actor::Property::SIZE ).height * (animatingOn ? (1.0f - fabsf(currentOvershoot)) : fabsf(currentOvershoot)) / mOvershootAnimationSpeed;
1678 // Mark the animation as in progress to prevent manual property sets overwriting it.
1679 mInAnimation = true;
1680 mAnimatingOvershootOn = animatingOn;
1681 RemoveAnimation(mScrollOvershootAnimation);
1682 mScrollOvershootAnimation = Animation::New(duration);
1683 mScrollOvershootAnimation.FinishedSignal().Connect(this, &ItemView::OnOvershootOnFinished);
1684 mScrollOvershootAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::OVERSHOOT), overshootAmount, TimePeriod(0.0f, duration) );
1685 mScrollOvershootAnimation.Play();
1689 self.SetProperty( Toolkit::ItemView::Property::OVERSHOOT, overshootAmount );
1693 void ItemView::SetItemsParentOrigin( const Vector3& parentOrigin )
1695 if( parentOrigin != mItemsParentOrigin )
1697 mItemsParentOrigin = parentOrigin;
1698 for (ItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
1700 iter->second.SetProperty( Actor::Property::PARENT_ORIGIN,parentOrigin );
1705 Vector3 ItemView::GetItemsParentOrigin() const
1707 return mItemsParentOrigin;
1710 void ItemView::SetItemsAnchorPoint( const Vector3& anchorPoint )
1712 if( anchorPoint != mItemsAnchorPoint )
1714 mItemsAnchorPoint = anchorPoint;
1715 for (ItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
1717 iter->second.SetProperty( Actor::Property::ANCHOR_POINT,anchorPoint);
1722 Vector3 ItemView::GetItemsAnchorPoint() const
1724 return mItemsAnchorPoint;
1727 void ItemView::GetItemsRange(ItemRange& range)
1729 if( !mItemPool.empty() )
1731 range.begin = mItemPool.begin()->first;
1732 range.end = mItemPool.rbegin()->first + 1;
1741 bool ItemView::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
1743 Dali::BaseHandle handle( object );
1745 bool connected( true );
1746 Toolkit::ItemView itemView = Toolkit::ItemView::DownCast( handle );
1748 if( 0 == strcmp( signalName.c_str(), LAYOUT_ACTIVATED_SIGNAL ) )
1750 itemView.LayoutActivatedSignal().Connect( tracker, functor );
1754 // signalName does not match any signal
1761 void ItemView::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
1763 Toolkit::ItemView itemView = Toolkit::ItemView::DownCast( Dali::BaseHandle( object ) );
1767 ItemView& itemViewImpl( GetImpl( itemView ) );
1770 case Toolkit::ItemView::Property::MINIMUM_SWIPE_SPEED:
1772 itemViewImpl.SetMinimumSwipeSpeed( value.Get<float>() );
1776 case Toolkit::ItemView::Property::MINIMUM_SWIPE_DISTANCE:
1778 itemViewImpl.SetMinimumSwipeDistance( value.Get<float>() );
1782 case Toolkit::ItemView::Property::WHEEL_SCROLL_DISTANCE_STEP:
1784 itemViewImpl.SetWheelScrollDistanceStep( value.Get<float>() );
1788 case Toolkit::ItemView::Property::SNAP_TO_ITEM_ENABLED:
1790 itemViewImpl.SetAnchoring( value.Get<bool>() );
1794 case Toolkit::ItemView::Property::REFRESH_INTERVAL:
1796 itemViewImpl.SetRefreshInterval( value.Get<float>() );
1800 case Toolkit::ItemView::Property::LAYOUT:
1802 // Get a Property::Array from the property if possible.
1803 Property::Array layoutArray;
1804 if( value.Get( layoutArray ) )
1806 itemViewImpl.SetLayoutArray( layoutArray );
1814 Property::Array ItemView::GetLayoutArray()
1816 return mlayoutArray;
1819 void ItemView::SetLayoutArray( const Property::Array& layouts )
1821 mlayoutArray = layouts;
1822 const int layoutCount = GetLayoutCount();
1823 if( layoutCount > 0 )
1825 for(int index = layoutCount - 1; index >= 0; --index)
1827 RemoveLayout(index);
1828 if(index == 0) break;
1832 for( unsigned int arrayIdx = 0, arrayCount = layouts.Count(); arrayIdx < arrayCount; ++arrayIdx )
1834 const Property::Value& element = layouts.GetElementAt( arrayIdx );
1836 const Property::Map* layout = element.GetMap();
1837 if( layout != NULL )
1839 for( unsigned int mapIdx = 0, mapCount = (*layout).Count(); mapIdx < mapCount; ++mapIdx )
1841 KeyValuePair propertyPair( (*layout).GetKeyValue( mapIdx ) );
1843 if(propertyPair.first == DefaultItemLayoutProperty::TYPE)
1845 int layoutType = propertyPair.second.Get<int>();
1846 if(layoutType <= DefaultItemLayout::SPIRAL && layoutType >= DefaultItemLayout::DEPTH)
1848 //DEPTH, GRID, LIST, SPIRAL
1849 switch(DefaultItemLayout::Type(layoutType))
1851 case DefaultItemLayout::DEPTH:
1853 Internal::DepthLayoutPtr depthLayout = Internal::DepthLayout::New();
1854 (*depthLayout).SetLayoutProperties(*layout);
1855 (*depthLayout).SetDepthLayoutProperties(*layout);
1856 AddLayout(*depthLayout);
1859 case DefaultItemLayout::GRID:
1861 Internal::GridLayoutPtr gridLayout = Internal::GridLayout::New();
1862 (*gridLayout).SetLayoutProperties(*layout);
1863 (*gridLayout).SetGridLayoutProperties(*layout);
1864 AddLayout(*gridLayout);
1867 case DefaultItemLayout::LIST:
1869 Internal::GridLayoutPtr listLayout = Internal::GridLayout::New();
1870 listLayout->SetNumberOfColumns( 1 );
1871 (*listLayout).SetLayoutProperties(*layout);
1872 (*listLayout).SetGridLayoutProperties(*layout);
1873 AddLayout(*listLayout);
1876 case DefaultItemLayout::SPIRAL:
1878 Internal::SpiralLayoutPtr spiralLayout = Internal::SpiralLayout::New();
1879 (*spiralLayout).SetLayoutProperties(*layout);
1880 (*spiralLayout).SetSpiralLayoutProperties(*layout);
1881 AddLayout(*spiralLayout);
1892 Property::Value ItemView::GetProperty( BaseObject* object, Property::Index index )
1894 Property::Value value;
1896 Toolkit::ItemView itemView = Toolkit::ItemView::DownCast( Dali::BaseHandle( object ) );
1900 ItemView& itemViewImpl( GetImpl( itemView ) );
1903 case Toolkit::ItemView::Property::MINIMUM_SWIPE_SPEED:
1905 value = itemViewImpl.GetMinimumSwipeSpeed();
1909 case Toolkit::ItemView::Property::MINIMUM_SWIPE_DISTANCE:
1911 value = itemViewImpl.GetMinimumSwipeDistance();
1915 case Toolkit::ItemView::Property::WHEEL_SCROLL_DISTANCE_STEP:
1917 value = itemViewImpl.GetWheelScrollDistanceStep();
1921 case Toolkit::ItemView::Property::SNAP_TO_ITEM_ENABLED:
1923 value = itemViewImpl.GetAnchoring();
1927 case Toolkit::ItemView::Property::REFRESH_INTERVAL:
1929 value = itemViewImpl.GetRefreshInterval();
1933 case Toolkit::ItemView::Property::LAYOUT:
1935 Property::Array layouts= itemViewImpl.GetLayoutArray();
1945 bool ItemView::DoAction( BaseObject* object, const std::string& actionName, const Property::Map& attributes )
1947 Dali::BaseHandle handle( object );
1949 Toolkit::ItemView itemView = Toolkit::ItemView::DownCast( handle );
1951 DALI_ASSERT_ALWAYS( itemView );
1953 if( 0 == strcmp( actionName.c_str(), ACTION_STOP_SCROLLING ) )
1955 GetImpl( itemView ).DoStopScrolling();
1957 else if ( 0 == strcmp( actionName.c_str(), ACTION_ENABLE_REFRESH ) )
1959 GetImpl( itemView ).SetRefreshNotificationEnabled( true );
1961 else if ( 0 == strcmp( actionName.c_str(), ACTION_DISABLE_REFRESH ) )
1963 GetImpl( itemView ).SetRefreshNotificationEnabled( false );
1969 void ItemView::DoStopScrolling()
1971 if( mScrollAnimation )
1973 mScrollAnimation.Stop();
1974 mScrollAnimation.Reset();
1978 void ItemView::SetRefreshNotificationEnabled( bool enabled )
1980 mRefreshNotificationEnabled = enabled;
1983 } // namespace Internal
1985 } // namespace Toolkit