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;
72 const unsigned int OVERSHOOT_SIZE_CONSTRAINT_TAG(42);
75 * Local helper to convert pan distance (in actor coordinates) to the layout-specific scrolling direction
77 float CalculateScrollDistance(Vector2 panDistance, Toolkit::ItemLayout& layout)
79 Radian scrollDirection(layout.GetScrollDirection());
81 float cosTheta = cosf(scrollDirection);
82 float sinTheta = sinf(scrollDirection);
84 return panDistance.x * sinTheta + panDistance.y * cosTheta;
87 // Overshoot overlay constraints
88 struct OvershootOverlaySizeConstraint
90 OvershootOverlaySizeConstraint( float height )
91 : mOvershootHeight( height )
95 void operator()( Vector3& current, const PropertyInputContainer& inputs )
97 const Vector2& parentScrollDirection = inputs[0]->GetVector2();
98 const Toolkit::ControlOrientation::Type& layoutOrientation = static_cast<Toolkit::ControlOrientation::Type>(inputs[1]->GetInteger());
99 const Vector3& parentSize = inputs[2]->GetVector3();
101 if(Toolkit::IsVertical(layoutOrientation))
103 current.width = fabsf(parentScrollDirection.y) > Math::MACHINE_EPSILON_1 ? parentSize.x : parentSize.y;
107 current.width = fabsf(parentScrollDirection.x) > Math::MACHINE_EPSILON_1 ? parentSize.y : parentSize.x;
110 current.height = ( current.width > OVERSHOOT_BOUNCE_ACTOR_RESIZE_THRESHOLD ) ? mOvershootHeight : mOvershootHeight*0.5f;
113 float mOvershootHeight;
116 void OvershootOverlayRotationConstraint( Quaternion& current, const PropertyInputContainer& inputs )
118 const Vector2& parentScrollDirection = inputs[0]->GetVector2();
119 const Toolkit::ControlOrientation::Type& layoutOrientation = static_cast<Toolkit::ControlOrientation::Type>(inputs[1]->GetInteger());
120 const float parentOvershoot = inputs[2]->GetFloat();
122 float multiplier = 0;
123 if(Toolkit::IsVertical(layoutOrientation))
125 if(fabsf(parentScrollDirection.y) <= Math::MACHINE_EPSILON_1)
127 if( (layoutOrientation == Toolkit::ControlOrientation::Up && parentOvershoot < Math::MACHINE_EPSILON_0)
128 || (layoutOrientation == Toolkit::ControlOrientation::Down && parentOvershoot > Math::MACHINE_EPSILON_0) )
137 else if( (parentOvershoot > Math::MACHINE_EPSILON_0 && parentScrollDirection.y > Math::MACHINE_EPSILON_0)
138 || (parentOvershoot < Math::MACHINE_EPSILON_0 && parentScrollDirection.y < Math::MACHINE_EPSILON_0) )
149 if(fabsf(parentScrollDirection.x) <= Math::MACHINE_EPSILON_1)
151 if( (layoutOrientation == Toolkit::ControlOrientation::Left && parentOvershoot > Math::MACHINE_EPSILON_0)
152 ||(layoutOrientation == Toolkit::ControlOrientation::Right && parentOvershoot < Math::MACHINE_EPSILON_0) )
161 else if( (parentOvershoot > Math::MACHINE_EPSILON_0 && parentScrollDirection.x > Math::MACHINE_EPSILON_0)
162 || (parentOvershoot < Math::MACHINE_EPSILON_0 && parentScrollDirection.x < Math::MACHINE_EPSILON_0) )
172 current = Quaternion( Radian( multiplier * Math::PI ), Vector3::ZAXIS );
175 void OvershootOverlayPositionConstraint( Vector3& current, const PropertyInputContainer& inputs )
177 const Vector3& parentSize = inputs[0]->GetVector3();
178 const Vector2& parentScrollDirection = inputs[1]->GetVector2();
179 const Toolkit::ControlOrientation::Type& layoutOrientation = static_cast<Toolkit::ControlOrientation::Type>(inputs[2]->GetInteger());
180 const float parentOvershoot = inputs[3]->GetFloat();
182 Vector3 relativeOffset;
184 if(Toolkit::IsVertical(layoutOrientation))
186 if(fabsf(parentScrollDirection.y) <= Math::MACHINE_EPSILON_1)
188 if( (layoutOrientation == Toolkit::ControlOrientation::Up && parentOvershoot < Math::MACHINE_EPSILON_0)
189 || (layoutOrientation == Toolkit::ControlOrientation::Down && parentOvershoot > Math::MACHINE_EPSILON_0) )
191 relativeOffset = Vector3(1.0f, 0.0f, 0.0f);
195 relativeOffset =Vector3(0.0f, 1.0f, 0.0f);
198 else if( (parentOvershoot > Math::MACHINE_EPSILON_0 && parentScrollDirection.y > Math::MACHINE_EPSILON_0)
199 || (parentOvershoot < Math::MACHINE_EPSILON_0 && parentScrollDirection.y < Math::MACHINE_EPSILON_0) )
201 relativeOffset = Vector3(0.0f, 0.0f, 0.0f);
205 relativeOffset = Vector3(1.0f, 1.0f, 0.0f);
210 if(fabsf(parentScrollDirection.x) <= Math::MACHINE_EPSILON_1)
212 if( (layoutOrientation == Toolkit::ControlOrientation::Left && parentOvershoot < Math::MACHINE_EPSILON_0)
213 || (layoutOrientation == Toolkit::ControlOrientation::Right && parentOvershoot > Math::MACHINE_EPSILON_0) )
215 relativeOffset = Vector3(0.0f, 0.0f, 0.0f);
219 relativeOffset = Vector3(1.0f, 1.0f, 0.0f);
222 else if( (parentOvershoot > Math::MACHINE_EPSILON_0 && parentScrollDirection.x > Math::MACHINE_EPSILON_0)
223 || (parentOvershoot < Math::MACHINE_EPSILON_0 && parentScrollDirection.x < Math::MACHINE_EPSILON_0) )
225 relativeOffset = Vector3(0.0f, 1.0f, 0.0f);
229 relativeOffset = Vector3(1.0f, 0.0f, 0.0f);
233 current = relativeOffset * parentSize;
236 void OvershootOverlayVisibilityConstraint( bool& current, const PropertyInputContainer& inputs )
238 current = inputs[0]->GetBoolean();
241 } // unnamed namespace
252 namespace // unnamed namespace
257 DALI_TYPE_REGISTRATION_BEGIN( Toolkit::ItemView, Toolkit::Scrollable, NULL)
259 DALI_PROPERTY_REGISTRATION( Toolkit, ItemView, "minimumSwipeSpeed", FLOAT, MINIMUM_SWIPE_SPEED )
260 DALI_PROPERTY_REGISTRATION( Toolkit, ItemView, "minimumSwipeDistance", FLOAT, MINIMUM_SWIPE_DISTANCE )
261 DALI_PROPERTY_REGISTRATION( Toolkit, ItemView, "wheelScrollDistanceStep", FLOAT, WHEEL_SCROLL_DISTANCE_STEP )
262 DALI_PROPERTY_REGISTRATION( Toolkit, ItemView, "snapToItemEnabled", BOOLEAN, SNAP_TO_ITEM_ENABLED )
263 DALI_PROPERTY_REGISTRATION( Toolkit, ItemView, "refreshInterval", FLOAT, REFRESH_INTERVAL )
264 DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, ItemView, "layout", ARRAY, LAYOUT )
267 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "layoutPosition", FLOAT, LAYOUT_POSITION)
268 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "scrollSpeed", FLOAT, SCROLL_SPEED)
269 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "overshoot", FLOAT, OVERSHOOT)
270 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "scrollDirection", VECTOR2, SCROLL_DIRECTION)
271 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "layoutOrientation", INTEGER, LAYOUT_ORIENTATION)
272 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "scrollContentSize", FLOAT, SCROLL_CONTENT_SIZE)
274 DALI_SIGNAL_REGISTRATION( Toolkit, ItemView, "layoutActivated", LAYOUT_ACTIVATED_SIGNAL )
276 DALI_ACTION_REGISTRATION( Toolkit, ItemView, "stopScrolling", ACTION_STOP_SCROLLING )
278 DALI_ACTION_REGISTRATION( Toolkit, ItemView, "enableRefresh", ACTION_ENABLE_REFRESH )
279 DALI_ACTION_REGISTRATION( Toolkit, ItemView, "disableRefresh", ACTION_DISABLE_REFRESH )
281 DALI_TYPE_REGISTRATION_END()
283 bool FindById( const ItemContainer& items, ItemId id )
285 for( ConstItemIter iter = items.begin(); items.end() != iter; ++iter )
287 if( iter->first == id )
297 * Helper to apply size constraint to mOvershootOverlay
298 * @param[in] overshootOverlay The overshootOverlay actor
299 * @param[in] The required height
301 void ApplyOvershootSizeConstraint( Actor overshootOverlay, float height )
303 Constraint constraint = Constraint::New<Vector3>( overshootOverlay, Actor::Property::SIZE, OvershootOverlaySizeConstraint( height ) );
304 constraint.AddSource( ParentSource( Dali::Toolkit::ItemView::Property::SCROLL_DIRECTION ) );
305 constraint.AddSource( ParentSource( Dali::Toolkit::ItemView::Property::LAYOUT_ORIENTATION ) );
306 constraint.AddSource( ParentSource( Dali::Actor::Property::SIZE ) );
307 constraint.SetTag( OVERSHOOT_SIZE_CONSTRAINT_TAG );
311 } // unnamed namespace
313 Dali::Toolkit::ItemView ItemView::New(ItemFactory& factory)
315 // Create the implementation
316 ItemViewPtr itemView(new ItemView(factory));
318 // Pass ownership to CustomActor via derived handle
319 Dali::Toolkit::ItemView handle(*itemView);
321 // Second-phase init of the implementation
322 // This can only be done after the CustomActor connection has been made...
323 itemView->Initialize();
328 ItemView::ItemView(ItemFactory& factory)
329 : Scrollable( ControlBehaviour( DISABLE_SIZE_NEGOTIATION | DISABLE_STYLE_CHANGE_SIGNALS | REQUIRES_WHEEL_EVENTS | REQUIRES_KEYBOARD_NAVIGATION_SUPPORT ) ),
330 mItemFactory(factory),
331 mItemsParentOrigin(ParentOrigin::CENTER),
332 mItemsAnchorPoint(AnchorPoint::CENTER),
333 mTotalPanDisplacement(Vector2::ZERO),
335 mAnchoringDuration(DEFAULT_ANCHORING_DURATION),
336 mRefreshIntervalLayoutPositions(0.0f),
337 mMinimumSwipeSpeed(DEFAULT_MINIMUM_SWIPE_SPEED),
338 mMinimumSwipeDistance(DEFAULT_MINIMUM_SWIPE_DISTANCE),
339 mWheelScrollDistanceStep(0.0f),
340 mScrollDistance(0.0f),
342 mScrollOvershoot(0.0f),
343 mGestureState(Gesture::Clear),
344 mAnimatingOvershootOn(false),
345 mAnimateOvershootOff(false),
346 mAnchoringEnabled(false),
347 mRefreshOrderHint(true/*Refresh item 0 first*/),
350 mRefreshEnabled(true),
351 mRefreshNotificationEnabled(true),
356 void ItemView::OnInitialize()
360 Vector2 stageSize = Stage::GetCurrent().GetSize();
361 mWheelScrollDistanceStep = stageSize.y * DEFAULT_WHEEL_SCROLL_DISTANCE_STEP_PROPORTION;
363 self.TouchSignal().Connect( this, &ItemView::OnTouch );
364 EnableGestureDetection(Gesture::Type(Gesture::Pan));
366 mWheelEventFinishedTimer = Timer::New( WHEEL_EVENT_FINISHED_TIME_OUT );
367 mWheelEventFinishedTimer.TickSignal().Connect( this, &ItemView::OnWheelEventFinished );
369 SetRefreshInterval(DEFAULT_REFRESH_INTERVAL_LAYOUT_POSITIONS);
372 ItemView::~ItemView()
376 unsigned int ItemView::GetLayoutCount() const
378 return mLayouts.size();
381 void ItemView::AddLayout(ItemLayout& layout)
383 mLayouts.push_back(ItemLayoutPtr(&layout));
386 void ItemView::RemoveLayout(unsigned int layoutIndex)
388 DALI_ASSERT_ALWAYS(layoutIndex < mLayouts.size());
390 if (mActiveLayout == mLayouts[layoutIndex].Get())
392 mActiveLayout = NULL;
395 mLayouts.erase(mLayouts.begin() + layoutIndex);
398 ItemLayoutPtr ItemView::GetLayout(unsigned int layoutIndex) const
400 return mLayouts[layoutIndex];
403 ItemLayoutPtr ItemView::GetActiveLayout() const
405 return ItemLayoutPtr(mActiveLayout);
408 float ItemView::GetCurrentLayoutPosition(unsigned int itemId) const
410 return Self().GetProperty<float>( Toolkit::ItemView::Property::LAYOUT_POSITION ) + static_cast<float>( itemId );
413 void ItemView::ActivateLayout(unsigned int layoutIndex, const Vector3& targetSize, float durationSeconds)
415 DALI_ASSERT_ALWAYS(layoutIndex < mLayouts.size());
417 mRefreshEnabled = false;
421 // The ItemView size should match the active layout size
422 self.SetSize(targetSize);
423 mActiveLayoutTargetSize = targetSize;
425 // Switch to the new layout
426 mActiveLayout = mLayouts[layoutIndex].Get();
428 // Move the items to the new layout positions...
430 for (ConstItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
432 unsigned int itemId = iter->first;
433 Actor actor = iter->second;
435 // Remove constraints from previous layout
436 actor.RemoveConstraints();
438 mActiveLayout->ApplyConstraints(actor, itemId, targetSize, Self() );
441 mActiveLayout->GetItemSize( itemId, targetSize, size );
442 actor.SetSize( size.GetVectorXY() );
445 // Refresh the new layout
446 ItemRange range = GetItemRange(*mActiveLayout, targetSize, GetCurrentLayoutPosition(0), false/* don't reserve extra*/);
447 AddActorsWithinRange( range, targetSize );
449 // Scroll to an appropriate layout position
451 bool scrollAnimationNeeded(false);
452 float firstItemScrollPosition(0.0f);
454 float current = GetCurrentLayoutPosition(0);
455 float minimum = ClampFirstItemPosition(current, targetSize, *mActiveLayout);
457 if (current < minimum)
459 scrollAnimationNeeded = true;
460 firstItemScrollPosition = minimum;
462 else if (mAnchoringEnabled)
464 scrollAnimationNeeded = true;
465 firstItemScrollPosition = mActiveLayout->GetClosestAnchorPosition(current);
468 if (scrollAnimationNeeded)
470 RemoveAnimation(mScrollAnimation);
471 mScrollAnimation = Animation::New(durationSeconds);
472 mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), firstItemScrollPosition, AlphaFunction::EASE_OUT );
473 mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnLayoutActivationScrollFinished);
474 mScrollAnimation.Play();
478 // Emit the layout activated signal
479 mLayoutActivatedSignal.Emit();
482 AnimateScrollOvershoot(0.0f);
483 mScrollOvershoot = 0.0f;
485 Radian scrollDirection(mActiveLayout->GetScrollDirection());
486 self.SetProperty(Toolkit::ItemView::Property::SCROLL_DIRECTION, Vector2(sinf(scrollDirection), cosf(scrollDirection)));
487 self.SetProperty(Toolkit::ItemView::Property::LAYOUT_ORIENTATION, static_cast<int>(mActiveLayout->GetOrientation()));
488 self.SetProperty(Toolkit::ItemView::Property::SCROLL_SPEED, mScrollSpeed);
490 CalculateDomainSize(targetSize);
493 void ItemView::DeactivateCurrentLayout()
497 for (ConstItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
499 Actor actor = iter->second;
500 actor.RemoveConstraints();
503 mActiveLayout = NULL;
507 void ItemView::OnRefreshNotification(PropertyNotification& source)
509 if( mRefreshNotificationEnabled )
511 // Cancel scroll animation to prevent any fighting of setting the scroll position property by scroll bar during fast scroll.
512 if(!mRefreshEnabled && mScrollAnimation)
514 RemoveAnimation(mScrollAnimation);
517 // Only cache extra items when it is not a fast scroll
518 DoRefresh(GetCurrentLayoutPosition(0), mRefreshEnabled || mScrollAnimation);
522 void ItemView::Refresh()
524 for (ItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter )
526 ReleaseActor( iter->first, iter->second );
530 DoRefresh(GetCurrentLayoutPosition(0), true);
533 void ItemView::DoRefresh(float currentLayoutPosition, bool cacheExtra)
537 ItemRange range = GetItemRange(*mActiveLayout, mActiveLayoutTargetSize, currentLayoutPosition, cacheExtra/*reserve extra*/);
538 RemoveActorsOutsideRange( range );
539 AddActorsWithinRange( range, Self().GetCurrentSize() );
541 mScrollUpdatedSignal.Emit( Vector2(0.0f, currentLayoutPosition) );
545 void ItemView::SetMinimumSwipeSpeed(float speed)
547 mMinimumSwipeSpeed = speed;
550 float ItemView::GetMinimumSwipeSpeed() const
552 return mMinimumSwipeSpeed;
555 void ItemView::SetMinimumSwipeDistance(float distance)
557 mMinimumSwipeDistance = distance;
560 float ItemView::GetMinimumSwipeDistance() const
562 return mMinimumSwipeDistance;
565 void ItemView::SetWheelScrollDistanceStep(float step)
567 mWheelScrollDistanceStep = step;
570 float ItemView::GetWheelScrollDistanceStep() const
572 return mWheelScrollDistanceStep;
575 void ItemView::SetAnchoring(bool enabled)
577 mAnchoringEnabled = enabled;
580 bool ItemView::GetAnchoring() const
582 return mAnchoringEnabled;
585 void ItemView::SetAnchoringDuration(float durationSeconds)
587 mAnchoringDuration = durationSeconds;
590 float ItemView::GetAnchoringDuration() const
592 return mAnchoringDuration;
595 void ItemView::SetRefreshInterval(float intervalLayoutPositions)
597 if( !Equals(mRefreshIntervalLayoutPositions, intervalLayoutPositions) )
599 mRefreshIntervalLayoutPositions = intervalLayoutPositions;
602 if(mRefreshNotification)
604 self.RemovePropertyNotification(mRefreshNotification);
606 mRefreshNotification = self.AddPropertyNotification( Toolkit::ItemView::Property::LAYOUT_POSITION, StepCondition(mRefreshIntervalLayoutPositions, 0.0f) );
607 mRefreshNotification.NotifySignal().Connect( this, &ItemView::OnRefreshNotification );
611 float ItemView::GetRefreshInterval() const
613 return mRefreshIntervalLayoutPositions;
616 void ItemView::SetRefreshEnabled(bool enabled)
618 mRefreshEnabled = enabled;
621 Actor ItemView::GetItem(unsigned int itemId) const
625 ConstItemPoolIter iter = mItemPool.find( itemId );
626 if( iter != mItemPool.end() )
628 actor = iter->second;
634 unsigned int ItemView::GetItemId( Actor actor ) const
636 unsigned int itemId( 0 );
638 for ( ConstItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter )
640 if( iter->second == actor )
642 itemId = iter->first;
650 void ItemView::InsertItem( Item newItem, float durationSeconds )
653 Vector3 layoutSize = Self().GetCurrentSize();
655 Actor displacedActor;
656 ItemPoolIter afterDisplacedIter = mItemPool.end();
658 ItemPoolIter foundIter = mItemPool.find( newItem.first );
659 if( mItemPool.end() != foundIter )
661 SetupActor( newItem, layoutSize );
662 Self().Add( newItem.second );
664 displacedActor = foundIter->second;
665 foundIter->second = newItem.second;
667 afterDisplacedIter = ++foundIter;
671 // Inserting before the existing item range?
672 ItemPoolIter iter = mItemPool.begin();
673 if( iter != mItemPool.end() &&
674 iter->first > newItem.first )
676 displacedActor = iter->second;
677 mItemPool.erase( iter++ ); // iter is still valid after the erase
679 afterDisplacedIter = iter;
685 // Move the existing actors to make room
686 for( ItemPoolIter iter = afterDisplacedIter; mItemPool.end() != iter; ++iter )
688 Actor temp = iter->second;
689 iter->second = displacedActor;
690 displacedActor = temp;
692 iter->second.RemoveConstraints();
693 mActiveLayout->ApplyConstraints( iter->second, iter->first, layoutSize, Self() );
697 ItemPool::reverse_iterator lastIter = mItemPool.rbegin();
698 if ( lastIter != mItemPool.rend() )
700 ItemId lastId = lastIter->first;
701 Item lastItem( lastId + 1, displacedActor );
702 mItemPool.insert( lastItem );
704 lastItem.second.RemoveConstraints();
705 mActiveLayout->ApplyConstraints( lastItem.second, lastItem.first, layoutSize, Self() );
709 CalculateDomainSize( layoutSize );
711 mAddingItems = false;
714 void ItemView::InsertItems( const ItemContainer& newItems, float durationSeconds )
717 Vector3 layoutSize = Self().GetCurrentSize();
719 // Insert from lowest id to highest
720 std::set<Item> sortedItems;
721 for( ConstItemIter iter = newItems.begin(); newItems.end() != iter; ++iter )
723 sortedItems.insert( *iter );
726 for( std::set<Item>::iterator iter = sortedItems.begin(); sortedItems.end() != iter; ++iter )
728 Self().Add( iter->second );
730 ItemPoolIter foundIter = mItemPool.find( iter->first );
731 if( mItemPool.end() != foundIter )
733 Actor moveMe = foundIter->second;
734 foundIter->second = iter->second;
736 // Move the existing actors to make room
737 for( ItemPoolIter iter = ++foundIter; mItemPool.end() != iter; ++iter )
739 Actor temp = iter->second;
740 iter->second = moveMe;
745 ItemId lastId = mItemPool.rbegin()->first;
746 Item lastItem( lastId + 1, moveMe );
747 mItemPool.insert( lastItem );
751 mItemPool.insert( *iter );
755 // Relayout everything
756 for (ItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
759 if( FindById( newItems, iter->first ) )
761 SetupActor( *iter, layoutSize );
765 iter->second.RemoveConstraints();
766 mActiveLayout->ApplyConstraints( iter->second, iter->first, layoutSize, Self() );
770 CalculateDomainSize( layoutSize );
772 mAddingItems = false;
775 void ItemView::RemoveItem( unsigned int itemId, float durationSeconds )
777 bool actorsReordered = RemoveActor( itemId );
778 if( actorsReordered )
780 ReapplyAllConstraints();
786 void ItemView::RemoveItems( const ItemIdContainer& itemIds, float durationSeconds )
788 bool actorsReordered( false );
790 // Remove from highest id to lowest
791 set<ItemId> sortedItems;
792 for( ConstItemIdIter iter = itemIds.begin(); itemIds.end() != iter; ++iter )
794 sortedItems.insert( *iter );
797 for( set<ItemId>::reverse_iterator iter = sortedItems.rbegin(); sortedItems.rend() != iter; ++iter )
799 if( RemoveActor( *iter ) )
801 actorsReordered = true;
805 if( actorsReordered )
807 ReapplyAllConstraints();
813 bool ItemView::RemoveActor(unsigned int itemId)
815 bool reordered( false );
817 ItemPoolIter removeIter = mItemPool.find( itemId );
818 if( removeIter != mItemPool.end() )
820 ReleaseActor(itemId, removeIter->second);
824 // Removing before the existing item range?
825 ItemPoolIter iter = mItemPool.begin();
826 if( iter != mItemPool.end() &&
827 iter->first > itemId )
829 // In order to decrement the first visible item ID
830 mItemPool.insert( Item(iter->first - 1, Actor()) );
832 removeIter = mItemPool.begin();
836 if( removeIter != mItemPool.end() )
840 // Adjust the remaining item IDs, for example if item 2 is removed:
841 // Initial actors: After insert:
842 // ID 1 - ActorA ID 1 - ActorA
843 // ID 2 - ActorB ID 2 - ActorC (previously ID 3)
844 // ID 3 - ActorC ID 3 - ActorB (previously ID 4)
846 for (ItemPoolIter iter = removeIter; iter != mItemPool.end(); ++iter)
848 if( iter->first < mItemPool.rbegin()->first )
850 iter->second = mItemPool[ iter->first + 1 ];
854 mItemPool.erase( iter );
863 void ItemView::ReplaceItem( Item replacementItem, float durationSeconds )
866 Vector3 layoutSize = Self().GetCurrentSize();
868 SetupActor( replacementItem, layoutSize );
869 Self().Add( replacementItem.second );
871 const ItemPoolIter iter = mItemPool.find( replacementItem.first );
872 if( mItemPool.end() != iter )
874 ReleaseActor(iter->first, iter->second);
875 iter->second = replacementItem.second;
879 mItemPool.insert( replacementItem );
882 CalculateDomainSize( layoutSize );
884 mAddingItems = false;
887 void ItemView::ReplaceItems( const ItemContainer& replacementItems, float durationSeconds )
889 for( ConstItemIter iter = replacementItems.begin(); replacementItems.end() != iter; ++iter )
891 ReplaceItem( *iter, durationSeconds );
895 void ItemView::RemoveActorsOutsideRange( ItemRange range )
897 // Remove unwanted actors from the ItemView & ItemPool
898 for (ItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); )
900 unsigned int current = iter->first;
902 if( ! range.Within( current ) )
904 ReleaseActor(iter->first, iter->second);
906 mItemPool.erase( iter++ ); // erase invalidates the return value of post-increment; iter remains valid
915 void ItemView::AddActorsWithinRange( ItemRange range, const Vector3& layoutSize )
917 range.end = std::min(mItemFactory.GetNumberOfItems(), range.end);
919 // The order of addition depends on the scroll direction.
920 if (mRefreshOrderHint)
922 for (unsigned int itemId = range.begin; itemId < range.end; ++itemId)
924 AddNewActor( itemId, layoutSize );
929 for (unsigned int itemId = range.end; itemId > range.begin; --itemId)
931 AddNewActor( itemId-1, layoutSize );
935 // Total number of items may change dynamically.
936 // Always recalculate the domain size to reflect that.
937 CalculateDomainSize(Self().GetCurrentSize());
940 void ItemView::AddNewActor( unsigned int itemId, const Vector3& layoutSize )
944 if( mItemPool.end() == mItemPool.find( itemId ) )
946 Actor actor = mItemFactory.NewItem( itemId );
950 Item newItem( itemId, actor );
952 mItemPool.insert( newItem );
954 SetupActor( newItem, layoutSize );
959 mAddingItems = false;
962 void ItemView::SetupActor( Item item, const Vector3& layoutSize )
964 item.second.SetParentOrigin( mItemsParentOrigin );
965 item.second.SetAnchorPoint( mItemsAnchorPoint );
970 mActiveLayout->GetItemSize( item.first, mActiveLayoutTargetSize, size );
971 item.second.SetSize( size.GetVectorXY() );
973 mActiveLayout->ApplyConstraints( item.second, item.first, layoutSize, Self() );
977 void ItemView::ReleaseActor( ItemId item, Actor actor )
979 Self().Remove( actor );
980 mItemFactory.ItemReleased(item, actor);
983 ItemRange ItemView::GetItemRange(ItemLayout& layout, const Vector3& layoutSize, float layoutPosition, bool reserveExtra)
985 unsigned int itemCount = mItemFactory.GetNumberOfItems();
987 ItemRange available(0u, itemCount);
989 ItemRange range = layout.GetItemsWithinArea( layoutPosition, layoutSize );
993 // Add the reserve items for scrolling
994 unsigned int extra = layout.GetReserveItemCount(layoutSize);
995 range.begin = (range.begin >= extra) ? (range.begin - extra) : 0u;
999 return range.Intersection(available);
1002 void ItemView::OnChildAdd(Actor& child)
1006 // We don't want to do this downcast check for any item added by ItemView itself.
1007 Dali::Toolkit::ScrollBar scrollBar = Dali::Toolkit::ScrollBar::DownCast(child);
1010 scrollBar.SetScrollPropertySource(Self(),
1011 Toolkit::ItemView::Property::LAYOUT_POSITION,
1012 Toolkit::Scrollable::Property::SCROLL_POSITION_MIN_Y,
1013 Toolkit::Scrollable::Property::SCROLL_POSITION_MAX_Y,
1014 Toolkit::ItemView::Property::SCROLL_CONTENT_SIZE);
1018 Scrollable::OnChildAdd( child );
1021 bool ItemView::OnWheelEvent(const WheelEvent& event)
1023 // Respond the wheel event to scroll
1026 Actor self = Self();
1027 const Vector3 layoutSize = Self().GetCurrentSize();
1028 float layoutPositionDelta = GetCurrentLayoutPosition(0) - (event.z * mWheelScrollDistanceStep * mActiveLayout->GetScrollSpeedFactor());
1029 float firstItemScrollPosition = ClampFirstItemPosition(layoutPositionDelta, layoutSize, *mActiveLayout);
1031 self.SetProperty(Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1033 mScrollStartedSignal.Emit(GetCurrentScrollPosition());
1034 mRefreshEnabled = true;
1037 if (mWheelEventFinishedTimer.IsRunning())
1039 mWheelEventFinishedTimer.Stop();
1042 mWheelEventFinishedTimer.Start();
1047 bool ItemView::OnWheelEventFinished()
1051 RemoveAnimation(mScrollAnimation);
1053 // No more wheel events coming. Do the anchoring if enabled.
1054 mScrollAnimation = DoAnchoring();
1055 if (mScrollAnimation)
1057 mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
1058 mScrollAnimation.Play();
1062 mScrollOvershoot = 0.0f;
1063 AnimateScrollOvershoot(0.0f);
1065 mScrollCompletedSignal.Emit(GetCurrentScrollPosition());
1072 void ItemView::ReapplyAllConstraints()
1074 Vector3 layoutSize = Self().GetCurrentSize();
1076 for (ConstItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
1078 unsigned int id = iter->first;
1079 Actor actor = iter->second;
1081 actor.RemoveConstraints();
1082 mActiveLayout->ApplyConstraints(actor, id, layoutSize, Self());
1086 void ItemView::OnItemsRemoved()
1088 CalculateDomainSize(Self().GetCurrentSize());
1090 // Adjust scroll-position after an item is removed
1093 float firstItemScrollPosition = ClampFirstItemPosition(GetCurrentLayoutPosition(0), Self().GetCurrentSize(), *mActiveLayout);
1094 Self().SetProperty( Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1098 float ItemView::ClampFirstItemPosition( float targetPosition, const Vector3& targetSize, ItemLayout& layout, bool updateOvershoot )
1100 Actor self = Self();
1101 float minLayoutPosition = layout.GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), targetSize);
1102 float clamppedPosition = std::min(0.0f, std::max(minLayoutPosition, targetPosition));
1103 self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX, Vector2(0.0f, -minLayoutPosition));
1105 if( updateOvershoot )
1107 mScrollOvershoot = targetPosition - clamppedPosition;
1110 return clamppedPosition;
1113 bool ItemView::OnTouch( Actor actor, const TouchData& touch )
1115 // Ignore events with multiple-touch points
1116 if (touch.GetPointCount() != 1)
1121 if ( touch.GetState( 0 ) == PointState::DOWN )
1123 // Cancel ongoing scrolling etc.
1124 mGestureState = Gesture::Clear;
1126 mScrollDistance = 0.0f;
1127 mScrollSpeed = 0.0f;
1128 Self().SetProperty(Toolkit::ItemView::Property::SCROLL_SPEED, mScrollSpeed);
1130 mScrollOvershoot = 0.0f;
1131 AnimateScrollOvershoot(0.0f);
1133 if(mScrollAnimation)
1135 mScrollCompletedSignal.Emit(GetCurrentScrollPosition());
1138 RemoveAnimation(mScrollAnimation);
1141 return true; // consume since we're potentially scrolling
1144 void ItemView::OnPan( const PanGesture& gesture )
1146 Actor self = Self();
1147 const Vector3 layoutSize = Self().GetCurrentSize();
1149 RemoveAnimation(mScrollAnimation);
1151 // Short-circuit if there is no active layout
1154 mGestureState = Gesture::Clear;
1158 mGestureState = gesture.state;
1160 switch (mGestureState)
1162 case Gesture::Finished:
1165 if (fabsf(mScrollDistance) > mMinimumSwipeDistance &&
1166 mScrollSpeed > mMinimumSwipeSpeed)
1168 float direction = (mScrollDistance < 0.0f) ? -1.0f : 1.0f;
1170 mRefreshOrderHint = true;
1172 float currentLayoutPosition = GetCurrentLayoutPosition(0);
1173 float firstItemScrollPosition = ClampFirstItemPosition(currentLayoutPosition + mScrollSpeed * direction,
1177 if (mAnchoringEnabled)
1179 firstItemScrollPosition = mActiveLayout->GetClosestAnchorPosition(firstItemScrollPosition);
1182 RemoveAnimation(mScrollAnimation);
1184 float flickAnimationDuration = Clamp( mActiveLayout->GetItemFlickAnimationDuration() * std::max(1.0f, fabsf(firstItemScrollPosition - GetCurrentLayoutPosition(0)))
1185 , DEFAULT_MINIMUM_SWIPE_DURATION, DEFAULT_MAXIMUM_SWIPE_DURATION);
1187 mScrollAnimation = Animation::New(flickAnimationDuration);
1188 mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION ), firstItemScrollPosition, AlphaFunction::EASE_OUT );
1189 mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::SCROLL_SPEED), 0.0f, AlphaFunction::EASE_OUT );
1192 // Check whether it has already scrolled to the end
1193 if(fabs(currentLayoutPosition - firstItemScrollPosition) > Math::MACHINE_EPSILON_0)
1195 AnimateScrollOvershoot(0.0f);
1199 // Anchoring may be triggered when there was no swipe
1200 if (!mScrollAnimation)
1202 mScrollAnimation = DoAnchoring();
1205 // Reset the overshoot if no scroll animation.
1206 if (!mScrollAnimation)
1208 mScrollCompletedSignal.Emit(GetCurrentScrollPosition());
1210 AnimateScrollOvershoot(0.0f, false);
1215 case Gesture::Started: // Fall through
1217 mTotalPanDisplacement = Vector2::ZERO;
1218 mScrollStartedSignal.Emit(GetCurrentScrollPosition());
1219 mRefreshEnabled = true;
1222 case Gesture::Continuing:
1224 mScrollDistance = CalculateScrollDistance(gesture.displacement, *mActiveLayout);
1225 mScrollSpeed = Clamp((gesture.GetSpeed() * gesture.GetSpeed() * mActiveLayout->GetFlickSpeedFactor() * MILLISECONDS_PER_SECONDS), 0.0f, mActiveLayout->GetMaximumSwipeSpeed());
1227 // Refresh order depends on the direction of the scroll; negative is towards the last item.
1228 mRefreshOrderHint = mScrollDistance < 0.0f;
1230 float layoutPositionDelta = GetCurrentLayoutPosition(0) + (mScrollDistance * mActiveLayout->GetScrollSpeedFactor());
1232 float firstItemScrollPosition = ClampFirstItemPosition(layoutPositionDelta, layoutSize, *mActiveLayout);
1234 float currentOvershoot = self.GetProperty<float>(Toolkit::ItemView::Property::OVERSHOOT);
1236 self.SetProperty(Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1238 if( ( firstItemScrollPosition >= 0.0f &&
1239 currentOvershoot < 1.0f ) ||
1240 ( firstItemScrollPosition <= mActiveLayout->GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), layoutSize) &&
1241 currentOvershoot > -1.0f ) )
1243 mTotalPanDisplacement += gesture.displacement;
1246 mScrollOvershoot = CalculateScrollOvershoot();
1248 // If the view is moved in a direction against the overshoot indicator, then the indicator should be animated off.
1249 // First make sure we are not in an animation, otherwise a previously started
1250 // off-animation will be overwritten as the user continues scrolling.
1253 // Check if the movement is against the current overshoot amount (if we are currently displaying the indicator).
1254 if( ( ( mScrollOvershoot > Math::MACHINE_EPSILON_0 ) && ( mScrollDistance < -Math::MACHINE_EPSILON_0 ) ) ||
1255 ( ( mScrollOvershoot < Math::MACHINE_EPSILON_0 ) && ( mScrollDistance > Math::MACHINE_EPSILON_0 ) ) )
1257 // The user has moved against the indicator direction.
1258 // First, we reset the total displacement. This means the overshoot amount will become zero the next frame,
1259 // and if the user starts dragging in the overshoot direction again, the indicator will appear once more.
1260 mTotalPanDisplacement = Vector2::ZERO;
1261 // Animate the overshoot indicator off.
1262 AnimateScrollOvershoot( 0.0f, false );
1266 // Only set the property directly if we are not animating the overshoot away,
1267 // as otherwise this will overwrite the animation generated value.
1268 self.SetProperty( Toolkit::ItemView::Property::OVERSHOOT, mScrollOvershoot );
1274 case Gesture::Cancelled:
1276 mScrollAnimation = DoAnchoring();
1284 if (mScrollAnimation)
1286 mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
1287 mScrollAnimation.Play();
1291 bool ItemView::OnAccessibilityPan(PanGesture gesture)
1297 Actor ItemView::GetNextKeyboardFocusableActor(Actor actor, Toolkit::Control::KeyboardFocus::Direction direction, bool loopEnabled)
1299 Actor nextFocusActor;
1303 if(!actor || actor == this->Self())
1305 nextFocusActor = GetItem(nextItemID);
1307 else if(actor && actor.GetParent() == this->Self())
1309 int itemID = GetItemId(actor);
1310 nextItemID = mActiveLayout->GetNextFocusItemID(itemID, mItemFactory.GetNumberOfItems(), direction, loopEnabled);
1311 nextFocusActor = GetItem(nextItemID);
1312 if(nextFocusActor == actor)
1314 // need to pass NULL actor back to focus manager
1315 nextFocusActor.Reset();
1316 return nextFocusActor;
1319 float layoutPosition = mActiveLayout->GetClosestAnchorPosition( GetCurrentLayoutPosition(0) );
1320 Vector3 layoutSize = Self().GetCurrentSize();
1323 // likely the current item is not buffered, so not in our item pool, probably best to get first viewable item
1324 ItemRange viewableItems = mActiveLayout->GetItemsWithinArea(layoutPosition, layoutSize);
1325 nextItemID = viewableItems.begin;
1326 nextFocusActor = GetItem(nextItemID);
1329 return nextFocusActor;
1332 void ItemView::OnKeyboardFocusChangeCommitted(Actor commitedFocusableActor)
1334 // only in this function if our chosen focus actor was actually used
1335 if(commitedFocusableActor)
1337 int nextItemID = GetItemId(commitedFocusableActor);
1338 float layoutPosition = GetCurrentLayoutPosition(0);
1339 Vector3 layoutSize = Self().GetCurrentSize();
1341 float scrollTo = mActiveLayout->GetClosestOnScreenLayoutPosition(nextItemID, layoutPosition, layoutSize);
1342 ScrollTo(Vector2(0.0f, scrollTo), DEFAULT_KEYBOARD_FOCUS_SCROLL_DURATION);
1346 Animation ItemView::DoAnchoring()
1348 Animation anchoringAnimation;
1349 Actor self = Self();
1351 if (mActiveLayout && mAnchoringEnabled)
1353 float anchorPosition = mActiveLayout->GetClosestAnchorPosition( GetCurrentLayoutPosition(0) );
1355 anchoringAnimation = Animation::New(mAnchoringDuration);
1356 anchoringAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), anchorPosition, AlphaFunction::EASE_OUT );
1357 anchoringAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::SCROLL_SPEED), 0.0f, AlphaFunction::EASE_OUT );
1360 AnimateScrollOvershoot(0.0f);
1364 return anchoringAnimation;
1367 void ItemView::OnScrollFinished(Animation& source)
1369 Actor self = Self();
1371 RemoveAnimation(mScrollAnimation); // mScrollAnimation is used to query whether we're scrolling
1373 mScrollCompletedSignal.Emit(GetCurrentScrollPosition());
1375 if(mIsFlicking && fabsf(mScrollOvershoot) > Math::MACHINE_EPSILON_1)
1377 AnimateScrollOvershoot( mScrollOvershoot > 0.0f ? 1.0f : -1.0f, true);
1381 // Reset the overshoot
1382 AnimateScrollOvershoot( 0.0f );
1384 mIsFlicking = false;
1386 mScrollOvershoot = 0.0f;
1389 void ItemView::OnLayoutActivationScrollFinished(Animation& source)
1391 RemoveAnimation(mScrollAnimation);
1392 mRefreshEnabled = true;
1393 DoRefresh(GetCurrentLayoutPosition(0), true);
1395 // Emit the layout activated signal
1396 mLayoutActivatedSignal.Emit();
1399 void ItemView::OnOvershootOnFinished(Animation& animation)
1401 mAnimatingOvershootOn = false;
1402 mScrollOvershootAnimation.FinishedSignal().Disconnect(this, &ItemView::OnOvershootOnFinished);
1403 RemoveAnimation(mScrollOvershootAnimation);
1404 if(mAnimateOvershootOff)
1406 AnimateScrollOvershoot(0.0f);
1408 mInAnimation = false;
1411 void ItemView::ScrollToItem(unsigned int itemId, float durationSeconds)
1413 Actor self = Self();
1414 const Vector3 layoutSize = Self().GetCurrentSize();
1415 float firstItemScrollPosition = ClampFirstItemPosition(mActiveLayout->GetItemScrollToPosition(itemId), layoutSize, *mActiveLayout);
1417 if(durationSeconds > 0.0f)
1419 RemoveAnimation(mScrollAnimation);
1420 mScrollAnimation = Animation::New(durationSeconds);
1421 mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), firstItemScrollPosition, mScrollToAlphaFunction );
1422 mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
1423 mScrollAnimation.Play();
1427 self.SetProperty( Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1428 AnimateScrollOvershoot(0.0f);
1431 mScrollStartedSignal.Emit(GetCurrentScrollPosition());
1432 mRefreshEnabled = true;
1435 void ItemView::RemoveAnimation(Animation& animation)
1439 // Cease animating, and reset handle.
1445 void ItemView::CalculateDomainSize(const Vector3& layoutSize)
1447 Actor self = Self();
1449 Vector3 firstItemPosition(Vector3::ZERO);
1450 Vector3 lastItemPosition(Vector3::ZERO);
1454 firstItemPosition = mActiveLayout->GetItemPosition( 0,0,layoutSize );
1456 float minLayoutPosition = mActiveLayout->GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), layoutSize);
1457 lastItemPosition = mActiveLayout->GetItemPosition( fabs(minLayoutPosition),fabs(minLayoutPosition),layoutSize );
1461 if(IsHorizontal(mActiveLayout->GetOrientation()))
1463 domainSize = fabs(firstItemPosition.x - lastItemPosition.x);
1467 domainSize = fabs(firstItemPosition.y - lastItemPosition.y);
1470 self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MIN, Vector2::ZERO);
1471 self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX, Vector2(0.0f, -minLayoutPosition));
1473 self.SetProperty(Toolkit::ItemView::Property::SCROLL_CONTENT_SIZE, domainSize);
1475 bool isLayoutScrollable = IsLayoutScrollable(layoutSize);
1476 self.SetProperty(Toolkit::Scrollable::Property::CAN_SCROLL_VERTICAL, isLayoutScrollable);
1477 self.SetProperty(Toolkit::Scrollable::Property::CAN_SCROLL_HORIZONTAL, false);
1481 bool ItemView::IsLayoutScrollable(const Vector3& layoutSize)
1483 Actor self = Self();
1485 float currentLayoutPosition = ClampFirstItemPosition( GetCurrentLayoutPosition(0), layoutSize, *mActiveLayout, false );
1486 float forwardClampedPosition = ClampFirstItemPosition( currentLayoutPosition + 1.0, layoutSize, *mActiveLayout, false );
1487 float backwardClampedPosition = ClampFirstItemPosition( currentLayoutPosition - 1.0, layoutSize, *mActiveLayout, false );
1489 return (fabs(forwardClampedPosition - backwardClampedPosition) > Math::MACHINE_EPSILON_0);
1492 float ItemView::GetScrollPosition(float layoutPosition, const Vector3& layoutSize) const
1494 Vector3 firstItemPosition( mActiveLayout->GetItemPosition(0, layoutPosition, layoutSize ) );
1495 return IsHorizontal(mActiveLayout->GetOrientation()) ? firstItemPosition.x: firstItemPosition.y;
1498 Vector2 ItemView::GetCurrentScrollPosition() const
1500 return Vector2(0.0f, GetScrollPosition(GetCurrentLayoutPosition(0), Self().GetCurrentSize()));
1503 void ItemView::AddOverlay(Actor actor)
1505 actor.SetDrawMode( DrawMode::OVERLAY_2D );
1509 void ItemView::RemoveOverlay(Actor actor)
1511 Self().Remove(actor);
1514 void ItemView::ScrollTo(const Vector2& position, float duration)
1516 Actor self = Self();
1517 const Vector3 layoutSize = Self().GetCurrentSize();
1519 float firstItemScrollPosition = ClampFirstItemPosition(position.y, layoutSize, *mActiveLayout);
1523 RemoveAnimation(mScrollAnimation);
1524 mScrollAnimation = Animation::New(duration);
1525 mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), firstItemScrollPosition, mScrollToAlphaFunction );
1526 mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
1527 mScrollAnimation.Play();
1531 self.SetProperty( Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1532 AnimateScrollOvershoot(0.0f);
1535 mScrollStartedSignal.Emit(GetCurrentScrollPosition());
1536 mRefreshEnabled = true;
1539 void ItemView::SetOvershootSize( const Vector2& size )
1541 mOvershootSize = size;
1543 if( mOvershootOverlay )
1545 // Remove old & add new size constraint
1546 mOvershootOverlay.RemoveConstraints( OVERSHOOT_SIZE_CONSTRAINT_TAG );
1547 ApplyOvershootSizeConstraint( mOvershootOverlay, mOvershootSize.height );
1551 void ItemView::SetOvershootEffectColor( const Vector4& color )
1553 mOvershootEffectColor = color;
1554 if( mOvershootOverlay )
1556 mOvershootOverlay.SetColor( color );
1560 void ItemView::EnableScrollOvershoot( bool enable )
1562 Actor self = Self();
1565 if( !mOvershootOverlay )
1567 Property::Index effectOvershootPropertyIndex = Property::INVALID_INDEX;
1568 mOvershootOverlay = CreateBouncingEffectActor( effectOvershootPropertyIndex );
1569 mOvershootOverlay.SetColor(mOvershootEffectColor);
1570 mOvershootOverlay.SetParentOrigin(ParentOrigin::TOP_LEFT);
1571 mOvershootOverlay.SetAnchorPoint(AnchorPoint::TOP_LEFT);
1572 mOvershootOverlay.SetDrawMode( DrawMode::OVERLAY_2D );
1573 self.Add(mOvershootOverlay);
1575 ApplyOvershootSizeConstraint( mOvershootOverlay, mOvershootSize.height );
1577 Constraint constraint = Constraint::New<Quaternion>( mOvershootOverlay, Actor::Property::ORIENTATION, OvershootOverlayRotationConstraint );
1578 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::SCROLL_DIRECTION ) );
1579 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_ORIENTATION ) );
1580 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::OVERSHOOT ) );
1583 constraint = Constraint::New<Vector3>( mOvershootOverlay, Actor::Property::POSITION, OvershootOverlayPositionConstraint );
1584 constraint.AddSource( ParentSource( Actor::Property::SIZE ) );
1585 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::SCROLL_DIRECTION ) );
1586 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_ORIENTATION ) );
1587 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::OVERSHOOT ) );
1590 constraint = Constraint::New<bool>( mOvershootOverlay, Actor::Property::VISIBLE, OvershootOverlayVisibilityConstraint );
1591 constraint.AddSource( ParentSource( Toolkit::Scrollable::Property::CAN_SCROLL_VERTICAL ) );
1594 constraint = Constraint::New<float>( mOvershootOverlay, effectOvershootPropertyIndex, EqualToConstraint() );
1595 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::OVERSHOOT ) );
1601 if( mOvershootOverlay )
1603 self.Remove(mOvershootOverlay);
1604 mOvershootOverlay.Reset();
1609 float ItemView::CalculateScrollOvershoot()
1611 float overshoot = 0.0f;
1615 // The overshoot must be calculated from the accumulated pan gesture displacement
1616 // since the pan gesture starts.
1617 Actor self = Self();
1618 float scrollDistance = CalculateScrollDistance(mTotalPanDisplacement, *mActiveLayout) * mActiveLayout->GetScrollSpeedFactor();
1619 float positionDelta = GetCurrentLayoutPosition(0) + scrollDistance;
1620 float minLayoutPosition = mActiveLayout->GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), Self().GetCurrentSize());
1621 self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX, Vector2(0.0f, -minLayoutPosition));
1622 float clamppedPosition = std::min(0.0f, std::max(minLayoutPosition, positionDelta));
1623 overshoot = positionDelta - clamppedPosition;
1626 return overshoot > 0.0f ? std::min(overshoot, 1.0f) : std::max(overshoot, -1.0f);
1629 void ItemView::AnimateScrollOvershoot(float overshootAmount, bool animateBack)
1631 bool animatingOn = fabsf(overshootAmount) > Math::MACHINE_EPSILON_1;
1633 // make sure we animate back if needed
1634 mAnimateOvershootOff = animateBack || (!animatingOn && mAnimatingOvershootOn);
1636 if( mAnimatingOvershootOn )
1638 // animating on, do not allow animate off
1642 Actor self = Self();
1644 if(mOvershootAnimationSpeed > Math::MACHINE_EPSILON_0)
1646 float currentOvershoot = self.GetProperty<float>(Toolkit::ItemView::Property::OVERSHOOT);
1647 float duration = 0.0f;
1649 if (mOvershootOverlay)
1651 duration = mOvershootOverlay.GetCurrentSize().height * (animatingOn ? (1.0f - fabsf(currentOvershoot)) : fabsf(currentOvershoot)) / mOvershootAnimationSpeed;
1654 // Mark the animation as in progress to prevent manual property sets overwriting it.
1655 mInAnimation = true;
1656 mAnimatingOvershootOn = animatingOn;
1657 RemoveAnimation(mScrollOvershootAnimation);
1658 mScrollOvershootAnimation = Animation::New(duration);
1659 mScrollOvershootAnimation.FinishedSignal().Connect(this, &ItemView::OnOvershootOnFinished);
1660 mScrollOvershootAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::OVERSHOOT), overshootAmount, TimePeriod(0.0f, duration) );
1661 mScrollOvershootAnimation.Play();
1665 self.SetProperty( Toolkit::ItemView::Property::OVERSHOOT, overshootAmount );
1669 void ItemView::SetItemsParentOrigin( const Vector3& parentOrigin )
1671 if( parentOrigin != mItemsParentOrigin )
1673 mItemsParentOrigin = parentOrigin;
1674 for (ItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
1676 iter->second.SetParentOrigin(parentOrigin);
1681 Vector3 ItemView::GetItemsParentOrigin() const
1683 return mItemsParentOrigin;
1686 void ItemView::SetItemsAnchorPoint( const Vector3& anchorPoint )
1688 if( anchorPoint != mItemsAnchorPoint )
1690 mItemsAnchorPoint = anchorPoint;
1691 for (ItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
1693 iter->second.SetAnchorPoint(anchorPoint);
1698 Vector3 ItemView::GetItemsAnchorPoint() const
1700 return mItemsAnchorPoint;
1703 void ItemView::GetItemsRange(ItemRange& range)
1705 if( !mItemPool.empty() )
1707 range.begin = mItemPool.begin()->first;
1708 range.end = mItemPool.rbegin()->first + 1;
1717 bool ItemView::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
1719 Dali::BaseHandle handle( object );
1721 bool connected( true );
1722 Toolkit::ItemView itemView = Toolkit::ItemView::DownCast( handle );
1724 if( 0 == strcmp( signalName.c_str(), LAYOUT_ACTIVATED_SIGNAL ) )
1726 itemView.LayoutActivatedSignal().Connect( tracker, functor );
1730 // signalName does not match any signal
1737 void ItemView::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
1739 Toolkit::ItemView itemView = Toolkit::ItemView::DownCast( Dali::BaseHandle( object ) );
1743 ItemView& itemViewImpl( GetImpl( itemView ) );
1746 case Toolkit::ItemView::Property::MINIMUM_SWIPE_SPEED:
1748 itemViewImpl.SetMinimumSwipeSpeed( value.Get<float>() );
1751 case Toolkit::ItemView::Property::MINIMUM_SWIPE_DISTANCE:
1753 itemViewImpl.SetMinimumSwipeDistance( value.Get<float>() );
1756 case Toolkit::ItemView::Property::WHEEL_SCROLL_DISTANCE_STEP:
1758 itemViewImpl.SetWheelScrollDistanceStep( value.Get<float>() );
1761 case Toolkit::ItemView::Property::SNAP_TO_ITEM_ENABLED:
1763 itemViewImpl.SetAnchoring( value.Get<bool>() );
1766 case Toolkit::ItemView::Property::REFRESH_INTERVAL:
1768 itemViewImpl.SetRefreshInterval( value.Get<float>() );
1771 case Toolkit::DevelItemView::Property::LAYOUT:
1773 // Get a Property::Array from the property if possible.
1774 Property::Array layoutArray;
1775 if( value.Get( layoutArray ) )
1777 itemViewImpl.SetLayoutArray( layoutArray );
1785 Property::Array ItemView::GetLayoutArray()
1787 return mlayoutArray;
1790 void ItemView::SetLayoutArray( const Property::Array& layouts )
1792 mlayoutArray = layouts;
1793 const int layoutCount = GetLayoutCount();
1794 if( layoutCount > 0 )
1796 for(int index = layoutCount - 1; index >= 0; --index)
1798 RemoveLayout(index);
1799 if(index == 0) break;
1803 for( unsigned int arrayIdx = 0, arrayCount = layouts.Count(); arrayIdx < arrayCount; ++arrayIdx )
1805 const Property::Value& element = layouts.GetElementAt( arrayIdx );
1807 Property::Map* layout = element.GetMap();
1808 if( layout != NULL )
1810 for( unsigned int mapIdx = 0, mapCount = (*layout).Count(); mapIdx < mapCount; ++mapIdx )
1812 KeyValuePair propertyPair( (*layout).GetKeyValue( mapIdx ) );
1814 if(propertyPair.first == DefaultItemLayoutProperty::TYPE)
1816 int layoutType = propertyPair.second.Get<int>();
1817 if(layoutType <= DefaultItemLayout::SPIRAL && layoutType >= DefaultItemLayout::DEPTH)
1819 //DEPTH, GRID, LIST, SPIRAL
1820 switch(DefaultItemLayout::Type(layoutType))
1822 case DefaultItemLayout::DEPTH:
1824 Internal::DepthLayoutPtr depthLayout = Internal::DepthLayout::New();
1825 (*depthLayout).SetLayoutProperties(*layout);
1826 (*depthLayout).SetDepthLayoutProperties(*layout);
1827 AddLayout(*depthLayout);
1830 case DefaultItemLayout::GRID:
1832 Internal::GridLayoutPtr gridLayout = Internal::GridLayout::New();
1833 (*gridLayout).SetLayoutProperties(*layout);
1834 (*gridLayout).SetGridLayoutProperties(*layout);
1835 AddLayout(*gridLayout);
1838 case DefaultItemLayout::LIST:
1840 Internal::GridLayoutPtr listLayout = Internal::GridLayout::New();
1841 listLayout->SetNumberOfColumns( 1 );
1842 (*listLayout).SetLayoutProperties(*layout);
1843 (*listLayout).SetGridLayoutProperties(*layout);
1844 AddLayout(*listLayout);
1847 case DefaultItemLayout::SPIRAL:
1849 Internal::SpiralLayoutPtr spiralLayout = Internal::SpiralLayout::New();
1850 (*spiralLayout).SetLayoutProperties(*layout);
1851 (*spiralLayout).SetSpiralLayoutProperties(*layout);
1852 AddLayout(*spiralLayout);
1863 Property::Value ItemView::GetProperty( BaseObject* object, Property::Index index )
1865 Property::Value value;
1867 Toolkit::ItemView itemView = Toolkit::ItemView::DownCast( Dali::BaseHandle( object ) );
1871 ItemView& itemViewImpl( GetImpl( itemView ) );
1874 case Toolkit::ItemView::Property::MINIMUM_SWIPE_SPEED:
1876 value = itemViewImpl.GetMinimumSwipeSpeed();
1879 case Toolkit::ItemView::Property::MINIMUM_SWIPE_DISTANCE:
1881 value = itemViewImpl.GetMinimumSwipeDistance();
1884 case Toolkit::ItemView::Property::WHEEL_SCROLL_DISTANCE_STEP:
1886 value = itemViewImpl.GetWheelScrollDistanceStep();
1889 case Toolkit::ItemView::Property::SNAP_TO_ITEM_ENABLED:
1891 value = itemViewImpl.GetAnchoring();
1894 case Toolkit::ItemView::Property::REFRESH_INTERVAL:
1896 value = itemViewImpl.GetRefreshInterval();
1899 case Toolkit::DevelItemView::Property::LAYOUT:
1901 Property::Array layouts= itemViewImpl.GetLayoutArray();
1912 bool ItemView::DoAction( BaseObject* object, const std::string& actionName, const Property::Map& attributes )
1914 Dali::BaseHandle handle( object );
1916 Toolkit::ItemView itemView = Toolkit::ItemView::DownCast( handle );
1918 DALI_ASSERT_ALWAYS( itemView );
1920 if( 0 == strcmp( actionName.c_str(), ACTION_STOP_SCROLLING ) )
1922 GetImpl( itemView ).DoStopScrolling();
1924 else if ( 0 == strcmp( actionName.c_str(), ACTION_ENABLE_REFRESH ) )
1926 GetImpl( itemView ).SetRefreshNotificationEnabled( true );
1928 else if ( 0 == strcmp( actionName.c_str(), ACTION_DISABLE_REFRESH ) )
1930 GetImpl( itemView ).SetRefreshNotificationEnabled( false );
1936 void ItemView::DoStopScrolling()
1938 if( mScrollAnimation )
1940 mScrollAnimation.Stop();
1941 mScrollAnimation.Reset();
1945 void ItemView::SetRefreshNotificationEnabled( bool enabled )
1947 mRefreshNotificationEnabled = enabled;
1950 } // namespace Internal
1952 } // namespace Toolkit