2 * Copyright (c) 2014 Samsung Electronics Co., Ltd.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 #include <dali-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);
1002 bool ItemView::OnWheelEvent(const WheelEvent& event)
1004 // Respond the wheel event to scroll
1007 Actor self = Self();
1008 const Vector3 layoutSize = Self().GetCurrentSize();
1009 float layoutPositionDelta = GetCurrentLayoutPosition(0) - (event.z * mWheelScrollDistanceStep * mActiveLayout->GetScrollSpeedFactor());
1010 float firstItemScrollPosition = ClampFirstItemPosition(layoutPositionDelta, layoutSize, *mActiveLayout);
1012 self.SetProperty(Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1014 mScrollStartedSignal.Emit(GetCurrentScrollPosition());
1015 mRefreshEnabled = true;
1018 if (mWheelEventFinishedTimer.IsRunning())
1020 mWheelEventFinishedTimer.Stop();
1023 mWheelEventFinishedTimer.Start();
1028 bool ItemView::OnWheelEventFinished()
1032 RemoveAnimation(mScrollAnimation);
1034 // No more wheel events coming. Do the anchoring if enabled.
1035 mScrollAnimation = DoAnchoring();
1036 if (mScrollAnimation)
1038 mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
1039 mScrollAnimation.Play();
1043 mScrollOvershoot = 0.0f;
1044 AnimateScrollOvershoot(0.0f);
1046 mScrollCompletedSignal.Emit(GetCurrentScrollPosition());
1053 void ItemView::ReapplyAllConstraints()
1055 Vector3 layoutSize = Self().GetCurrentSize();
1057 for (ConstItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
1059 unsigned int id = iter->first;
1060 Actor actor = iter->second;
1062 actor.RemoveConstraints();
1063 mActiveLayout->ApplyConstraints(actor, id, layoutSize, Self());
1067 void ItemView::OnItemsRemoved()
1069 CalculateDomainSize(Self().GetCurrentSize());
1071 // Adjust scroll-position after an item is removed
1074 float firstItemScrollPosition = ClampFirstItemPosition(GetCurrentLayoutPosition(0), Self().GetCurrentSize(), *mActiveLayout);
1075 Self().SetProperty( Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1079 float ItemView::ClampFirstItemPosition( float targetPosition, const Vector3& targetSize, ItemLayout& layout, bool updateOvershoot )
1081 Actor self = Self();
1082 float minLayoutPosition = layout.GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), targetSize);
1083 float clamppedPosition = std::min(0.0f, std::max(minLayoutPosition, targetPosition));
1084 self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX, Vector2(0.0f, -minLayoutPosition));
1086 if( updateOvershoot )
1088 mScrollOvershoot = targetPosition - clamppedPosition;
1091 return clamppedPosition;
1094 bool ItemView::OnTouch( Actor actor, const TouchData& touch )
1096 // Ignore events with multiple-touch points
1097 if (touch.GetPointCount() != 1)
1102 if ( touch.GetState( 0 ) == PointState::DOWN )
1104 // Cancel ongoing scrolling etc.
1105 mGestureState = Gesture::Clear;
1107 mScrollDistance = 0.0f;
1108 mScrollSpeed = 0.0f;
1109 Self().SetProperty(Toolkit::ItemView::Property::SCROLL_SPEED, mScrollSpeed);
1111 mScrollOvershoot = 0.0f;
1112 AnimateScrollOvershoot(0.0f);
1114 if(mScrollAnimation)
1116 mScrollCompletedSignal.Emit(GetCurrentScrollPosition());
1119 RemoveAnimation(mScrollAnimation);
1122 return true; // consume since we're potentially scrolling
1125 void ItemView::OnPan( const PanGesture& gesture )
1127 Actor self = Self();
1128 const Vector3 layoutSize = Self().GetCurrentSize();
1130 RemoveAnimation(mScrollAnimation);
1132 // Short-circuit if there is no active layout
1135 mGestureState = Gesture::Clear;
1139 mGestureState = gesture.state;
1141 switch (mGestureState)
1143 case Gesture::Finished:
1146 if (fabsf(mScrollDistance) > mMinimumSwipeDistance &&
1147 mScrollSpeed > mMinimumSwipeSpeed)
1149 float direction = (mScrollDistance < 0.0f) ? -1.0f : 1.0f;
1151 mRefreshOrderHint = true;
1153 float currentLayoutPosition = GetCurrentLayoutPosition(0);
1154 float firstItemScrollPosition = ClampFirstItemPosition(currentLayoutPosition + mScrollSpeed * direction,
1158 if (mAnchoringEnabled)
1160 firstItemScrollPosition = mActiveLayout->GetClosestAnchorPosition(firstItemScrollPosition);
1163 RemoveAnimation(mScrollAnimation);
1165 float flickAnimationDuration = Clamp( mActiveLayout->GetItemFlickAnimationDuration() * std::max(1.0f, fabsf(firstItemScrollPosition - GetCurrentLayoutPosition(0)))
1166 , DEFAULT_MINIMUM_SWIPE_DURATION, DEFAULT_MAXIMUM_SWIPE_DURATION);
1168 mScrollAnimation = Animation::New(flickAnimationDuration);
1169 mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION ), firstItemScrollPosition, AlphaFunction::EASE_OUT );
1170 mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::SCROLL_SPEED), 0.0f, AlphaFunction::EASE_OUT );
1173 // Check whether it has already scrolled to the end
1174 if(fabs(currentLayoutPosition - firstItemScrollPosition) > Math::MACHINE_EPSILON_0)
1176 AnimateScrollOvershoot(0.0f);
1180 // Anchoring may be triggered when there was no swipe
1181 if (!mScrollAnimation)
1183 mScrollAnimation = DoAnchoring();
1186 // Reset the overshoot if no scroll animation.
1187 if (!mScrollAnimation)
1189 mScrollCompletedSignal.Emit(GetCurrentScrollPosition());
1191 AnimateScrollOvershoot(0.0f, false);
1196 case Gesture::Started: // Fall through
1198 mTotalPanDisplacement = Vector2::ZERO;
1199 mScrollStartedSignal.Emit(GetCurrentScrollPosition());
1200 mRefreshEnabled = true;
1203 case Gesture::Continuing:
1205 mScrollDistance = CalculateScrollDistance(gesture.displacement, *mActiveLayout);
1206 mScrollSpeed = Clamp((gesture.GetSpeed() * gesture.GetSpeed() * mActiveLayout->GetFlickSpeedFactor() * MILLISECONDS_PER_SECONDS), 0.0f, mActiveLayout->GetMaximumSwipeSpeed());
1208 // Refresh order depends on the direction of the scroll; negative is towards the last item.
1209 mRefreshOrderHint = mScrollDistance < 0.0f;
1211 float layoutPositionDelta = GetCurrentLayoutPosition(0) + (mScrollDistance * mActiveLayout->GetScrollSpeedFactor());
1213 float firstItemScrollPosition = ClampFirstItemPosition(layoutPositionDelta, layoutSize, *mActiveLayout);
1215 float currentOvershoot = self.GetProperty<float>(Toolkit::ItemView::Property::OVERSHOOT);
1217 self.SetProperty(Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1219 if( ( firstItemScrollPosition >= 0.0f &&
1220 currentOvershoot < 1.0f ) ||
1221 ( firstItemScrollPosition <= mActiveLayout->GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), layoutSize) &&
1222 currentOvershoot > -1.0f ) )
1224 mTotalPanDisplacement += gesture.displacement;
1227 mScrollOvershoot = CalculateScrollOvershoot();
1229 // If the view is moved in a direction against the overshoot indicator, then the indicator should be animated off.
1230 // First make sure we are not in an animation, otherwise a previously started
1231 // off-animation will be overwritten as the user continues scrolling.
1234 // Check if the movement is against the current overshoot amount (if we are currently displaying the indicator).
1235 if( ( ( mScrollOvershoot > Math::MACHINE_EPSILON_0 ) && ( mScrollDistance < -Math::MACHINE_EPSILON_0 ) ) ||
1236 ( ( mScrollOvershoot < Math::MACHINE_EPSILON_0 ) && ( mScrollDistance > Math::MACHINE_EPSILON_0 ) ) )
1238 // The user has moved against the indicator direction.
1239 // First, we reset the total displacement. This means the overshoot amount will become zero the next frame,
1240 // and if the user starts dragging in the overshoot direction again, the indicator will appear once more.
1241 mTotalPanDisplacement = Vector2::ZERO;
1242 // Animate the overshoot indicator off.
1243 AnimateScrollOvershoot( 0.0f, false );
1247 // Only set the property directly if we are not animating the overshoot away,
1248 // as otherwise this will overwrite the animation generated value.
1249 self.SetProperty( Toolkit::ItemView::Property::OVERSHOOT, mScrollOvershoot );
1255 case Gesture::Cancelled:
1257 mScrollAnimation = DoAnchoring();
1265 if (mScrollAnimation)
1267 mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
1268 mScrollAnimation.Play();
1272 bool ItemView::OnAccessibilityPan(PanGesture gesture)
1278 Actor ItemView::GetNextKeyboardFocusableActor(Actor actor, Toolkit::Control::KeyboardFocus::Direction direction, bool loopEnabled)
1280 Actor nextFocusActor;
1284 if(!actor || actor == this->Self())
1286 nextFocusActor = GetItem(nextItemID);
1288 else if(actor && actor.GetParent() == this->Self())
1290 int itemID = GetItemId(actor);
1291 nextItemID = mActiveLayout->GetNextFocusItemID(itemID, mItemFactory.GetNumberOfItems(), direction, loopEnabled);
1292 nextFocusActor = GetItem(nextItemID);
1293 if(nextFocusActor == actor)
1295 // need to pass NULL actor back to focus manager
1296 nextFocusActor.Reset();
1297 return nextFocusActor;
1300 float layoutPosition = mActiveLayout->GetClosestAnchorPosition( GetCurrentLayoutPosition(0) );
1301 Vector3 layoutSize = Self().GetCurrentSize();
1304 // likely the current item is not buffered, so not in our item pool, probably best to get first viewable item
1305 ItemRange viewableItems = mActiveLayout->GetItemsWithinArea(layoutPosition, layoutSize);
1306 nextItemID = viewableItems.begin;
1307 nextFocusActor = GetItem(nextItemID);
1310 return nextFocusActor;
1313 void ItemView::OnKeyboardFocusChangeCommitted(Actor commitedFocusableActor)
1315 // only in this function if our chosen focus actor was actually used
1316 if(commitedFocusableActor)
1318 int nextItemID = GetItemId(commitedFocusableActor);
1319 float layoutPosition = GetCurrentLayoutPosition(0);
1320 Vector3 layoutSize = Self().GetCurrentSize();
1322 float scrollTo = mActiveLayout->GetClosestOnScreenLayoutPosition(nextItemID, layoutPosition, layoutSize);
1323 ScrollTo(Vector2(0.0f, scrollTo), DEFAULT_KEYBOARD_FOCUS_SCROLL_DURATION);
1327 Animation ItemView::DoAnchoring()
1329 Animation anchoringAnimation;
1330 Actor self = Self();
1332 if (mActiveLayout && mAnchoringEnabled)
1334 float anchorPosition = mActiveLayout->GetClosestAnchorPosition( GetCurrentLayoutPosition(0) );
1336 anchoringAnimation = Animation::New(mAnchoringDuration);
1337 anchoringAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), anchorPosition, AlphaFunction::EASE_OUT );
1338 anchoringAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::SCROLL_SPEED), 0.0f, AlphaFunction::EASE_OUT );
1341 AnimateScrollOvershoot(0.0f);
1345 return anchoringAnimation;
1348 void ItemView::OnScrollFinished(Animation& source)
1350 Actor self = Self();
1352 RemoveAnimation(mScrollAnimation); // mScrollAnimation is used to query whether we're scrolling
1354 mScrollCompletedSignal.Emit(GetCurrentScrollPosition());
1356 if(mIsFlicking && fabsf(mScrollOvershoot) > Math::MACHINE_EPSILON_1)
1358 AnimateScrollOvershoot( mScrollOvershoot > 0.0f ? 1.0f : -1.0f, true);
1362 // Reset the overshoot
1363 AnimateScrollOvershoot( 0.0f );
1365 mIsFlicking = false;
1367 mScrollOvershoot = 0.0f;
1370 void ItemView::OnLayoutActivationScrollFinished(Animation& source)
1372 RemoveAnimation(mScrollAnimation);
1373 mRefreshEnabled = true;
1374 DoRefresh(GetCurrentLayoutPosition(0), true);
1376 // Emit the layout activated signal
1377 mLayoutActivatedSignal.Emit();
1380 void ItemView::OnOvershootOnFinished(Animation& animation)
1382 mAnimatingOvershootOn = false;
1383 mScrollOvershootAnimation.FinishedSignal().Disconnect(this, &ItemView::OnOvershootOnFinished);
1384 RemoveAnimation(mScrollOvershootAnimation);
1385 if(mAnimateOvershootOff)
1387 AnimateScrollOvershoot(0.0f);
1389 mInAnimation = false;
1392 void ItemView::ScrollToItem(unsigned int itemId, float durationSeconds)
1394 Actor self = Self();
1395 const Vector3 layoutSize = Self().GetCurrentSize();
1396 float firstItemScrollPosition = ClampFirstItemPosition(mActiveLayout->GetItemScrollToPosition(itemId), layoutSize, *mActiveLayout);
1398 if(durationSeconds > 0.0f)
1400 RemoveAnimation(mScrollAnimation);
1401 mScrollAnimation = Animation::New(durationSeconds);
1402 mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), firstItemScrollPosition, mScrollToAlphaFunction );
1403 mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
1404 mScrollAnimation.Play();
1408 self.SetProperty( Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1409 AnimateScrollOvershoot(0.0f);
1412 mScrollStartedSignal.Emit(GetCurrentScrollPosition());
1413 mRefreshEnabled = true;
1416 void ItemView::RemoveAnimation(Animation& animation)
1420 // Cease animating, and reset handle.
1426 void ItemView::CalculateDomainSize(const Vector3& layoutSize)
1428 Actor self = Self();
1430 Vector3 firstItemPosition(Vector3::ZERO);
1431 Vector3 lastItemPosition(Vector3::ZERO);
1435 firstItemPosition = mActiveLayout->GetItemPosition( 0,0,layoutSize );
1437 float minLayoutPosition = mActiveLayout->GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), layoutSize);
1438 lastItemPosition = mActiveLayout->GetItemPosition( fabs(minLayoutPosition),fabs(minLayoutPosition),layoutSize );
1442 if(IsHorizontal(mActiveLayout->GetOrientation()))
1444 domainSize = fabs(firstItemPosition.x - lastItemPosition.x);
1448 domainSize = fabs(firstItemPosition.y - lastItemPosition.y);
1451 self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MIN, Vector2::ZERO);
1452 self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX, Vector2(0.0f, -minLayoutPosition));
1454 self.SetProperty(Toolkit::ItemView::Property::SCROLL_CONTENT_SIZE, domainSize);
1456 bool isLayoutScrollable = IsLayoutScrollable(layoutSize);
1457 self.SetProperty(Toolkit::Scrollable::Property::CAN_SCROLL_VERTICAL, isLayoutScrollable);
1458 self.SetProperty(Toolkit::Scrollable::Property::CAN_SCROLL_HORIZONTAL, false);
1462 bool ItemView::IsLayoutScrollable(const Vector3& layoutSize)
1464 Actor self = Self();
1466 float currentLayoutPosition = ClampFirstItemPosition( GetCurrentLayoutPosition(0), layoutSize, *mActiveLayout, false );
1467 float forwardClampedPosition = ClampFirstItemPosition( currentLayoutPosition + 1.0, layoutSize, *mActiveLayout, false );
1468 float backwardClampedPosition = ClampFirstItemPosition( currentLayoutPosition - 1.0, layoutSize, *mActiveLayout, false );
1470 return (fabs(forwardClampedPosition - backwardClampedPosition) > Math::MACHINE_EPSILON_0);
1473 float ItemView::GetScrollPosition(float layoutPosition, const Vector3& layoutSize) const
1475 Vector3 firstItemPosition( mActiveLayout->GetItemPosition(0, layoutPosition, layoutSize ) );
1476 return IsHorizontal(mActiveLayout->GetOrientation()) ? firstItemPosition.x: firstItemPosition.y;
1479 Vector2 ItemView::GetCurrentScrollPosition() const
1481 return Vector2(0.0f, GetScrollPosition(GetCurrentLayoutPosition(0), Self().GetCurrentSize()));
1484 void ItemView::AddOverlay(Actor actor)
1486 actor.SetDrawMode( DrawMode::OVERLAY_2D );
1490 void ItemView::RemoveOverlay(Actor actor)
1492 Self().Remove(actor);
1495 void ItemView::ScrollTo(const Vector2& position, float duration)
1497 Actor self = Self();
1498 const Vector3 layoutSize = Self().GetCurrentSize();
1500 float firstItemScrollPosition = ClampFirstItemPosition(position.y, layoutSize, *mActiveLayout);
1504 RemoveAnimation(mScrollAnimation);
1505 mScrollAnimation = Animation::New(duration);
1506 mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), firstItemScrollPosition, mScrollToAlphaFunction );
1507 mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
1508 mScrollAnimation.Play();
1512 self.SetProperty( Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1513 AnimateScrollOvershoot(0.0f);
1516 mScrollStartedSignal.Emit(GetCurrentScrollPosition());
1517 mRefreshEnabled = true;
1520 void ItemView::SetOvershootEffectColor( const Vector4& color )
1522 mOvershootEffectColor = color;
1523 if( mOvershootOverlay )
1525 mOvershootOverlay.SetColor( color );
1529 void ItemView::EnableScrollOvershoot( bool enable )
1531 Actor self = Self();
1534 if( !mOvershootOverlay )
1536 Property::Index effectOvershootPropertyIndex = Property::INVALID_INDEX;
1537 mOvershootOverlay = CreateBouncingEffectActor( effectOvershootPropertyIndex );
1538 mOvershootOverlay.SetColor(mOvershootEffectColor);
1539 mOvershootOverlay.SetParentOrigin(ParentOrigin::TOP_LEFT);
1540 mOvershootOverlay.SetAnchorPoint(AnchorPoint::TOP_LEFT);
1541 mOvershootOverlay.SetDrawMode( DrawMode::OVERLAY_2D );
1542 self.Add(mOvershootOverlay);
1544 Constraint constraint = Constraint::New<Vector3>( mOvershootOverlay, Actor::Property::SIZE, OvershootOverlaySizeConstraint(mOvershootSize.height) );
1545 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::SCROLL_DIRECTION ) );
1546 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_ORIENTATION ) );
1547 constraint.AddSource( ParentSource( Actor::Property::SIZE ) );
1550 mOvershootOverlay.SetSize(mOvershootSize.width, mOvershootSize.height);
1552 constraint = Constraint::New<Quaternion>( mOvershootOverlay, Actor::Property::ORIENTATION, OvershootOverlayRotationConstraint );
1553 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::SCROLL_DIRECTION ) );
1554 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_ORIENTATION ) );
1555 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::OVERSHOOT ) );
1558 constraint = Constraint::New<Vector3>( mOvershootOverlay, Actor::Property::POSITION, OvershootOverlayPositionConstraint );
1559 constraint.AddSource( ParentSource( Actor::Property::SIZE ) );
1560 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::SCROLL_DIRECTION ) );
1561 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_ORIENTATION ) );
1562 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::OVERSHOOT ) );
1565 constraint = Constraint::New<bool>( mOvershootOverlay, Actor::Property::VISIBLE, OvershootOverlayVisibilityConstraint );
1566 constraint.AddSource( ParentSource( Toolkit::Scrollable::Property::CAN_SCROLL_VERTICAL ) );
1569 constraint = Constraint::New<float>( mOvershootOverlay, effectOvershootPropertyIndex, EqualToConstraint() );
1570 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::OVERSHOOT ) );
1576 if( mOvershootOverlay )
1578 self.Remove(mOvershootOverlay);
1579 mOvershootOverlay.Reset();
1584 float ItemView::CalculateScrollOvershoot()
1586 float overshoot = 0.0f;
1590 // The overshoot must be calculated from the accumulated pan gesture displacement
1591 // since the pan gesture starts.
1592 Actor self = Self();
1593 float scrollDistance = CalculateScrollDistance(mTotalPanDisplacement, *mActiveLayout) * mActiveLayout->GetScrollSpeedFactor();
1594 float positionDelta = GetCurrentLayoutPosition(0) + scrollDistance;
1595 float minLayoutPosition = mActiveLayout->GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), Self().GetCurrentSize());
1596 self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX, Vector2(0.0f, -minLayoutPosition));
1597 float clamppedPosition = std::min(0.0f, std::max(minLayoutPosition, positionDelta));
1598 overshoot = positionDelta - clamppedPosition;
1601 return overshoot > 0.0f ? std::min(overshoot, 1.0f) : std::max(overshoot, -1.0f);
1604 void ItemView::AnimateScrollOvershoot(float overshootAmount, bool animateBack)
1606 bool animatingOn = fabsf(overshootAmount) > Math::MACHINE_EPSILON_1;
1608 // make sure we animate back if needed
1609 mAnimateOvershootOff = animateBack || (!animatingOn && mAnimatingOvershootOn);
1611 if( mAnimatingOvershootOn )
1613 // animating on, do not allow animate off
1617 Actor self = Self();
1619 if(mOvershootAnimationSpeed > Math::MACHINE_EPSILON_0)
1621 float currentOvershoot = self.GetProperty<float>(Toolkit::ItemView::Property::OVERSHOOT);
1622 float duration = 0.0f;
1624 if (mOvershootOverlay)
1626 duration = mOvershootOverlay.GetCurrentSize().height * (animatingOn ? (1.0f - fabsf(currentOvershoot)) : fabsf(currentOvershoot)) / mOvershootAnimationSpeed;
1629 // Mark the animation as in progress to prevent manual property sets overwriting it.
1630 mInAnimation = true;
1631 mAnimatingOvershootOn = animatingOn;
1632 RemoveAnimation(mScrollOvershootAnimation);
1633 mScrollOvershootAnimation = Animation::New(duration);
1634 mScrollOvershootAnimation.FinishedSignal().Connect(this, &ItemView::OnOvershootOnFinished);
1635 mScrollOvershootAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::OVERSHOOT), overshootAmount, TimePeriod(0.0f, duration) );
1636 mScrollOvershootAnimation.Play();
1640 self.SetProperty( Toolkit::ItemView::Property::OVERSHOOT, overshootAmount );
1644 void ItemView::SetItemsParentOrigin( const Vector3& parentOrigin )
1646 if( parentOrigin != mItemsParentOrigin )
1648 mItemsParentOrigin = parentOrigin;
1649 for (ItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
1651 iter->second.SetParentOrigin(parentOrigin);
1656 Vector3 ItemView::GetItemsParentOrigin() const
1658 return mItemsParentOrigin;
1661 void ItemView::SetItemsAnchorPoint( const Vector3& anchorPoint )
1663 if( anchorPoint != mItemsAnchorPoint )
1665 mItemsAnchorPoint = anchorPoint;
1666 for (ItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
1668 iter->second.SetAnchorPoint(anchorPoint);
1673 Vector3 ItemView::GetItemsAnchorPoint() const
1675 return mItemsAnchorPoint;
1678 void ItemView::GetItemsRange(ItemRange& range)
1680 if( !mItemPool.empty() )
1682 range.begin = mItemPool.begin()->first;
1683 range.end = mItemPool.rbegin()->first + 1;
1692 bool ItemView::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
1694 Dali::BaseHandle handle( object );
1696 bool connected( true );
1697 Toolkit::ItemView itemView = Toolkit::ItemView::DownCast( handle );
1699 if( 0 == strcmp( signalName.c_str(), LAYOUT_ACTIVATED_SIGNAL ) )
1701 itemView.LayoutActivatedSignal().Connect( tracker, functor );
1705 // signalName does not match any signal
1712 void ItemView::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
1714 Toolkit::ItemView itemView = Toolkit::ItemView::DownCast( Dali::BaseHandle( object ) );
1718 ItemView& itemViewImpl( GetImpl( itemView ) );
1721 case Toolkit::ItemView::Property::MINIMUM_SWIPE_SPEED:
1723 itemViewImpl.SetMinimumSwipeSpeed( value.Get<float>() );
1726 case Toolkit::ItemView::Property::MINIMUM_SWIPE_DISTANCE:
1728 itemViewImpl.SetMinimumSwipeDistance( value.Get<float>() );
1731 case Toolkit::ItemView::Property::WHEEL_SCROLL_DISTANCE_STEP:
1733 itemViewImpl.SetWheelScrollDistanceStep( value.Get<float>() );
1736 case Toolkit::ItemView::Property::SNAP_TO_ITEM_ENABLED:
1738 itemViewImpl.SetAnchoring( value.Get<bool>() );
1741 case Toolkit::ItemView::Property::REFRESH_INTERVAL:
1743 itemViewImpl.SetRefreshInterval( value.Get<float>() );
1746 case Toolkit::DevelItemView::Property::LAYOUT:
1748 // Get a Property::Array from the property if possible.
1749 Property::Array layoutArray;
1750 if( value.Get( layoutArray ) )
1752 itemViewImpl.SetLayoutArray( layoutArray );
1760 Property::Array ItemView::GetLayoutArray()
1762 return mlayoutArray;
1765 void ItemView::SetLayoutArray( const Property::Array& layouts )
1767 mlayoutArray = layouts;
1768 if(GetLayoutCount() > 0)
1770 for(unsigned int index = GetLayoutCount() - 1; index >= 0; --index)
1772 RemoveLayout(index);
1773 if(index == 0) break;
1777 for( unsigned int arrayIdx = 0, arrayCount = layouts.Count(); arrayIdx < arrayCount; ++arrayIdx )
1779 const Property::Value& element = layouts.GetElementAt( arrayIdx );
1781 Property::Map* layout = element.GetMap();
1782 if( layout != NULL )
1784 for( unsigned int mapIdx = 0, mapCount = (*layout).Count(); mapIdx < mapCount; ++mapIdx )
1786 KeyValuePair propertyPair( (*layout).GetKeyValue( mapIdx ) );
1788 if(propertyPair.first == DefaultItemLayoutProperty::TYPE)
1790 int layoutType = propertyPair.second.Get<int>();
1791 if(layoutType <= DefaultItemLayout::SPIRAL && layoutType >= DefaultItemLayout::DEPTH)
1793 //DEPTH, GRID, LIST, SPIRAL
1794 switch(DefaultItemLayout::Type(layoutType))
1796 case DefaultItemLayout::DEPTH:
1798 Internal::DepthLayoutPtr depthLayout = Internal::DepthLayout::New();
1799 (*depthLayout).SetLayoutProperties(*layout);
1800 AddLayout(*depthLayout);
1803 case DefaultItemLayout::GRID:
1805 Internal::GridLayoutPtr gridLayout = Internal::GridLayout::New();
1806 (*gridLayout).SetLayoutProperties(*layout);
1807 AddLayout(*gridLayout);
1810 case DefaultItemLayout::LIST:
1812 Internal::GridLayoutPtr listLayout = Internal::GridLayout::New();
1813 listLayout->SetNumberOfColumns( 1 );
1814 (*listLayout).SetLayoutProperties(*layout);
1815 AddLayout(*listLayout);
1818 case DefaultItemLayout::SPIRAL:
1820 Internal::SpiralLayoutPtr spiralLayout = Internal::SpiralLayout::New();
1821 (*spiralLayout).SetLayoutProperties(*layout);
1822 AddLayout(*spiralLayout);
1833 Property::Value ItemView::GetProperty( BaseObject* object, Property::Index index )
1835 Property::Value value;
1837 Toolkit::ItemView itemView = Toolkit::ItemView::DownCast( Dali::BaseHandle( object ) );
1841 ItemView& itemViewImpl( GetImpl( itemView ) );
1844 case Toolkit::ItemView::Property::MINIMUM_SWIPE_SPEED:
1846 value = itemViewImpl.GetMinimumSwipeSpeed();
1849 case Toolkit::ItemView::Property::MINIMUM_SWIPE_DISTANCE:
1851 value = itemViewImpl.GetMinimumSwipeDistance();
1854 case Toolkit::ItemView::Property::WHEEL_SCROLL_DISTANCE_STEP:
1856 value = itemViewImpl.GetWheelScrollDistanceStep();
1859 case Toolkit::ItemView::Property::SNAP_TO_ITEM_ENABLED:
1861 value = itemViewImpl.GetAnchoring();
1864 case Toolkit::ItemView::Property::REFRESH_INTERVAL:
1866 value = itemViewImpl.GetRefreshInterval();
1869 case Toolkit::DevelItemView::Property::LAYOUT:
1871 Property::Array layouts= itemViewImpl.GetLayoutArray();
1882 bool ItemView::DoAction( BaseObject* object, const std::string& actionName, const Property::Map& attributes )
1884 Dali::BaseHandle handle( object );
1886 Toolkit::ItemView itemView = Toolkit::ItemView::DownCast( handle );
1888 DALI_ASSERT_ALWAYS( itemView );
1890 if( 0 == strcmp( actionName.c_str(), ACTION_STOP_SCROLLING ) )
1892 GetImpl( itemView ).DoStopScrolling();
1894 else if ( 0 == strcmp( actionName.c_str(), ACTION_ENABLE_REFRESH ) )
1896 GetImpl( itemView ).SetRefreshNotificationEnabled( true );
1898 else if ( 0 == strcmp( actionName.c_str(), ACTION_DISABLE_REFRESH ) )
1900 GetImpl( itemView ).SetRefreshNotificationEnabled( false );
1906 void ItemView::DoStopScrolling()
1908 if( mScrollAnimation )
1910 mScrollAnimation.Stop();
1911 mScrollAnimation.Reset();
1915 void ItemView::SetRefreshNotificationEnabled( bool enabled )
1917 mRefreshNotificationEnabled = enabled;
1920 } // namespace Internal
1922 } // namespace Toolkit