2 * Copyright (c) 2017 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>
26 #include <dali/public-api/animation/constraint.h>
27 #include <dali/public-api/animation/constraints.h>
28 #include <dali/devel-api/common/set-wrapper.h>
29 #include <dali/public-api/common/stage.h>
30 #include <dali/public-api/events/wheel-event.h>
31 #include <dali/public-api/events/touch-data.h>
32 #include <dali/public-api/object/type-registry.h>
33 #include <dali/public-api/object/type-registry-helper.h>
34 #include <dali/devel-api/object/property-helper-devel.h>
37 #include <dali-toolkit/public-api/controls/scroll-bar/scroll-bar.h>
38 #include <dali-toolkit/public-api/controls/scrollable/item-view/item-factory.h>
39 #include <dali-toolkit/public-api/controls/scrollable/item-view/default-item-layout.h>
40 #include <dali-toolkit/devel-api/controls/scrollable/item-view/default-item-layout-property.h>
41 #include <dali-toolkit/devel-api/controls/scrollable/item-view/item-view-devel.h>
42 #include <dali-toolkit/internal/controls/scrollable/item-view/grid-layout.h>
43 #include <dali-toolkit/internal/controls/scrollable/item-view/depth-layout.h>
44 #include <dali-toolkit/internal/controls/scrollable/item-view/spiral-layout.h>
45 #include <dali-toolkit/internal/controls/scrollable/bouncing-effect-actor.h>
51 namespace // Unnamed namespace
54 const float DEFAULT_MINIMUM_SWIPE_SPEED = 1.0f;
55 const float DEFAULT_MINIMUM_SWIPE_DISTANCE = 3.0f;
56 const float DEFAULT_WHEEL_SCROLL_DISTANCE_STEP_PROPORTION = 0.1f;
58 const float DEFAULT_MINIMUM_SWIPE_DURATION = 0.45f;
59 const float DEFAULT_MAXIMUM_SWIPE_DURATION = 2.6f;
61 const float DEFAULT_REFRESH_INTERVAL_LAYOUT_POSITIONS = 20.0f; // 1 updates per 20 items
62 const int WHEEL_EVENT_FINISHED_TIME_OUT = 500; // 0.5 second
64 const float DEFAULT_ANCHORING_DURATION = 1.0f; // 1 second
66 const float MILLISECONDS_PER_SECONDS = 1000.0f;
68 const float OVERSHOOT_BOUNCE_ACTOR_RESIZE_THRESHOLD = 180.0f;
69 const Vector4 OVERSHOOT_OVERLAY_NINE_PATCH_BORDER(0.0f, 0.0f, 1.0f, 12.0f);
70 const float DEFAULT_KEYBOARD_FOCUS_SCROLL_DURATION = 0.2f;
73 * Local helper to convert pan distance (in actor coordinates) to the layout-specific scrolling direction
75 float CalculateScrollDistance(Vector2 panDistance, Toolkit::ItemLayout& layout)
77 Radian scrollDirection(layout.GetScrollDirection());
79 float cosTheta = cosf(scrollDirection);
80 float sinTheta = sinf(scrollDirection);
82 return panDistance.x * sinTheta + panDistance.y * cosTheta;
85 // Overshoot overlay constraints
86 struct OvershootOverlaySizeConstraint
88 OvershootOverlaySizeConstraint( float height )
89 : mOvershootHeight( height )
93 void operator()( Vector3& current, const PropertyInputContainer& inputs )
95 const Vector2& parentScrollDirection = inputs[0]->GetVector2();
96 const Toolkit::ControlOrientation::Type& layoutOrientation = static_cast<Toolkit::ControlOrientation::Type>(inputs[1]->GetInteger());
97 const Vector3& parentSize = inputs[2]->GetVector3();
99 if(Toolkit::IsVertical(layoutOrientation))
101 current.width = fabsf(parentScrollDirection.y) > Math::MACHINE_EPSILON_1 ? parentSize.x : parentSize.y;
105 current.width = fabsf(parentScrollDirection.x) > Math::MACHINE_EPSILON_1 ? parentSize.y : parentSize.x;
108 current.height = ( current.width > OVERSHOOT_BOUNCE_ACTOR_RESIZE_THRESHOLD ) ? mOvershootHeight : mOvershootHeight*0.5f;
111 float mOvershootHeight;
114 void OvershootOverlayRotationConstraint( Quaternion& current, const PropertyInputContainer& inputs )
116 const Vector2& parentScrollDirection = inputs[0]->GetVector2();
117 const Toolkit::ControlOrientation::Type& layoutOrientation = static_cast<Toolkit::ControlOrientation::Type>(inputs[1]->GetInteger());
118 const float parentOvershoot = inputs[2]->GetFloat();
120 float multiplier = 0;
121 if(Toolkit::IsVertical(layoutOrientation))
123 if(fabsf(parentScrollDirection.y) <= Math::MACHINE_EPSILON_1)
125 if( (layoutOrientation == Toolkit::ControlOrientation::Up && parentOvershoot < Math::MACHINE_EPSILON_0)
126 || (layoutOrientation == Toolkit::ControlOrientation::Down && parentOvershoot > Math::MACHINE_EPSILON_0) )
135 else if( (parentOvershoot > Math::MACHINE_EPSILON_0 && parentScrollDirection.y > Math::MACHINE_EPSILON_0)
136 || (parentOvershoot < Math::MACHINE_EPSILON_0 && parentScrollDirection.y < Math::MACHINE_EPSILON_0) )
147 if(fabsf(parentScrollDirection.x) <= Math::MACHINE_EPSILON_1)
149 if( (layoutOrientation == Toolkit::ControlOrientation::Left && parentOvershoot > Math::MACHINE_EPSILON_0)
150 ||(layoutOrientation == Toolkit::ControlOrientation::Right && parentOvershoot < Math::MACHINE_EPSILON_0) )
159 else if( (parentOvershoot > Math::MACHINE_EPSILON_0 && parentScrollDirection.x > Math::MACHINE_EPSILON_0)
160 || (parentOvershoot < Math::MACHINE_EPSILON_0 && parentScrollDirection.x < Math::MACHINE_EPSILON_0) )
170 current = Quaternion( Radian( multiplier * Math::PI ), Vector3::ZAXIS );
173 void OvershootOverlayPositionConstraint( Vector3& current, const PropertyInputContainer& inputs )
175 const Vector3& parentSize = inputs[0]->GetVector3();
176 const Vector2& parentScrollDirection = inputs[1]->GetVector2();
177 const Toolkit::ControlOrientation::Type& layoutOrientation = static_cast<Toolkit::ControlOrientation::Type>(inputs[2]->GetInteger());
178 const float parentOvershoot = inputs[3]->GetFloat();
180 Vector3 relativeOffset;
182 if(Toolkit::IsVertical(layoutOrientation))
184 if(fabsf(parentScrollDirection.y) <= Math::MACHINE_EPSILON_1)
186 if( (layoutOrientation == Toolkit::ControlOrientation::Up && parentOvershoot < Math::MACHINE_EPSILON_0)
187 || (layoutOrientation == Toolkit::ControlOrientation::Down && parentOvershoot > Math::MACHINE_EPSILON_0) )
189 relativeOffset = Vector3(1.0f, 0.0f, 0.0f);
193 relativeOffset =Vector3(0.0f, 1.0f, 0.0f);
196 else if( (parentOvershoot > Math::MACHINE_EPSILON_0 && parentScrollDirection.y > Math::MACHINE_EPSILON_0)
197 || (parentOvershoot < Math::MACHINE_EPSILON_0 && parentScrollDirection.y < Math::MACHINE_EPSILON_0) )
199 relativeOffset = Vector3(0.0f, 0.0f, 0.0f);
203 relativeOffset = Vector3(1.0f, 1.0f, 0.0f);
208 if(fabsf(parentScrollDirection.x) <= Math::MACHINE_EPSILON_1)
210 if( (layoutOrientation == Toolkit::ControlOrientation::Left && parentOvershoot < Math::MACHINE_EPSILON_0)
211 || (layoutOrientation == Toolkit::ControlOrientation::Right && parentOvershoot > Math::MACHINE_EPSILON_0) )
213 relativeOffset = Vector3(0.0f, 0.0f, 0.0f);
217 relativeOffset = Vector3(1.0f, 1.0f, 0.0f);
220 else if( (parentOvershoot > Math::MACHINE_EPSILON_0 && parentScrollDirection.x > Math::MACHINE_EPSILON_0)
221 || (parentOvershoot < Math::MACHINE_EPSILON_0 && parentScrollDirection.x < Math::MACHINE_EPSILON_0) )
223 relativeOffset = Vector3(0.0f, 1.0f, 0.0f);
227 relativeOffset = Vector3(1.0f, 0.0f, 0.0f);
231 current = relativeOffset * parentSize;
234 void OvershootOverlayVisibilityConstraint( bool& current, const PropertyInputContainer& inputs )
236 current = inputs[0]->GetBoolean();
239 } // unnamed namespace
250 namespace // unnamed namespace
255 DALI_TYPE_REGISTRATION_BEGIN( Toolkit::ItemView, Toolkit::Scrollable, NULL)
257 DALI_PROPERTY_REGISTRATION( Toolkit, ItemView, "minimumSwipeSpeed", FLOAT, MINIMUM_SWIPE_SPEED )
258 DALI_PROPERTY_REGISTRATION( Toolkit, ItemView, "minimumSwipeDistance", FLOAT, MINIMUM_SWIPE_DISTANCE )
259 DALI_PROPERTY_REGISTRATION( Toolkit, ItemView, "wheelScrollDistanceStep", FLOAT, WHEEL_SCROLL_DISTANCE_STEP )
260 DALI_PROPERTY_REGISTRATION( Toolkit, ItemView, "snapToItemEnabled", BOOLEAN, SNAP_TO_ITEM_ENABLED )
261 DALI_PROPERTY_REGISTRATION( Toolkit, ItemView, "refreshInterval", FLOAT, REFRESH_INTERVAL )
262 DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, ItemView, "layout", ARRAY, LAYOUT )
265 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "layoutPosition", FLOAT, LAYOUT_POSITION)
266 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "scrollSpeed", FLOAT, SCROLL_SPEED)
267 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "overshoot", FLOAT, OVERSHOOT)
268 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "scrollDirection", VECTOR2, SCROLL_DIRECTION)
269 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "layoutOrientation", INTEGER, LAYOUT_ORIENTATION)
270 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "scrollContentSize", FLOAT, SCROLL_CONTENT_SIZE)
272 DALI_SIGNAL_REGISTRATION( Toolkit, ItemView, "layoutActivated", LAYOUT_ACTIVATED_SIGNAL )
274 DALI_ACTION_REGISTRATION( Toolkit, ItemView, "stopScrolling", ACTION_STOP_SCROLLING )
276 DALI_ACTION_REGISTRATION( Toolkit, ItemView, "enableRefresh", ACTION_ENABLE_REFRESH )
277 DALI_ACTION_REGISTRATION( Toolkit, ItemView, "disableRefresh", ACTION_DISABLE_REFRESH )
279 DALI_TYPE_REGISTRATION_END()
281 bool FindById( const ItemContainer& items, ItemId id )
283 for( ConstItemIter iter = items.begin(); items.end() != iter; ++iter )
285 if( iter->first == id )
294 } // unnamed namespace
296 Dali::Toolkit::ItemView ItemView::New(ItemFactory& factory)
298 // Create the implementation
299 ItemViewPtr itemView(new ItemView(factory));
301 // Pass ownership to CustomActor via derived handle
302 Dali::Toolkit::ItemView handle(*itemView);
304 // Second-phase init of the implementation
305 // This can only be done after the CustomActor connection has been made...
306 itemView->Initialize();
311 ItemView::ItemView(ItemFactory& factory)
312 : Scrollable( ControlBehaviour( DISABLE_SIZE_NEGOTIATION | DISABLE_STYLE_CHANGE_SIGNALS | REQUIRES_WHEEL_EVENTS | REQUIRES_KEYBOARD_NAVIGATION_SUPPORT ) ),
313 mItemFactory(factory),
314 mItemsParentOrigin(ParentOrigin::CENTER),
315 mItemsAnchorPoint(AnchorPoint::CENTER),
316 mTotalPanDisplacement(Vector2::ZERO),
318 mAnchoringDuration(DEFAULT_ANCHORING_DURATION),
319 mRefreshIntervalLayoutPositions(0.0f),
320 mMinimumSwipeSpeed(DEFAULT_MINIMUM_SWIPE_SPEED),
321 mMinimumSwipeDistance(DEFAULT_MINIMUM_SWIPE_DISTANCE),
322 mWheelScrollDistanceStep(0.0f),
323 mScrollDistance(0.0f),
325 mScrollOvershoot(0.0f),
326 mGestureState(Gesture::Clear),
327 mAnimatingOvershootOn(false),
328 mAnimateOvershootOff(false),
329 mAnchoringEnabled(false),
330 mRefreshOrderHint(true/*Refresh item 0 first*/),
333 mRefreshEnabled(true),
334 mRefreshNotificationEnabled(true),
339 void ItemView::OnInitialize()
343 Vector2 stageSize = Stage::GetCurrent().GetSize();
344 mWheelScrollDistanceStep = stageSize.y * DEFAULT_WHEEL_SCROLL_DISTANCE_STEP_PROPORTION;
346 self.TouchSignal().Connect( this, &ItemView::OnTouch );
347 EnableGestureDetection(Gesture::Type(Gesture::Pan));
349 mWheelEventFinishedTimer = Timer::New( WHEEL_EVENT_FINISHED_TIME_OUT );
350 mWheelEventFinishedTimer.TickSignal().Connect( this, &ItemView::OnWheelEventFinished );
352 SetRefreshInterval(DEFAULT_REFRESH_INTERVAL_LAYOUT_POSITIONS);
355 ItemView::~ItemView()
359 unsigned int ItemView::GetLayoutCount() const
361 return mLayouts.size();
364 void ItemView::AddLayout(ItemLayout& layout)
366 mLayouts.push_back(ItemLayoutPtr(&layout));
369 void ItemView::RemoveLayout(unsigned int layoutIndex)
371 DALI_ASSERT_ALWAYS(layoutIndex < mLayouts.size());
373 if (mActiveLayout == mLayouts[layoutIndex].Get())
375 mActiveLayout = NULL;
378 mLayouts.erase(mLayouts.begin() + layoutIndex);
381 ItemLayoutPtr ItemView::GetLayout(unsigned int layoutIndex) const
383 return mLayouts[layoutIndex];
386 ItemLayoutPtr ItemView::GetActiveLayout() const
388 return ItemLayoutPtr(mActiveLayout);
391 float ItemView::GetCurrentLayoutPosition(unsigned int itemId) const
393 return Self().GetProperty<float>( Toolkit::ItemView::Property::LAYOUT_POSITION ) + static_cast<float>( itemId );
396 void ItemView::ActivateLayout(unsigned int layoutIndex, const Vector3& targetSize, float durationSeconds)
398 DALI_ASSERT_ALWAYS(layoutIndex < mLayouts.size());
400 mRefreshEnabled = false;
404 // The ItemView size should match the active layout size
405 self.SetSize(targetSize);
406 mActiveLayoutTargetSize = targetSize;
408 // Switch to the new layout
409 mActiveLayout = mLayouts[layoutIndex].Get();
411 // Move the items to the new layout positions...
413 for (ConstItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
415 unsigned int itemId = iter->first;
416 Actor actor = iter->second;
418 // Remove constraints from previous layout
419 actor.RemoveConstraints();
421 mActiveLayout->ApplyConstraints(actor, itemId, targetSize, Self() );
424 mActiveLayout->GetItemSize( itemId, targetSize, size );
425 actor.SetSize( size.GetVectorXY() );
428 // Refresh the new layout
429 ItemRange range = GetItemRange(*mActiveLayout, targetSize, GetCurrentLayoutPosition(0), false/* don't reserve extra*/);
430 AddActorsWithinRange( range, targetSize );
432 // Scroll to an appropriate layout position
434 bool scrollAnimationNeeded(false);
435 float firstItemScrollPosition(0.0f);
437 float current = GetCurrentLayoutPosition(0);
438 float minimum = ClampFirstItemPosition(current, targetSize, *mActiveLayout);
440 if (current < minimum)
442 scrollAnimationNeeded = true;
443 firstItemScrollPosition = minimum;
445 else if (mAnchoringEnabled)
447 scrollAnimationNeeded = true;
448 firstItemScrollPosition = mActiveLayout->GetClosestAnchorPosition(current);
451 if (scrollAnimationNeeded)
453 RemoveAnimation(mScrollAnimation);
454 mScrollAnimation = Animation::New(durationSeconds);
455 mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), firstItemScrollPosition, AlphaFunction::EASE_OUT );
456 mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnLayoutActivationScrollFinished);
457 mScrollAnimation.Play();
461 // Emit the layout activated signal
462 mLayoutActivatedSignal.Emit();
465 AnimateScrollOvershoot(0.0f);
466 mScrollOvershoot = 0.0f;
468 Radian scrollDirection(mActiveLayout->GetScrollDirection());
469 self.SetProperty(Toolkit::ItemView::Property::SCROLL_DIRECTION, Vector2(sinf(scrollDirection), cosf(scrollDirection)));
470 self.SetProperty(Toolkit::ItemView::Property::LAYOUT_ORIENTATION, static_cast<int>(mActiveLayout->GetOrientation()));
471 self.SetProperty(Toolkit::ItemView::Property::SCROLL_SPEED, mScrollSpeed);
473 CalculateDomainSize(targetSize);
476 void ItemView::DeactivateCurrentLayout()
480 for (ConstItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
482 Actor actor = iter->second;
483 actor.RemoveConstraints();
486 mActiveLayout = NULL;
490 void ItemView::OnRefreshNotification(PropertyNotification& source)
492 if( mRefreshNotificationEnabled )
494 // Cancel scroll animation to prevent any fighting of setting the scroll position property by scroll bar during fast scroll.
495 if(!mRefreshEnabled && mScrollAnimation)
497 RemoveAnimation(mScrollAnimation);
500 // Only cache extra items when it is not a fast scroll
501 DoRefresh(GetCurrentLayoutPosition(0), mRefreshEnabled || mScrollAnimation);
505 void ItemView::Refresh()
507 for (ItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter )
509 ReleaseActor( iter->first, iter->second );
513 DoRefresh(GetCurrentLayoutPosition(0), true);
516 void ItemView::DoRefresh(float currentLayoutPosition, bool cacheExtra)
520 ItemRange range = GetItemRange(*mActiveLayout, mActiveLayoutTargetSize, currentLayoutPosition, cacheExtra/*reserve extra*/);
521 RemoveActorsOutsideRange( range );
522 AddActorsWithinRange( range, Self().GetCurrentSize() );
524 mScrollUpdatedSignal.Emit( Vector2(0.0f, currentLayoutPosition) );
528 void ItemView::SetMinimumSwipeSpeed(float speed)
530 mMinimumSwipeSpeed = speed;
533 float ItemView::GetMinimumSwipeSpeed() const
535 return mMinimumSwipeSpeed;
538 void ItemView::SetMinimumSwipeDistance(float distance)
540 mMinimumSwipeDistance = distance;
543 float ItemView::GetMinimumSwipeDistance() const
545 return mMinimumSwipeDistance;
548 void ItemView::SetWheelScrollDistanceStep(float step)
550 mWheelScrollDistanceStep = step;
553 float ItemView::GetWheelScrollDistanceStep() const
555 return mWheelScrollDistanceStep;
558 void ItemView::SetAnchoring(bool enabled)
560 mAnchoringEnabled = enabled;
563 bool ItemView::GetAnchoring() const
565 return mAnchoringEnabled;
568 void ItemView::SetAnchoringDuration(float durationSeconds)
570 mAnchoringDuration = durationSeconds;
573 float ItemView::GetAnchoringDuration() const
575 return mAnchoringDuration;
578 void ItemView::SetRefreshInterval(float intervalLayoutPositions)
580 if( !Equals(mRefreshIntervalLayoutPositions, intervalLayoutPositions) )
582 mRefreshIntervalLayoutPositions = intervalLayoutPositions;
585 if(mRefreshNotification)
587 self.RemovePropertyNotification(mRefreshNotification);
589 mRefreshNotification = self.AddPropertyNotification( Toolkit::ItemView::Property::LAYOUT_POSITION, StepCondition(mRefreshIntervalLayoutPositions, 0.0f) );
590 mRefreshNotification.NotifySignal().Connect( this, &ItemView::OnRefreshNotification );
594 float ItemView::GetRefreshInterval() const
596 return mRefreshIntervalLayoutPositions;
599 void ItemView::SetRefreshEnabled(bool enabled)
601 mRefreshEnabled = enabled;
604 Actor ItemView::GetItem(unsigned int itemId) const
608 ConstItemPoolIter iter = mItemPool.find( itemId );
609 if( iter != mItemPool.end() )
611 actor = iter->second;
617 unsigned int ItemView::GetItemId( Actor actor ) const
619 unsigned int itemId( 0 );
621 for ( ConstItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter )
623 if( iter->second == actor )
625 itemId = iter->first;
633 void ItemView::InsertItem( Item newItem, float durationSeconds )
636 Vector3 layoutSize = Self().GetCurrentSize();
638 Actor displacedActor;
639 ItemPoolIter afterDisplacedIter = mItemPool.end();
641 ItemPoolIter foundIter = mItemPool.find( newItem.first );
642 if( mItemPool.end() != foundIter )
644 SetupActor( newItem, layoutSize );
645 Self().Add( newItem.second );
647 displacedActor = foundIter->second;
648 foundIter->second = newItem.second;
650 afterDisplacedIter = ++foundIter;
654 // Inserting before the existing item range?
655 ItemPoolIter iter = mItemPool.begin();
656 if( iter != mItemPool.end() &&
657 iter->first > newItem.first )
659 displacedActor = iter->second;
660 mItemPool.erase( iter++ ); // iter is still valid after the erase
662 afterDisplacedIter = iter;
668 // Move the existing actors to make room
669 for( ItemPoolIter iter = afterDisplacedIter; mItemPool.end() != iter; ++iter )
671 Actor temp = iter->second;
672 iter->second = displacedActor;
673 displacedActor = temp;
675 iter->second.RemoveConstraints();
676 mActiveLayout->ApplyConstraints( iter->second, iter->first, layoutSize, Self() );
680 ItemPool::reverse_iterator lastIter = mItemPool.rbegin();
681 if ( lastIter != mItemPool.rend() )
683 ItemId lastId = lastIter->first;
684 Item lastItem( lastId + 1, displacedActor );
685 mItemPool.insert( lastItem );
687 lastItem.second.RemoveConstraints();
688 mActiveLayout->ApplyConstraints( lastItem.second, lastItem.first, layoutSize, Self() );
692 CalculateDomainSize( layoutSize );
694 mAddingItems = false;
697 void ItemView::InsertItems( const ItemContainer& newItems, float durationSeconds )
700 Vector3 layoutSize = Self().GetCurrentSize();
702 // Insert from lowest id to highest
703 std::set<Item> sortedItems;
704 for( ConstItemIter iter = newItems.begin(); newItems.end() != iter; ++iter )
706 sortedItems.insert( *iter );
709 for( std::set<Item>::iterator iter = sortedItems.begin(); sortedItems.end() != iter; ++iter )
711 Self().Add( iter->second );
713 ItemPoolIter foundIter = mItemPool.find( iter->first );
714 if( mItemPool.end() != foundIter )
716 Actor moveMe = foundIter->second;
717 foundIter->second = iter->second;
719 // Move the existing actors to make room
720 for( ItemPoolIter iter = ++foundIter; mItemPool.end() != iter; ++iter )
722 Actor temp = iter->second;
723 iter->second = moveMe;
728 ItemId lastId = mItemPool.rbegin()->first;
729 Item lastItem( lastId + 1, moveMe );
730 mItemPool.insert( lastItem );
734 mItemPool.insert( *iter );
738 // Relayout everything
739 for (ItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
742 if( FindById( newItems, iter->first ) )
744 SetupActor( *iter, layoutSize );
748 iter->second.RemoveConstraints();
749 mActiveLayout->ApplyConstraints( iter->second, iter->first, layoutSize, Self() );
753 CalculateDomainSize( layoutSize );
755 mAddingItems = false;
758 void ItemView::RemoveItem( unsigned int itemId, float durationSeconds )
760 bool actorsReordered = RemoveActor( itemId );
761 if( actorsReordered )
763 ReapplyAllConstraints();
769 void ItemView::RemoveItems( const ItemIdContainer& itemIds, float durationSeconds )
771 bool actorsReordered( false );
773 // Remove from highest id to lowest
774 set<ItemId> sortedItems;
775 for( ConstItemIdIter iter = itemIds.begin(); itemIds.end() != iter; ++iter )
777 sortedItems.insert( *iter );
780 for( set<ItemId>::reverse_iterator iter = sortedItems.rbegin(); sortedItems.rend() != iter; ++iter )
782 if( RemoveActor( *iter ) )
784 actorsReordered = true;
788 if( actorsReordered )
790 ReapplyAllConstraints();
796 bool ItemView::RemoveActor(unsigned int itemId)
798 bool reordered( false );
800 ItemPoolIter removeIter = mItemPool.find( itemId );
801 if( removeIter != mItemPool.end() )
803 ReleaseActor(itemId, removeIter->second);
807 // Removing before the existing item range?
808 ItemPoolIter iter = mItemPool.begin();
809 if( iter != mItemPool.end() &&
810 iter->first > itemId )
812 // In order to decrement the first visible item ID
813 mItemPool.insert( Item(iter->first - 1, Actor()) );
815 removeIter = mItemPool.begin();
819 if( removeIter != mItemPool.end() )
823 // Adjust the remaining item IDs, for example if item 2 is removed:
824 // Initial actors: After insert:
825 // ID 1 - ActorA ID 1 - ActorA
826 // ID 2 - ActorB ID 2 - ActorC (previously ID 3)
827 // ID 3 - ActorC ID 3 - ActorB (previously ID 4)
829 for (ItemPoolIter iter = removeIter; iter != mItemPool.end(); ++iter)
831 if( iter->first < mItemPool.rbegin()->first )
833 iter->second = mItemPool[ iter->first + 1 ];
837 mItemPool.erase( iter );
846 void ItemView::ReplaceItem( Item replacementItem, float durationSeconds )
849 Vector3 layoutSize = Self().GetCurrentSize();
851 SetupActor( replacementItem, layoutSize );
852 Self().Add( replacementItem.second );
854 const ItemPoolIter iter = mItemPool.find( replacementItem.first );
855 if( mItemPool.end() != iter )
857 ReleaseActor(iter->first, iter->second);
858 iter->second = replacementItem.second;
862 mItemPool.insert( replacementItem );
865 CalculateDomainSize( layoutSize );
867 mAddingItems = false;
870 void ItemView::ReplaceItems( const ItemContainer& replacementItems, float durationSeconds )
872 for( ConstItemIter iter = replacementItems.begin(); replacementItems.end() != iter; ++iter )
874 ReplaceItem( *iter, durationSeconds );
878 void ItemView::RemoveActorsOutsideRange( ItemRange range )
880 // Remove unwanted actors from the ItemView & ItemPool
881 for (ItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); )
883 unsigned int current = iter->first;
885 if( ! range.Within( current ) )
887 ReleaseActor(iter->first, iter->second);
889 mItemPool.erase( iter++ ); // erase invalidates the return value of post-increment; iter remains valid
898 void ItemView::AddActorsWithinRange( ItemRange range, const Vector3& layoutSize )
900 range.end = std::min(mItemFactory.GetNumberOfItems(), range.end);
902 // The order of addition depends on the scroll direction.
903 if (mRefreshOrderHint)
905 for (unsigned int itemId = range.begin; itemId < range.end; ++itemId)
907 AddNewActor( itemId, layoutSize );
912 for (unsigned int itemId = range.end; itemId > range.begin; --itemId)
914 AddNewActor( itemId-1, layoutSize );
918 // Total number of items may change dynamically.
919 // Always recalculate the domain size to reflect that.
920 CalculateDomainSize(Self().GetCurrentSize());
923 void ItemView::AddNewActor( unsigned int itemId, const Vector3& layoutSize )
927 if( mItemPool.end() == mItemPool.find( itemId ) )
929 Actor actor = mItemFactory.NewItem( itemId );
933 Item newItem( itemId, actor );
935 mItemPool.insert( newItem );
937 SetupActor( newItem, layoutSize );
942 mAddingItems = false;
945 void ItemView::SetupActor( Item item, const Vector3& layoutSize )
947 item.second.SetParentOrigin( mItemsParentOrigin );
948 item.second.SetAnchorPoint( mItemsAnchorPoint );
953 mActiveLayout->GetItemSize( item.first, mActiveLayoutTargetSize, size );
954 item.second.SetSize( size.GetVectorXY() );
956 mActiveLayout->ApplyConstraints( item.second, item.first, layoutSize, Self() );
960 void ItemView::ReleaseActor( ItemId item, Actor actor )
962 Self().Remove( actor );
963 mItemFactory.ItemReleased(item, actor);
966 ItemRange ItemView::GetItemRange(ItemLayout& layout, const Vector3& layoutSize, float layoutPosition, bool reserveExtra)
968 unsigned int itemCount = mItemFactory.GetNumberOfItems();
970 ItemRange available(0u, itemCount);
972 ItemRange range = layout.GetItemsWithinArea( layoutPosition, layoutSize );
976 // Add the reserve items for scrolling
977 unsigned int extra = layout.GetReserveItemCount(layoutSize);
978 range.begin = (range.begin >= extra) ? (range.begin - extra) : 0u;
982 return range.Intersection(available);
985 void ItemView::OnChildAdd(Actor& child)
989 // We don't want to do this downcast check for any item added by ItemView itself.
990 Dali::Toolkit::ScrollBar scrollBar = Dali::Toolkit::ScrollBar::DownCast(child);
993 scrollBar.SetScrollPropertySource(Self(),
994 Toolkit::ItemView::Property::LAYOUT_POSITION,
995 Toolkit::Scrollable::Property::SCROLL_POSITION_MIN_Y,
996 Toolkit::Scrollable::Property::SCROLL_POSITION_MAX_Y,
997 Toolkit::ItemView::Property::SCROLL_CONTENT_SIZE);
1001 Scrollable::OnChildAdd( child );
1004 bool ItemView::OnWheelEvent(const WheelEvent& event)
1006 // Respond the wheel event to scroll
1009 Actor self = Self();
1010 const Vector3 layoutSize = Self().GetCurrentSize();
1011 float layoutPositionDelta = GetCurrentLayoutPosition(0) - (event.z * mWheelScrollDistanceStep * mActiveLayout->GetScrollSpeedFactor());
1012 float firstItemScrollPosition = ClampFirstItemPosition(layoutPositionDelta, layoutSize, *mActiveLayout);
1014 self.SetProperty(Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1016 mScrollStartedSignal.Emit(GetCurrentScrollPosition());
1017 mRefreshEnabled = true;
1020 if (mWheelEventFinishedTimer.IsRunning())
1022 mWheelEventFinishedTimer.Stop();
1025 mWheelEventFinishedTimer.Start();
1030 bool ItemView::OnWheelEventFinished()
1034 RemoveAnimation(mScrollAnimation);
1036 // No more wheel events coming. Do the anchoring if enabled.
1037 mScrollAnimation = DoAnchoring();
1038 if (mScrollAnimation)
1040 mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
1041 mScrollAnimation.Play();
1045 mScrollOvershoot = 0.0f;
1046 AnimateScrollOvershoot(0.0f);
1048 mScrollCompletedSignal.Emit(GetCurrentScrollPosition());
1055 void ItemView::ReapplyAllConstraints()
1057 Vector3 layoutSize = Self().GetCurrentSize();
1059 for (ConstItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
1061 unsigned int id = iter->first;
1062 Actor actor = iter->second;
1064 actor.RemoveConstraints();
1065 mActiveLayout->ApplyConstraints(actor, id, layoutSize, Self());
1069 void ItemView::OnItemsRemoved()
1071 CalculateDomainSize(Self().GetCurrentSize());
1073 // Adjust scroll-position after an item is removed
1076 float firstItemScrollPosition = ClampFirstItemPosition(GetCurrentLayoutPosition(0), Self().GetCurrentSize(), *mActiveLayout);
1077 Self().SetProperty( Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1081 float ItemView::ClampFirstItemPosition( float targetPosition, const Vector3& targetSize, ItemLayout& layout, bool updateOvershoot )
1083 Actor self = Self();
1084 float minLayoutPosition = layout.GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), targetSize);
1085 float clamppedPosition = std::min(0.0f, std::max(minLayoutPosition, targetPosition));
1086 self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX, Vector2(0.0f, -minLayoutPosition));
1088 if( updateOvershoot )
1090 mScrollOvershoot = targetPosition - clamppedPosition;
1093 return clamppedPosition;
1096 bool ItemView::OnTouch( Actor actor, const TouchData& touch )
1098 // Ignore events with multiple-touch points
1099 if (touch.GetPointCount() != 1)
1104 if ( touch.GetState( 0 ) == PointState::DOWN )
1106 // Cancel ongoing scrolling etc.
1107 mGestureState = Gesture::Clear;
1109 mScrollDistance = 0.0f;
1110 mScrollSpeed = 0.0f;
1111 Self().SetProperty(Toolkit::ItemView::Property::SCROLL_SPEED, mScrollSpeed);
1113 mScrollOvershoot = 0.0f;
1114 AnimateScrollOvershoot(0.0f);
1116 if(mScrollAnimation)
1118 mScrollCompletedSignal.Emit(GetCurrentScrollPosition());
1121 RemoveAnimation(mScrollAnimation);
1124 return true; // consume since we're potentially scrolling
1127 void ItemView::OnPan( const PanGesture& gesture )
1129 Actor self = Self();
1130 const Vector3 layoutSize = Self().GetCurrentSize();
1132 RemoveAnimation(mScrollAnimation);
1134 // Short-circuit if there is no active layout
1137 mGestureState = Gesture::Clear;
1141 mGestureState = gesture.state;
1143 switch (mGestureState)
1145 case Gesture::Finished:
1148 if (fabsf(mScrollDistance) > mMinimumSwipeDistance &&
1149 mScrollSpeed > mMinimumSwipeSpeed)
1151 float direction = (mScrollDistance < 0.0f) ? -1.0f : 1.0f;
1153 mRefreshOrderHint = true;
1155 float currentLayoutPosition = GetCurrentLayoutPosition(0);
1156 float firstItemScrollPosition = ClampFirstItemPosition(currentLayoutPosition + mScrollSpeed * direction,
1160 if (mAnchoringEnabled)
1162 firstItemScrollPosition = mActiveLayout->GetClosestAnchorPosition(firstItemScrollPosition);
1165 RemoveAnimation(mScrollAnimation);
1167 float flickAnimationDuration = Clamp( mActiveLayout->GetItemFlickAnimationDuration() * std::max(1.0f, fabsf(firstItemScrollPosition - GetCurrentLayoutPosition(0)))
1168 , DEFAULT_MINIMUM_SWIPE_DURATION, DEFAULT_MAXIMUM_SWIPE_DURATION);
1170 mScrollAnimation = Animation::New(flickAnimationDuration);
1171 mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION ), firstItemScrollPosition, AlphaFunction::EASE_OUT );
1172 mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::SCROLL_SPEED), 0.0f, AlphaFunction::EASE_OUT );
1175 // Check whether it has already scrolled to the end
1176 if(fabs(currentLayoutPosition - firstItemScrollPosition) > Math::MACHINE_EPSILON_0)
1178 AnimateScrollOvershoot(0.0f);
1182 // Anchoring may be triggered when there was no swipe
1183 if (!mScrollAnimation)
1185 mScrollAnimation = DoAnchoring();
1188 // Reset the overshoot if no scroll animation.
1189 if (!mScrollAnimation)
1191 mScrollCompletedSignal.Emit(GetCurrentScrollPosition());
1193 AnimateScrollOvershoot(0.0f, false);
1198 case Gesture::Started: // Fall through
1200 mTotalPanDisplacement = Vector2::ZERO;
1201 mScrollStartedSignal.Emit(GetCurrentScrollPosition());
1202 mRefreshEnabled = true;
1205 case Gesture::Continuing:
1207 mScrollDistance = CalculateScrollDistance(gesture.displacement, *mActiveLayout);
1208 mScrollSpeed = Clamp((gesture.GetSpeed() * gesture.GetSpeed() * mActiveLayout->GetFlickSpeedFactor() * MILLISECONDS_PER_SECONDS), 0.0f, mActiveLayout->GetMaximumSwipeSpeed());
1210 // Refresh order depends on the direction of the scroll; negative is towards the last item.
1211 mRefreshOrderHint = mScrollDistance < 0.0f;
1213 float layoutPositionDelta = GetCurrentLayoutPosition(0) + (mScrollDistance * mActiveLayout->GetScrollSpeedFactor());
1215 float firstItemScrollPosition = ClampFirstItemPosition(layoutPositionDelta, layoutSize, *mActiveLayout);
1217 float currentOvershoot = self.GetProperty<float>(Toolkit::ItemView::Property::OVERSHOOT);
1219 self.SetProperty(Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1221 if( ( firstItemScrollPosition >= 0.0f &&
1222 currentOvershoot < 1.0f ) ||
1223 ( firstItemScrollPosition <= mActiveLayout->GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), layoutSize) &&
1224 currentOvershoot > -1.0f ) )
1226 mTotalPanDisplacement += gesture.displacement;
1229 mScrollOvershoot = CalculateScrollOvershoot();
1231 // If the view is moved in a direction against the overshoot indicator, then the indicator should be animated off.
1232 // First make sure we are not in an animation, otherwise a previously started
1233 // off-animation will be overwritten as the user continues scrolling.
1236 // Check if the movement is against the current overshoot amount (if we are currently displaying the indicator).
1237 if( ( ( mScrollOvershoot > Math::MACHINE_EPSILON_0 ) && ( mScrollDistance < -Math::MACHINE_EPSILON_0 ) ) ||
1238 ( ( mScrollOvershoot < Math::MACHINE_EPSILON_0 ) && ( mScrollDistance > Math::MACHINE_EPSILON_0 ) ) )
1240 // The user has moved against the indicator direction.
1241 // First, we reset the total displacement. This means the overshoot amount will become zero the next frame,
1242 // and if the user starts dragging in the overshoot direction again, the indicator will appear once more.
1243 mTotalPanDisplacement = Vector2::ZERO;
1244 // Animate the overshoot indicator off.
1245 AnimateScrollOvershoot( 0.0f, false );
1249 // Only set the property directly if we are not animating the overshoot away,
1250 // as otherwise this will overwrite the animation generated value.
1251 self.SetProperty( Toolkit::ItemView::Property::OVERSHOOT, mScrollOvershoot );
1257 case Gesture::Cancelled:
1259 mScrollAnimation = DoAnchoring();
1267 if (mScrollAnimation)
1269 mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
1270 mScrollAnimation.Play();
1274 bool ItemView::OnAccessibilityPan(PanGesture gesture)
1280 Actor ItemView::GetNextKeyboardFocusableActor(Actor actor, Toolkit::Control::KeyboardFocus::Direction direction, bool loopEnabled)
1282 Actor nextFocusActor;
1286 if(!actor || actor == this->Self())
1288 nextFocusActor = GetItem(nextItemID);
1290 else if(actor && actor.GetParent() == this->Self())
1292 int itemID = GetItemId(actor);
1293 nextItemID = mActiveLayout->GetNextFocusItemID(itemID, mItemFactory.GetNumberOfItems(), direction, loopEnabled);
1294 nextFocusActor = GetItem(nextItemID);
1295 if(nextFocusActor == actor)
1297 // need to pass NULL actor back to focus manager
1298 nextFocusActor.Reset();
1299 return nextFocusActor;
1302 float layoutPosition = mActiveLayout->GetClosestAnchorPosition( GetCurrentLayoutPosition(0) );
1303 Vector3 layoutSize = Self().GetCurrentSize();
1306 // likely the current item is not buffered, so not in our item pool, probably best to get first viewable item
1307 ItemRange viewableItems = mActiveLayout->GetItemsWithinArea(layoutPosition, layoutSize);
1308 nextItemID = viewableItems.begin;
1309 nextFocusActor = GetItem(nextItemID);
1312 return nextFocusActor;
1315 void ItemView::OnKeyboardFocusChangeCommitted(Actor commitedFocusableActor)
1317 // only in this function if our chosen focus actor was actually used
1318 if(commitedFocusableActor)
1320 int nextItemID = GetItemId(commitedFocusableActor);
1321 float layoutPosition = GetCurrentLayoutPosition(0);
1322 Vector3 layoutSize = Self().GetCurrentSize();
1324 float scrollTo = mActiveLayout->GetClosestOnScreenLayoutPosition(nextItemID, layoutPosition, layoutSize);
1325 ScrollTo(Vector2(0.0f, scrollTo), DEFAULT_KEYBOARD_FOCUS_SCROLL_DURATION);
1329 Animation ItemView::DoAnchoring()
1331 Animation anchoringAnimation;
1332 Actor self = Self();
1334 if (mActiveLayout && mAnchoringEnabled)
1336 float anchorPosition = mActiveLayout->GetClosestAnchorPosition( GetCurrentLayoutPosition(0) );
1338 anchoringAnimation = Animation::New(mAnchoringDuration);
1339 anchoringAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), anchorPosition, AlphaFunction::EASE_OUT );
1340 anchoringAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::SCROLL_SPEED), 0.0f, AlphaFunction::EASE_OUT );
1343 AnimateScrollOvershoot(0.0f);
1347 return anchoringAnimation;
1350 void ItemView::OnScrollFinished(Animation& source)
1352 Actor self = Self();
1354 RemoveAnimation(mScrollAnimation); // mScrollAnimation is used to query whether we're scrolling
1356 mScrollCompletedSignal.Emit(GetCurrentScrollPosition());
1358 if(mIsFlicking && fabsf(mScrollOvershoot) > Math::MACHINE_EPSILON_1)
1360 AnimateScrollOvershoot( mScrollOvershoot > 0.0f ? 1.0f : -1.0f, true);
1364 // Reset the overshoot
1365 AnimateScrollOvershoot( 0.0f );
1367 mIsFlicking = false;
1369 mScrollOvershoot = 0.0f;
1372 void ItemView::OnLayoutActivationScrollFinished(Animation& source)
1374 RemoveAnimation(mScrollAnimation);
1375 mRefreshEnabled = true;
1376 DoRefresh(GetCurrentLayoutPosition(0), true);
1378 // Emit the layout activated signal
1379 mLayoutActivatedSignal.Emit();
1382 void ItemView::OnOvershootOnFinished(Animation& animation)
1384 mAnimatingOvershootOn = false;
1385 mScrollOvershootAnimation.FinishedSignal().Disconnect(this, &ItemView::OnOvershootOnFinished);
1386 RemoveAnimation(mScrollOvershootAnimation);
1387 if(mAnimateOvershootOff)
1389 AnimateScrollOvershoot(0.0f);
1391 mInAnimation = false;
1394 void ItemView::ScrollToItem(unsigned int itemId, float durationSeconds)
1396 Actor self = Self();
1397 const Vector3 layoutSize = Self().GetCurrentSize();
1398 float firstItemScrollPosition = ClampFirstItemPosition(mActiveLayout->GetItemScrollToPosition(itemId), layoutSize, *mActiveLayout);
1400 if(durationSeconds > 0.0f)
1402 RemoveAnimation(mScrollAnimation);
1403 mScrollAnimation = Animation::New(durationSeconds);
1404 mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), firstItemScrollPosition, mScrollToAlphaFunction );
1405 mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
1406 mScrollAnimation.Play();
1410 self.SetProperty( Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1411 AnimateScrollOvershoot(0.0f);
1414 mScrollStartedSignal.Emit(GetCurrentScrollPosition());
1415 mRefreshEnabled = true;
1418 void ItemView::RemoveAnimation(Animation& animation)
1422 // Cease animating, and reset handle.
1428 void ItemView::CalculateDomainSize(const Vector3& layoutSize)
1430 Actor self = Self();
1432 Vector3 firstItemPosition(Vector3::ZERO);
1433 Vector3 lastItemPosition(Vector3::ZERO);
1437 firstItemPosition = mActiveLayout->GetItemPosition( 0,0,layoutSize );
1439 float minLayoutPosition = mActiveLayout->GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), layoutSize);
1440 lastItemPosition = mActiveLayout->GetItemPosition( fabs(minLayoutPosition),fabs(minLayoutPosition),layoutSize );
1444 if(IsHorizontal(mActiveLayout->GetOrientation()))
1446 domainSize = fabs(firstItemPosition.x - lastItemPosition.x);
1450 domainSize = fabs(firstItemPosition.y - lastItemPosition.y);
1453 self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MIN, Vector2::ZERO);
1454 self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX, Vector2(0.0f, -minLayoutPosition));
1456 self.SetProperty(Toolkit::ItemView::Property::SCROLL_CONTENT_SIZE, domainSize);
1458 bool isLayoutScrollable = IsLayoutScrollable(layoutSize);
1459 self.SetProperty(Toolkit::Scrollable::Property::CAN_SCROLL_VERTICAL, isLayoutScrollable);
1460 self.SetProperty(Toolkit::Scrollable::Property::CAN_SCROLL_HORIZONTAL, false);
1464 bool ItemView::IsLayoutScrollable(const Vector3& layoutSize)
1466 Actor self = Self();
1468 float currentLayoutPosition = ClampFirstItemPosition( GetCurrentLayoutPosition(0), layoutSize, *mActiveLayout, false );
1469 float forwardClampedPosition = ClampFirstItemPosition( currentLayoutPosition + 1.0, layoutSize, *mActiveLayout, false );
1470 float backwardClampedPosition = ClampFirstItemPosition( currentLayoutPosition - 1.0, layoutSize, *mActiveLayout, false );
1472 return (fabs(forwardClampedPosition - backwardClampedPosition) > Math::MACHINE_EPSILON_0);
1475 float ItemView::GetScrollPosition(float layoutPosition, const Vector3& layoutSize) const
1477 Vector3 firstItemPosition( mActiveLayout->GetItemPosition(0, layoutPosition, layoutSize ) );
1478 return IsHorizontal(mActiveLayout->GetOrientation()) ? firstItemPosition.x: firstItemPosition.y;
1481 Vector2 ItemView::GetCurrentScrollPosition() const
1483 return Vector2(0.0f, GetScrollPosition(GetCurrentLayoutPosition(0), Self().GetCurrentSize()));
1486 void ItemView::AddOverlay(Actor actor)
1488 actor.SetDrawMode( DrawMode::OVERLAY_2D );
1492 void ItemView::RemoveOverlay(Actor actor)
1494 Self().Remove(actor);
1497 void ItemView::ScrollTo(const Vector2& position, float duration)
1499 Actor self = Self();
1500 const Vector3 layoutSize = Self().GetCurrentSize();
1502 float firstItemScrollPosition = ClampFirstItemPosition(position.y, layoutSize, *mActiveLayout);
1506 RemoveAnimation(mScrollAnimation);
1507 mScrollAnimation = Animation::New(duration);
1508 mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), firstItemScrollPosition, mScrollToAlphaFunction );
1509 mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
1510 mScrollAnimation.Play();
1514 self.SetProperty( Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1515 AnimateScrollOvershoot(0.0f);
1518 mScrollStartedSignal.Emit(GetCurrentScrollPosition());
1519 mRefreshEnabled = true;
1522 void ItemView::SetOvershootEffectColor( const Vector4& color )
1524 mOvershootEffectColor = color;
1525 if( mOvershootOverlay )
1527 mOvershootOverlay.SetColor( color );
1531 void ItemView::EnableScrollOvershoot( bool enable )
1533 Actor self = Self();
1536 if( !mOvershootOverlay )
1538 Property::Index effectOvershootPropertyIndex = Property::INVALID_INDEX;
1539 mOvershootOverlay = CreateBouncingEffectActor( effectOvershootPropertyIndex );
1540 mOvershootOverlay.SetColor(mOvershootEffectColor);
1541 mOvershootOverlay.SetParentOrigin(ParentOrigin::TOP_LEFT);
1542 mOvershootOverlay.SetAnchorPoint(AnchorPoint::TOP_LEFT);
1543 mOvershootOverlay.SetDrawMode( DrawMode::OVERLAY_2D );
1544 self.Add(mOvershootOverlay);
1546 Constraint constraint = Constraint::New<Vector3>( mOvershootOverlay, Actor::Property::SIZE, OvershootOverlaySizeConstraint(mOvershootSize.height) );
1547 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::SCROLL_DIRECTION ) );
1548 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_ORIENTATION ) );
1549 constraint.AddSource( ParentSource( Actor::Property::SIZE ) );
1552 mOvershootOverlay.SetSize(mOvershootSize.width, mOvershootSize.height);
1554 constraint = Constraint::New<Quaternion>( mOvershootOverlay, Actor::Property::ORIENTATION, OvershootOverlayRotationConstraint );
1555 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::SCROLL_DIRECTION ) );
1556 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_ORIENTATION ) );
1557 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::OVERSHOOT ) );
1560 constraint = Constraint::New<Vector3>( mOvershootOverlay, Actor::Property::POSITION, OvershootOverlayPositionConstraint );
1561 constraint.AddSource( ParentSource( Actor::Property::SIZE ) );
1562 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::SCROLL_DIRECTION ) );
1563 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_ORIENTATION ) );
1564 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::OVERSHOOT ) );
1567 constraint = Constraint::New<bool>( mOvershootOverlay, Actor::Property::VISIBLE, OvershootOverlayVisibilityConstraint );
1568 constraint.AddSource( ParentSource( Toolkit::Scrollable::Property::CAN_SCROLL_VERTICAL ) );
1571 constraint = Constraint::New<float>( mOvershootOverlay, effectOvershootPropertyIndex, EqualToConstraint() );
1572 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::OVERSHOOT ) );
1578 if( mOvershootOverlay )
1580 self.Remove(mOvershootOverlay);
1581 mOvershootOverlay.Reset();
1586 float ItemView::CalculateScrollOvershoot()
1588 float overshoot = 0.0f;
1592 // The overshoot must be calculated from the accumulated pan gesture displacement
1593 // since the pan gesture starts.
1594 Actor self = Self();
1595 float scrollDistance = CalculateScrollDistance(mTotalPanDisplacement, *mActiveLayout) * mActiveLayout->GetScrollSpeedFactor();
1596 float positionDelta = GetCurrentLayoutPosition(0) + scrollDistance;
1597 float minLayoutPosition = mActiveLayout->GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), Self().GetCurrentSize());
1598 self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX, Vector2(0.0f, -minLayoutPosition));
1599 float clamppedPosition = std::min(0.0f, std::max(minLayoutPosition, positionDelta));
1600 overshoot = positionDelta - clamppedPosition;
1603 return overshoot > 0.0f ? std::min(overshoot, 1.0f) : std::max(overshoot, -1.0f);
1606 void ItemView::AnimateScrollOvershoot(float overshootAmount, bool animateBack)
1608 bool animatingOn = fabsf(overshootAmount) > Math::MACHINE_EPSILON_1;
1610 // make sure we animate back if needed
1611 mAnimateOvershootOff = animateBack || (!animatingOn && mAnimatingOvershootOn);
1613 if( mAnimatingOvershootOn )
1615 // animating on, do not allow animate off
1619 Actor self = Self();
1621 if(mOvershootAnimationSpeed > Math::MACHINE_EPSILON_0)
1623 float currentOvershoot = self.GetProperty<float>(Toolkit::ItemView::Property::OVERSHOOT);
1624 float duration = 0.0f;
1626 if (mOvershootOverlay)
1628 duration = mOvershootOverlay.GetCurrentSize().height * (animatingOn ? (1.0f - fabsf(currentOvershoot)) : fabsf(currentOvershoot)) / mOvershootAnimationSpeed;
1631 // Mark the animation as in progress to prevent manual property sets overwriting it.
1632 mInAnimation = true;
1633 mAnimatingOvershootOn = animatingOn;
1634 RemoveAnimation(mScrollOvershootAnimation);
1635 mScrollOvershootAnimation = Animation::New(duration);
1636 mScrollOvershootAnimation.FinishedSignal().Connect(this, &ItemView::OnOvershootOnFinished);
1637 mScrollOvershootAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::OVERSHOOT), overshootAmount, TimePeriod(0.0f, duration) );
1638 mScrollOvershootAnimation.Play();
1642 self.SetProperty( Toolkit::ItemView::Property::OVERSHOOT, overshootAmount );
1646 void ItemView::SetItemsParentOrigin( const Vector3& parentOrigin )
1648 if( parentOrigin != mItemsParentOrigin )
1650 mItemsParentOrigin = parentOrigin;
1651 for (ItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
1653 iter->second.SetParentOrigin(parentOrigin);
1658 Vector3 ItemView::GetItemsParentOrigin() const
1660 return mItemsParentOrigin;
1663 void ItemView::SetItemsAnchorPoint( const Vector3& anchorPoint )
1665 if( anchorPoint != mItemsAnchorPoint )
1667 mItemsAnchorPoint = anchorPoint;
1668 for (ItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
1670 iter->second.SetAnchorPoint(anchorPoint);
1675 Vector3 ItemView::GetItemsAnchorPoint() const
1677 return mItemsAnchorPoint;
1680 void ItemView::GetItemsRange(ItemRange& range)
1682 if( !mItemPool.empty() )
1684 range.begin = mItemPool.begin()->first;
1685 range.end = mItemPool.rbegin()->first + 1;
1694 bool ItemView::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
1696 Dali::BaseHandle handle( object );
1698 bool connected( true );
1699 Toolkit::ItemView itemView = Toolkit::ItemView::DownCast( handle );
1701 if( 0 == strcmp( signalName.c_str(), LAYOUT_ACTIVATED_SIGNAL ) )
1703 itemView.LayoutActivatedSignal().Connect( tracker, functor );
1707 // signalName does not match any signal
1714 void ItemView::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
1716 Toolkit::ItemView itemView = Toolkit::ItemView::DownCast( Dali::BaseHandle( object ) );
1720 ItemView& itemViewImpl( GetImpl( itemView ) );
1723 case Toolkit::ItemView::Property::MINIMUM_SWIPE_SPEED:
1725 itemViewImpl.SetMinimumSwipeSpeed( value.Get<float>() );
1728 case Toolkit::ItemView::Property::MINIMUM_SWIPE_DISTANCE:
1730 itemViewImpl.SetMinimumSwipeDistance( value.Get<float>() );
1733 case Toolkit::ItemView::Property::WHEEL_SCROLL_DISTANCE_STEP:
1735 itemViewImpl.SetWheelScrollDistanceStep( value.Get<float>() );
1738 case Toolkit::ItemView::Property::SNAP_TO_ITEM_ENABLED:
1740 itemViewImpl.SetAnchoring( value.Get<bool>() );
1743 case Toolkit::ItemView::Property::REFRESH_INTERVAL:
1745 itemViewImpl.SetRefreshInterval( value.Get<float>() );
1748 case Toolkit::DevelItemView::Property::LAYOUT:
1750 // Get a Property::Array from the property if possible.
1751 Property::Array layoutArray;
1752 if( value.Get( layoutArray ) )
1754 itemViewImpl.SetLayoutArray( layoutArray );
1762 Property::Array ItemView::GetLayoutArray()
1764 return mlayoutArray;
1767 void ItemView::SetLayoutArray( const Property::Array& layouts )
1769 mlayoutArray = layouts;
1770 const int layoutCount = GetLayoutCount();
1771 if( layoutCount > 0 )
1773 for(int index = layoutCount - 1; index >= 0; --index)
1775 RemoveLayout(index);
1776 if(index == 0) break;
1780 for( unsigned int arrayIdx = 0, arrayCount = layouts.Count(); arrayIdx < arrayCount; ++arrayIdx )
1782 const Property::Value& element = layouts.GetElementAt( arrayIdx );
1784 Property::Map* layout = element.GetMap();
1785 if( layout != NULL )
1787 for( unsigned int mapIdx = 0, mapCount = (*layout).Count(); mapIdx < mapCount; ++mapIdx )
1789 KeyValuePair propertyPair( (*layout).GetKeyValue( mapIdx ) );
1791 if(propertyPair.first == DefaultItemLayoutProperty::TYPE)
1793 int layoutType = propertyPair.second.Get<int>();
1794 if(layoutType <= DefaultItemLayout::SPIRAL && layoutType >= DefaultItemLayout::DEPTH)
1796 //DEPTH, GRID, LIST, SPIRAL
1797 switch(DefaultItemLayout::Type(layoutType))
1799 case DefaultItemLayout::DEPTH:
1801 Internal::DepthLayoutPtr depthLayout = Internal::DepthLayout::New();
1802 (*depthLayout).SetLayoutProperties(*layout);
1803 AddLayout(*depthLayout);
1806 case DefaultItemLayout::GRID:
1808 Internal::GridLayoutPtr gridLayout = Internal::GridLayout::New();
1809 (*gridLayout).SetLayoutProperties(*layout);
1810 AddLayout(*gridLayout);
1813 case DefaultItemLayout::LIST:
1815 Internal::GridLayoutPtr listLayout = Internal::GridLayout::New();
1816 listLayout->SetNumberOfColumns( 1 );
1817 (*listLayout).SetLayoutProperties(*layout);
1818 AddLayout(*listLayout);
1821 case DefaultItemLayout::SPIRAL:
1823 Internal::SpiralLayoutPtr spiralLayout = Internal::SpiralLayout::New();
1824 (*spiralLayout).SetLayoutProperties(*layout);
1825 AddLayout(*spiralLayout);
1836 Property::Value ItemView::GetProperty( BaseObject* object, Property::Index index )
1838 Property::Value value;
1840 Toolkit::ItemView itemView = Toolkit::ItemView::DownCast( Dali::BaseHandle( object ) );
1844 ItemView& itemViewImpl( GetImpl( itemView ) );
1847 case Toolkit::ItemView::Property::MINIMUM_SWIPE_SPEED:
1849 value = itemViewImpl.GetMinimumSwipeSpeed();
1852 case Toolkit::ItemView::Property::MINIMUM_SWIPE_DISTANCE:
1854 value = itemViewImpl.GetMinimumSwipeDistance();
1857 case Toolkit::ItemView::Property::WHEEL_SCROLL_DISTANCE_STEP:
1859 value = itemViewImpl.GetWheelScrollDistanceStep();
1862 case Toolkit::ItemView::Property::SNAP_TO_ITEM_ENABLED:
1864 value = itemViewImpl.GetAnchoring();
1867 case Toolkit::ItemView::Property::REFRESH_INTERVAL:
1869 value = itemViewImpl.GetRefreshInterval();
1872 case Toolkit::DevelItemView::Property::LAYOUT:
1874 Property::Array layouts= itemViewImpl.GetLayoutArray();
1885 bool ItemView::DoAction( BaseObject* object, const std::string& actionName, const Property::Map& attributes )
1887 Dali::BaseHandle handle( object );
1889 Toolkit::ItemView itemView = Toolkit::ItemView::DownCast( handle );
1891 DALI_ASSERT_ALWAYS( itemView );
1893 if( 0 == strcmp( actionName.c_str(), ACTION_STOP_SCROLLING ) )
1895 GetImpl( itemView ).DoStopScrolling();
1897 else if ( 0 == strcmp( actionName.c_str(), ACTION_ENABLE_REFRESH ) )
1899 GetImpl( itemView ).SetRefreshNotificationEnabled( true );
1901 else if ( 0 == strcmp( actionName.c_str(), ACTION_DISABLE_REFRESH ) )
1903 GetImpl( itemView ).SetRefreshNotificationEnabled( false );
1909 void ItemView::DoStopScrolling()
1911 if( mScrollAnimation )
1913 mScrollAnimation.Stop();
1914 mScrollAnimation.Reset();
1918 void ItemView::SetRefreshNotificationEnabled( bool enabled )
1920 mRefreshNotificationEnabled = enabled;
1923 } // namespace Internal
1925 } // namespace Toolkit