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>
35 #include <dali/devel-api/object/handle-devel.h>
38 #include <dali-toolkit/public-api/controls/scroll-bar/scroll-bar.h>
39 #include <dali-toolkit/public-api/controls/scrollable/item-view/item-factory.h>
40 #include <dali-toolkit/public-api/controls/scrollable/item-view/default-item-layout.h>
41 #include <dali-toolkit/devel-api/controls/scrollable/item-view/default-item-layout-property.h>
42 #include <dali-toolkit/devel-api/controls/scrollable/item-view/item-view-devel.h>
43 #include <dali-toolkit/internal/controls/scrollable/item-view/grid-layout.h>
44 #include <dali-toolkit/internal/controls/scrollable/item-view/depth-layout.h>
45 #include <dali-toolkit/internal/controls/scrollable/item-view/spiral-layout.h>
46 #include <dali-toolkit/internal/controls/scrollable/bouncing-effect-actor.h>
52 namespace // Unnamed namespace
55 const float DEFAULT_MINIMUM_SWIPE_SPEED = 1.0f;
56 const float DEFAULT_MINIMUM_SWIPE_DISTANCE = 3.0f;
57 const float DEFAULT_WHEEL_SCROLL_DISTANCE_STEP_PROPORTION = 0.1f;
59 const float DEFAULT_MINIMUM_SWIPE_DURATION = 0.45f;
60 const float DEFAULT_MAXIMUM_SWIPE_DURATION = 2.6f;
62 const float DEFAULT_REFRESH_INTERVAL_LAYOUT_POSITIONS = 20.0f; // 1 updates per 20 items
63 const int WHEEL_EVENT_FINISHED_TIME_OUT = 500; // 0.5 second
65 const float DEFAULT_ANCHORING_DURATION = 1.0f; // 1 second
67 const float MILLISECONDS_PER_SECONDS = 1000.0f;
69 const float OVERSHOOT_BOUNCE_ACTOR_RESIZE_THRESHOLD = 180.0f;
70 const Vector4 OVERSHOOT_OVERLAY_NINE_PATCH_BORDER(0.0f, 0.0f, 1.0f, 12.0f);
71 const float DEFAULT_KEYBOARD_FOCUS_SCROLL_DURATION = 0.2f;
73 const unsigned int OVERSHOOT_SIZE_CONSTRAINT_TAG(42);
76 * Local helper to convert pan distance (in actor coordinates) to the layout-specific scrolling direction
78 float CalculateScrollDistance(Vector2 panDistance, Toolkit::ItemLayout& layout)
80 Radian scrollDirection(layout.GetScrollDirection());
82 float cosTheta = cosf(scrollDirection);
83 float sinTheta = sinf(scrollDirection);
85 return panDistance.x * sinTheta + panDistance.y * cosTheta;
88 // Overshoot overlay constraints
89 struct OvershootOverlaySizeConstraint
91 OvershootOverlaySizeConstraint( float height )
92 : mOvershootHeight( height )
96 void operator()( Vector3& current, const PropertyInputContainer& inputs )
98 const Vector2& parentScrollDirection = inputs[0]->GetVector2();
99 const Toolkit::ControlOrientation::Type& layoutOrientation = static_cast<Toolkit::ControlOrientation::Type>(inputs[1]->GetInteger());
100 const Vector3& parentSize = inputs[2]->GetVector3();
102 if(Toolkit::IsVertical(layoutOrientation))
104 current.width = fabsf(parentScrollDirection.y) > Math::MACHINE_EPSILON_1 ? parentSize.x : parentSize.y;
108 current.width = fabsf(parentScrollDirection.x) > Math::MACHINE_EPSILON_1 ? parentSize.y : parentSize.x;
111 current.height = ( current.width > OVERSHOOT_BOUNCE_ACTOR_RESIZE_THRESHOLD ) ? mOvershootHeight : mOvershootHeight*0.5f;
114 float mOvershootHeight;
117 void OvershootOverlayRotationConstraint( Quaternion& current, const PropertyInputContainer& inputs )
119 const Vector2& parentScrollDirection = inputs[0]->GetVector2();
120 const Toolkit::ControlOrientation::Type& layoutOrientation = static_cast<Toolkit::ControlOrientation::Type>(inputs[1]->GetInteger());
121 const float parentOvershoot = inputs[2]->GetFloat();
123 float multiplier = 0;
124 if(Toolkit::IsVertical(layoutOrientation))
126 if(fabsf(parentScrollDirection.y) <= Math::MACHINE_EPSILON_1)
128 if( (layoutOrientation == Toolkit::ControlOrientation::Up && parentOvershoot < Math::MACHINE_EPSILON_0)
129 || (layoutOrientation == Toolkit::ControlOrientation::Down && parentOvershoot > Math::MACHINE_EPSILON_0) )
138 else if( (parentOvershoot > Math::MACHINE_EPSILON_0 && parentScrollDirection.y > Math::MACHINE_EPSILON_0)
139 || (parentOvershoot < Math::MACHINE_EPSILON_0 && parentScrollDirection.y < Math::MACHINE_EPSILON_0) )
150 if(fabsf(parentScrollDirection.x) <= Math::MACHINE_EPSILON_1)
152 if( (layoutOrientation == Toolkit::ControlOrientation::Left && parentOvershoot > Math::MACHINE_EPSILON_0)
153 ||(layoutOrientation == Toolkit::ControlOrientation::Right && parentOvershoot < Math::MACHINE_EPSILON_0) )
162 else if( (parentOvershoot > Math::MACHINE_EPSILON_0 && parentScrollDirection.x > Math::MACHINE_EPSILON_0)
163 || (parentOvershoot < Math::MACHINE_EPSILON_0 && parentScrollDirection.x < Math::MACHINE_EPSILON_0) )
173 current = Quaternion( Radian( multiplier * Math::PI ), Vector3::ZAXIS );
176 void OvershootOverlayPositionConstraint( Vector3& current, const PropertyInputContainer& inputs )
178 const Vector3& parentSize = inputs[0]->GetVector3();
179 const Vector2& parentScrollDirection = inputs[1]->GetVector2();
180 const Toolkit::ControlOrientation::Type& layoutOrientation = static_cast<Toolkit::ControlOrientation::Type>(inputs[2]->GetInteger());
181 const float parentOvershoot = inputs[3]->GetFloat();
183 Vector3 relativeOffset;
185 if(Toolkit::IsVertical(layoutOrientation))
187 if(fabsf(parentScrollDirection.y) <= Math::MACHINE_EPSILON_1)
189 if( (layoutOrientation == Toolkit::ControlOrientation::Up && parentOvershoot < Math::MACHINE_EPSILON_0)
190 || (layoutOrientation == Toolkit::ControlOrientation::Down && parentOvershoot > Math::MACHINE_EPSILON_0) )
192 relativeOffset = Vector3(1.0f, 0.0f, 0.0f);
196 relativeOffset =Vector3(0.0f, 1.0f, 0.0f);
199 else if( (parentOvershoot > Math::MACHINE_EPSILON_0 && parentScrollDirection.y > Math::MACHINE_EPSILON_0)
200 || (parentOvershoot < Math::MACHINE_EPSILON_0 && parentScrollDirection.y < Math::MACHINE_EPSILON_0) )
202 relativeOffset = Vector3(0.0f, 0.0f, 0.0f);
206 relativeOffset = Vector3(1.0f, 1.0f, 0.0f);
211 if(fabsf(parentScrollDirection.x) <= Math::MACHINE_EPSILON_1)
213 if( (layoutOrientation == Toolkit::ControlOrientation::Left && parentOvershoot < Math::MACHINE_EPSILON_0)
214 || (layoutOrientation == Toolkit::ControlOrientation::Right && parentOvershoot > Math::MACHINE_EPSILON_0) )
216 relativeOffset = Vector3(0.0f, 0.0f, 0.0f);
220 relativeOffset = Vector3(1.0f, 1.0f, 0.0f);
223 else if( (parentOvershoot > Math::MACHINE_EPSILON_0 && parentScrollDirection.x > Math::MACHINE_EPSILON_0)
224 || (parentOvershoot < Math::MACHINE_EPSILON_0 && parentScrollDirection.x < Math::MACHINE_EPSILON_0) )
226 relativeOffset = Vector3(0.0f, 1.0f, 0.0f);
230 relativeOffset = Vector3(1.0f, 0.0f, 0.0f);
234 current = relativeOffset * parentSize;
237 void OvershootOverlayVisibilityConstraint( bool& current, const PropertyInputContainer& inputs )
239 current = inputs[0]->GetBoolean();
242 } // unnamed namespace
253 namespace // unnamed namespace
258 DALI_TYPE_REGISTRATION_BEGIN( Toolkit::ItemView, Toolkit::Scrollable, NULL)
260 DALI_PROPERTY_REGISTRATION( Toolkit, ItemView, "minimumSwipeSpeed", FLOAT, MINIMUM_SWIPE_SPEED )
261 DALI_PROPERTY_REGISTRATION( Toolkit, ItemView, "minimumSwipeDistance", FLOAT, MINIMUM_SWIPE_DISTANCE )
262 DALI_PROPERTY_REGISTRATION( Toolkit, ItemView, "wheelScrollDistanceStep", FLOAT, WHEEL_SCROLL_DISTANCE_STEP )
263 DALI_PROPERTY_REGISTRATION( Toolkit, ItemView, "snapToItemEnabled", BOOLEAN, SNAP_TO_ITEM_ENABLED )
264 DALI_PROPERTY_REGISTRATION( Toolkit, ItemView, "refreshInterval", FLOAT, REFRESH_INTERVAL )
265 DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, ItemView, "layout", ARRAY, LAYOUT )
268 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "layoutPosition", FLOAT, LAYOUT_POSITION)
269 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "scrollSpeed", FLOAT, SCROLL_SPEED)
270 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "overshoot", FLOAT, OVERSHOOT)
271 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "scrollDirection", VECTOR2, SCROLL_DIRECTION)
272 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "layoutOrientation", INTEGER, LAYOUT_ORIENTATION)
273 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "scrollContentSize", FLOAT, SCROLL_CONTENT_SIZE)
275 DALI_SIGNAL_REGISTRATION( Toolkit, ItemView, "layoutActivated", LAYOUT_ACTIVATED_SIGNAL )
277 DALI_ACTION_REGISTRATION( Toolkit, ItemView, "stopScrolling", ACTION_STOP_SCROLLING )
279 DALI_ACTION_REGISTRATION( Toolkit, ItemView, "enableRefresh", ACTION_ENABLE_REFRESH )
280 DALI_ACTION_REGISTRATION( Toolkit, ItemView, "disableRefresh", ACTION_DISABLE_REFRESH )
282 DALI_TYPE_REGISTRATION_END()
284 bool FindById( const ItemContainer& items, ItemId id )
286 for( ConstItemIter iter = items.begin(); items.end() != iter; ++iter )
288 if( iter->first == id )
298 * Helper to apply size constraint to mOvershootOverlay
299 * @param[in] overshootOverlay The overshootOverlay actor
300 * @param[in] The required height
302 void ApplyOvershootSizeConstraint( Actor overshootOverlay, float height )
304 Constraint constraint = Constraint::New<Vector3>( overshootOverlay, Actor::Property::SIZE, OvershootOverlaySizeConstraint( height ) );
305 constraint.AddSource( ParentSource( Dali::Toolkit::ItemView::Property::SCROLL_DIRECTION ) );
306 constraint.AddSource( ParentSource( Dali::Toolkit::ItemView::Property::LAYOUT_ORIENTATION ) );
307 constraint.AddSource( ParentSource( Dali::Actor::Property::SIZE ) );
308 constraint.SetTag( OVERSHOOT_SIZE_CONSTRAINT_TAG );
312 } // unnamed namespace
314 Dali::Toolkit::ItemView ItemView::New(ItemFactory& factory)
316 // Create the implementation
317 ItemViewPtr itemView(new ItemView(factory));
319 // Pass ownership to CustomActor via derived handle
320 Dali::Toolkit::ItemView handle(*itemView);
322 // Second-phase init of the implementation
323 // This can only be done after the CustomActor connection has been made...
324 itemView->Initialize();
329 ItemView::ItemView(ItemFactory& factory)
330 : Scrollable( ControlBehaviour( DISABLE_SIZE_NEGOTIATION | DISABLE_STYLE_CHANGE_SIGNALS | REQUIRES_WHEEL_EVENTS | REQUIRES_KEYBOARD_NAVIGATION_SUPPORT ) ),
331 mItemFactory(factory),
332 mItemsParentOrigin(ParentOrigin::CENTER),
333 mItemsAnchorPoint(AnchorPoint::CENTER),
334 mTotalPanDisplacement(Vector2::ZERO),
336 mAnchoringDuration(DEFAULT_ANCHORING_DURATION),
337 mRefreshIntervalLayoutPositions(0.0f),
338 mMinimumSwipeSpeed(DEFAULT_MINIMUM_SWIPE_SPEED),
339 mMinimumSwipeDistance(DEFAULT_MINIMUM_SWIPE_DISTANCE),
340 mWheelScrollDistanceStep(0.0f),
341 mScrollDistance(0.0f),
343 mScrollOvershoot(0.0f),
344 mGestureState(Gesture::Clear),
345 mAnimatingOvershootOn(false),
346 mAnimateOvershootOff(false),
347 mAnchoringEnabled(false),
348 mRefreshOrderHint(true/*Refresh item 0 first*/),
351 mRefreshEnabled(true),
352 mRefreshNotificationEnabled(true),
357 void ItemView::OnInitialize()
361 Vector2 stageSize = Stage::GetCurrent().GetSize();
362 mWheelScrollDistanceStep = stageSize.y * DEFAULT_WHEEL_SCROLL_DISTANCE_STEP_PROPORTION;
364 self.TouchSignal().Connect( this, &ItemView::OnTouch );
365 EnableGestureDetection(Gesture::Type(Gesture::Pan));
367 mWheelEventFinishedTimer = Timer::New( WHEEL_EVENT_FINISHED_TIME_OUT );
368 mWheelEventFinishedTimer.TickSignal().Connect( this, &ItemView::OnWheelEventFinished );
370 SetRefreshInterval(DEFAULT_REFRESH_INTERVAL_LAYOUT_POSITIONS);
373 ItemView::~ItemView()
377 unsigned int ItemView::GetLayoutCount() const
379 return mLayouts.size();
382 void ItemView::AddLayout(ItemLayout& layout)
384 mLayouts.push_back(ItemLayoutPtr(&layout));
387 void ItemView::RemoveLayout(unsigned int layoutIndex)
389 DALI_ASSERT_ALWAYS(layoutIndex < mLayouts.size());
391 if (mActiveLayout == mLayouts[layoutIndex].Get())
393 mActiveLayout = NULL;
396 mLayouts.erase(mLayouts.begin() + layoutIndex);
399 ItemLayoutPtr ItemView::GetLayout(unsigned int layoutIndex) const
401 return mLayouts[layoutIndex];
404 ItemLayoutPtr ItemView::GetActiveLayout() const
406 return ItemLayoutPtr(mActiveLayout);
409 float ItemView::GetCurrentLayoutPosition(unsigned int itemId) const
411 return DevelHandle::GetCurrentProperty< float >( Self(), Toolkit::ItemView::Property::LAYOUT_POSITION ) + static_cast<float>( itemId );
414 void ItemView::ActivateLayout(unsigned int layoutIndex, const Vector3& targetSize, float durationSeconds)
416 DALI_ASSERT_ALWAYS(layoutIndex < mLayouts.size());
418 mRefreshEnabled = false;
422 // The ItemView size should match the active layout size
423 self.SetSize(targetSize);
424 mActiveLayoutTargetSize = targetSize;
426 // Switch to the new layout
427 mActiveLayout = mLayouts[layoutIndex].Get();
429 // Move the items to the new layout positions...
431 for (ConstItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
433 unsigned int itemId = iter->first;
434 Actor actor = iter->second;
436 // Remove constraints from previous layout
437 actor.RemoveConstraints();
439 mActiveLayout->ApplyConstraints(actor, itemId, targetSize, Self() );
442 mActiveLayout->GetItemSize( itemId, targetSize, size );
443 actor.SetSize( size.GetVectorXY() );
446 // Refresh the new layout
447 ItemRange range = GetItemRange(*mActiveLayout, targetSize, GetCurrentLayoutPosition(0), false/* don't reserve extra*/);
448 AddActorsWithinRange( range, targetSize );
450 // Scroll to an appropriate layout position
452 bool scrollAnimationNeeded(false);
453 float firstItemScrollPosition(0.0f);
455 float current = GetCurrentLayoutPosition(0);
456 float minimum = ClampFirstItemPosition(current, targetSize, *mActiveLayout);
458 if (current < minimum)
460 scrollAnimationNeeded = true;
461 firstItemScrollPosition = minimum;
463 else if (mAnchoringEnabled)
465 scrollAnimationNeeded = true;
466 firstItemScrollPosition = mActiveLayout->GetClosestAnchorPosition(current);
469 if (scrollAnimationNeeded)
471 RemoveAnimation(mScrollAnimation);
472 mScrollAnimation = Animation::New(durationSeconds);
473 mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), firstItemScrollPosition, AlphaFunction::EASE_OUT );
474 mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnLayoutActivationScrollFinished);
475 mScrollAnimation.Play();
479 // Emit the layout activated signal
480 mLayoutActivatedSignal.Emit();
483 AnimateScrollOvershoot(0.0f);
484 mScrollOvershoot = 0.0f;
486 Radian scrollDirection(mActiveLayout->GetScrollDirection());
487 self.SetProperty(Toolkit::ItemView::Property::SCROLL_DIRECTION, Vector2(sinf(scrollDirection), cosf(scrollDirection)));
488 self.SetProperty(Toolkit::ItemView::Property::LAYOUT_ORIENTATION, static_cast<int>(mActiveLayout->GetOrientation()));
489 self.SetProperty(Toolkit::ItemView::Property::SCROLL_SPEED, mScrollSpeed);
491 CalculateDomainSize(targetSize);
494 void ItemView::DeactivateCurrentLayout()
498 for (ConstItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
500 Actor actor = iter->second;
501 actor.RemoveConstraints();
504 mActiveLayout = NULL;
508 void ItemView::OnRefreshNotification(PropertyNotification& source)
510 if( mRefreshNotificationEnabled )
512 // Cancel scroll animation to prevent any fighting of setting the scroll position property by scroll bar during fast scroll.
513 if(!mRefreshEnabled && mScrollAnimation)
515 RemoveAnimation(mScrollAnimation);
518 // Only cache extra items when it is not a fast scroll
519 DoRefresh(GetCurrentLayoutPosition(0), mRefreshEnabled || mScrollAnimation);
523 void ItemView::Refresh()
525 for (ItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter )
527 ReleaseActor( iter->first, iter->second );
531 DoRefresh(GetCurrentLayoutPosition(0), true);
534 void ItemView::DoRefresh(float currentLayoutPosition, bool cacheExtra)
538 ItemRange range = GetItemRange(*mActiveLayout, mActiveLayoutTargetSize, currentLayoutPosition, cacheExtra/*reserve extra*/);
539 RemoveActorsOutsideRange( range );
540 AddActorsWithinRange( range, Self().GetCurrentSize() );
542 mScrollUpdatedSignal.Emit( Vector2(0.0f, currentLayoutPosition) );
546 void ItemView::SetMinimumSwipeSpeed(float speed)
548 mMinimumSwipeSpeed = speed;
551 float ItemView::GetMinimumSwipeSpeed() const
553 return mMinimumSwipeSpeed;
556 void ItemView::SetMinimumSwipeDistance(float distance)
558 mMinimumSwipeDistance = distance;
561 float ItemView::GetMinimumSwipeDistance() const
563 return mMinimumSwipeDistance;
566 void ItemView::SetWheelScrollDistanceStep(float step)
568 mWheelScrollDistanceStep = step;
571 float ItemView::GetWheelScrollDistanceStep() const
573 return mWheelScrollDistanceStep;
576 void ItemView::SetAnchoring(bool enabled)
578 mAnchoringEnabled = enabled;
581 bool ItemView::GetAnchoring() const
583 return mAnchoringEnabled;
586 void ItemView::SetAnchoringDuration(float durationSeconds)
588 mAnchoringDuration = durationSeconds;
591 float ItemView::GetAnchoringDuration() const
593 return mAnchoringDuration;
596 void ItemView::SetRefreshInterval(float intervalLayoutPositions)
598 if( !Equals(mRefreshIntervalLayoutPositions, intervalLayoutPositions) )
600 mRefreshIntervalLayoutPositions = intervalLayoutPositions;
603 if(mRefreshNotification)
605 self.RemovePropertyNotification(mRefreshNotification);
607 mRefreshNotification = self.AddPropertyNotification( Toolkit::ItemView::Property::LAYOUT_POSITION, StepCondition(mRefreshIntervalLayoutPositions, 0.0f) );
608 mRefreshNotification.NotifySignal().Connect( this, &ItemView::OnRefreshNotification );
612 float ItemView::GetRefreshInterval() const
614 return mRefreshIntervalLayoutPositions;
617 void ItemView::SetRefreshEnabled(bool enabled)
619 mRefreshEnabled = enabled;
622 Actor ItemView::GetItem(unsigned int itemId) const
626 ConstItemPoolIter iter = mItemPool.find( itemId );
627 if( iter != mItemPool.end() )
629 actor = iter->second;
635 unsigned int ItemView::GetItemId( Actor actor ) const
637 unsigned int itemId( 0 );
639 for ( ConstItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter )
641 if( iter->second == actor )
643 itemId = iter->first;
651 void ItemView::InsertItem( Item newItem, float durationSeconds )
654 Vector3 layoutSize = Self().GetCurrentSize();
656 Actor displacedActor;
657 ItemPoolIter afterDisplacedIter = mItemPool.end();
659 ItemPoolIter foundIter = mItemPool.find( newItem.first );
660 if( mItemPool.end() != foundIter )
662 SetupActor( newItem, layoutSize );
663 Self().Add( newItem.second );
665 displacedActor = foundIter->second;
666 foundIter->second = newItem.second;
668 afterDisplacedIter = ++foundIter;
672 // Inserting before the existing item range?
673 ItemPoolIter iter = mItemPool.begin();
674 if( iter != mItemPool.end() &&
675 iter->first > newItem.first )
677 displacedActor = iter->second;
678 mItemPool.erase( iter++ ); // iter is still valid after the erase
680 afterDisplacedIter = iter;
686 // Move the existing actors to make room
687 for( ItemPoolIter iter = afterDisplacedIter; mItemPool.end() != iter; ++iter )
689 Actor temp = iter->second;
690 iter->second = displacedActor;
691 displacedActor = temp;
693 iter->second.RemoveConstraints();
694 mActiveLayout->ApplyConstraints( iter->second, iter->first, layoutSize, Self() );
698 ItemPool::reverse_iterator lastIter = mItemPool.rbegin();
699 if ( lastIter != mItemPool.rend() )
701 ItemId lastId = lastIter->first;
702 Item lastItem( lastId + 1, displacedActor );
703 mItemPool.insert( lastItem );
705 lastItem.second.RemoveConstraints();
706 mActiveLayout->ApplyConstraints( lastItem.second, lastItem.first, layoutSize, Self() );
710 CalculateDomainSize( layoutSize );
712 mAddingItems = false;
715 void ItemView::InsertItems( const ItemContainer& newItems, float durationSeconds )
718 Vector3 layoutSize = Self().GetCurrentSize();
720 // Insert from lowest id to highest
721 std::set<Item> sortedItems;
722 for( ConstItemIter iter = newItems.begin(); newItems.end() != iter; ++iter )
724 sortedItems.insert( *iter );
727 for( std::set<Item>::iterator iter = sortedItems.begin(); sortedItems.end() != iter; ++iter )
729 Self().Add( iter->second );
731 ItemPoolIter foundIter = mItemPool.find( iter->first );
732 if( mItemPool.end() != foundIter )
734 Actor moveMe = foundIter->second;
735 foundIter->second = iter->second;
737 // Move the existing actors to make room
738 for( ItemPoolIter iter = ++foundIter; mItemPool.end() != iter; ++iter )
740 Actor temp = iter->second;
741 iter->second = moveMe;
746 ItemId lastId = mItemPool.rbegin()->first;
747 Item lastItem( lastId + 1, moveMe );
748 mItemPool.insert( lastItem );
752 mItemPool.insert( *iter );
756 // Relayout everything
757 for (ItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
760 if( FindById( newItems, iter->first ) )
762 SetupActor( *iter, layoutSize );
766 iter->second.RemoveConstraints();
767 mActiveLayout->ApplyConstraints( iter->second, iter->first, layoutSize, Self() );
771 CalculateDomainSize( layoutSize );
773 mAddingItems = false;
776 void ItemView::RemoveItem( unsigned int itemId, float durationSeconds )
778 bool actorsReordered = RemoveActor( itemId );
779 if( actorsReordered )
781 ReapplyAllConstraints();
787 void ItemView::RemoveItems( const ItemIdContainer& itemIds, float durationSeconds )
789 bool actorsReordered( false );
791 // Remove from highest id to lowest
792 set<ItemId> sortedItems;
793 for( ConstItemIdIter iter = itemIds.begin(); itemIds.end() != iter; ++iter )
795 sortedItems.insert( *iter );
798 for( set<ItemId>::reverse_iterator iter = sortedItems.rbegin(); sortedItems.rend() != iter; ++iter )
800 if( RemoveActor( *iter ) )
802 actorsReordered = true;
806 if( actorsReordered )
808 ReapplyAllConstraints();
814 bool ItemView::RemoveActor(unsigned int itemId)
816 bool reordered( false );
818 ItemPoolIter removeIter = mItemPool.find( itemId );
819 if( removeIter != mItemPool.end() )
821 ReleaseActor(itemId, removeIter->second);
825 // Removing before the existing item range?
826 ItemPoolIter iter = mItemPool.begin();
827 if( iter != mItemPool.end() &&
828 iter->first > itemId )
830 // In order to decrement the first visible item ID
831 mItemPool.insert( Item(iter->first - 1, Actor()) );
833 removeIter = mItemPool.begin();
837 if( removeIter != mItemPool.end() )
841 // Adjust the remaining item IDs, for example if item 2 is removed:
842 // Initial actors: After insert:
843 // ID 1 - ActorA ID 1 - ActorA
844 // ID 2 - ActorB ID 2 - ActorC (previously ID 3)
845 // ID 3 - ActorC ID 3 - ActorB (previously ID 4)
847 for (ItemPoolIter iter = removeIter; iter != mItemPool.end(); ++iter)
849 if( iter->first < mItemPool.rbegin()->first )
851 iter->second = mItemPool[ iter->first + 1 ];
855 mItemPool.erase( iter );
864 void ItemView::ReplaceItem( Item replacementItem, float durationSeconds )
867 Vector3 layoutSize = Self().GetCurrentSize();
869 SetupActor( replacementItem, layoutSize );
870 Self().Add( replacementItem.second );
872 const ItemPoolIter iter = mItemPool.find( replacementItem.first );
873 if( mItemPool.end() != iter )
875 ReleaseActor(iter->first, iter->second);
876 iter->second = replacementItem.second;
880 mItemPool.insert( replacementItem );
883 CalculateDomainSize( layoutSize );
885 mAddingItems = false;
888 void ItemView::ReplaceItems( const ItemContainer& replacementItems, float durationSeconds )
890 for( ConstItemIter iter = replacementItems.begin(); replacementItems.end() != iter; ++iter )
892 ReplaceItem( *iter, durationSeconds );
896 void ItemView::RemoveActorsOutsideRange( ItemRange range )
898 // Remove unwanted actors from the ItemView & ItemPool
899 for (ItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); )
901 unsigned int current = iter->first;
903 if( ! range.Within( current ) )
905 ReleaseActor(iter->first, iter->second);
907 mItemPool.erase( iter++ ); // erase invalidates the return value of post-increment; iter remains valid
916 void ItemView::AddActorsWithinRange( ItemRange range, const Vector3& layoutSize )
918 range.end = std::min(mItemFactory.GetNumberOfItems(), range.end);
920 // The order of addition depends on the scroll direction.
921 if (mRefreshOrderHint)
923 for (unsigned int itemId = range.begin; itemId < range.end; ++itemId)
925 AddNewActor( itemId, layoutSize );
930 for (unsigned int itemId = range.end; itemId > range.begin; --itemId)
932 AddNewActor( itemId-1, layoutSize );
936 // Total number of items may change dynamically.
937 // Always recalculate the domain size to reflect that.
938 CalculateDomainSize(Self().GetCurrentSize());
941 void ItemView::AddNewActor( unsigned int itemId, const Vector3& layoutSize )
945 if( mItemPool.end() == mItemPool.find( itemId ) )
947 Actor actor = mItemFactory.NewItem( itemId );
951 Item newItem( itemId, actor );
953 mItemPool.insert( newItem );
955 SetupActor( newItem, layoutSize );
960 mAddingItems = false;
963 void ItemView::SetupActor( Item item, const Vector3& layoutSize )
965 item.second.SetParentOrigin( mItemsParentOrigin );
966 item.second.SetAnchorPoint( mItemsAnchorPoint );
971 mActiveLayout->GetItemSize( item.first, mActiveLayoutTargetSize, size );
972 item.second.SetSize( size.GetVectorXY() );
974 mActiveLayout->ApplyConstraints( item.second, item.first, layoutSize, Self() );
978 void ItemView::ReleaseActor( ItemId item, Actor actor )
980 Self().Remove( actor );
981 mItemFactory.ItemReleased(item, actor);
984 ItemRange ItemView::GetItemRange(ItemLayout& layout, const Vector3& layoutSize, float layoutPosition, bool reserveExtra)
986 unsigned int itemCount = mItemFactory.GetNumberOfItems();
988 ItemRange available(0u, itemCount);
990 ItemRange range = layout.GetItemsWithinArea( layoutPosition, layoutSize );
994 // Add the reserve items for scrolling
995 unsigned int extra = layout.GetReserveItemCount(layoutSize);
996 range.begin = (range.begin >= extra) ? (range.begin - extra) : 0u;
1000 return range.Intersection(available);
1003 void ItemView::OnChildAdd(Actor& child)
1007 // We don't want to do this downcast check for any item added by ItemView itself.
1008 Dali::Toolkit::ScrollBar scrollBar = Dali::Toolkit::ScrollBar::DownCast(child);
1011 scrollBar.SetScrollPropertySource(Self(),
1012 Toolkit::ItemView::Property::LAYOUT_POSITION,
1013 Toolkit::Scrollable::Property::SCROLL_POSITION_MIN_Y,
1014 Toolkit::Scrollable::Property::SCROLL_POSITION_MAX_Y,
1015 Toolkit::ItemView::Property::SCROLL_CONTENT_SIZE);
1019 Scrollable::OnChildAdd( child );
1022 bool ItemView::OnWheelEvent(const WheelEvent& event)
1024 // Respond the wheel event to scroll
1027 Actor self = Self();
1028 const Vector3 layoutSize = Self().GetCurrentSize();
1029 float layoutPositionDelta = GetCurrentLayoutPosition(0) - (event.z * mWheelScrollDistanceStep * mActiveLayout->GetScrollSpeedFactor());
1030 float firstItemScrollPosition = ClampFirstItemPosition(layoutPositionDelta, layoutSize, *mActiveLayout);
1032 self.SetProperty(Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1034 mScrollStartedSignal.Emit(GetCurrentScrollPosition());
1035 mRefreshEnabled = true;
1038 if (mWheelEventFinishedTimer.IsRunning())
1040 mWheelEventFinishedTimer.Stop();
1043 mWheelEventFinishedTimer.Start();
1048 bool ItemView::OnWheelEventFinished()
1052 RemoveAnimation(mScrollAnimation);
1054 // No more wheel events coming. Do the anchoring if enabled.
1055 mScrollAnimation = DoAnchoring();
1056 if (mScrollAnimation)
1058 mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
1059 mScrollAnimation.Play();
1063 mScrollOvershoot = 0.0f;
1064 AnimateScrollOvershoot(0.0f);
1066 mScrollCompletedSignal.Emit(GetCurrentScrollPosition());
1073 void ItemView::ReapplyAllConstraints()
1075 Vector3 layoutSize = Self().GetCurrentSize();
1077 for (ConstItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
1079 unsigned int id = iter->first;
1080 Actor actor = iter->second;
1082 actor.RemoveConstraints();
1083 mActiveLayout->ApplyConstraints(actor, id, layoutSize, Self());
1087 void ItemView::OnItemsRemoved()
1089 CalculateDomainSize(Self().GetCurrentSize());
1091 // Adjust scroll-position after an item is removed
1094 float firstItemScrollPosition = ClampFirstItemPosition(GetCurrentLayoutPosition(0), Self().GetCurrentSize(), *mActiveLayout);
1095 Self().SetProperty( Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1099 float ItemView::ClampFirstItemPosition( float targetPosition, const Vector3& targetSize, ItemLayout& layout, bool updateOvershoot )
1101 Actor self = Self();
1102 float minLayoutPosition = layout.GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), targetSize);
1103 float clamppedPosition = std::min(0.0f, std::max(minLayoutPosition, targetPosition));
1104 self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX, Vector2(0.0f, -minLayoutPosition));
1106 if( updateOvershoot )
1108 mScrollOvershoot = targetPosition - clamppedPosition;
1111 return clamppedPosition;
1114 bool ItemView::OnTouch( Actor actor, const TouchData& touch )
1116 // Ignore events with multiple-touch points
1117 if (touch.GetPointCount() != 1)
1122 if ( touch.GetState( 0 ) == PointState::DOWN )
1124 // Cancel ongoing scrolling etc.
1125 mGestureState = Gesture::Clear;
1127 mScrollDistance = 0.0f;
1128 mScrollSpeed = 0.0f;
1129 Self().SetProperty(Toolkit::ItemView::Property::SCROLL_SPEED, mScrollSpeed);
1131 mScrollOvershoot = 0.0f;
1132 AnimateScrollOvershoot(0.0f);
1134 if(mScrollAnimation)
1136 mScrollCompletedSignal.Emit(GetCurrentScrollPosition());
1139 RemoveAnimation(mScrollAnimation);
1142 return true; // consume since we're potentially scrolling
1145 void ItemView::OnPan( const PanGesture& gesture )
1147 Actor self = Self();
1148 const Vector3 layoutSize = Self().GetCurrentSize();
1150 RemoveAnimation(mScrollAnimation);
1152 // Short-circuit if there is no active layout
1155 mGestureState = Gesture::Clear;
1159 mGestureState = gesture.state;
1161 switch (mGestureState)
1163 case Gesture::Finished:
1166 if (fabsf(mScrollDistance) > mMinimumSwipeDistance &&
1167 mScrollSpeed > mMinimumSwipeSpeed)
1169 float direction = (mScrollDistance < 0.0f) ? -1.0f : 1.0f;
1171 mRefreshOrderHint = true;
1173 float currentLayoutPosition = GetCurrentLayoutPosition(0);
1174 float firstItemScrollPosition = ClampFirstItemPosition(currentLayoutPosition + mScrollSpeed * direction,
1178 if (mAnchoringEnabled)
1180 firstItemScrollPosition = mActiveLayout->GetClosestAnchorPosition(firstItemScrollPosition);
1183 RemoveAnimation(mScrollAnimation);
1185 float flickAnimationDuration = Clamp( mActiveLayout->GetItemFlickAnimationDuration() * std::max(1.0f, fabsf(firstItemScrollPosition - GetCurrentLayoutPosition(0)))
1186 , DEFAULT_MINIMUM_SWIPE_DURATION, DEFAULT_MAXIMUM_SWIPE_DURATION);
1188 mScrollAnimation = Animation::New(flickAnimationDuration);
1189 mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION ), firstItemScrollPosition, AlphaFunction::EASE_OUT );
1190 mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::SCROLL_SPEED), 0.0f, AlphaFunction::EASE_OUT );
1194 // Check whether it has already scrolled to the end
1195 if( fabs(currentLayoutPosition - firstItemScrollPosition) < Math::MACHINE_EPSILON_0 )
1197 AnimateScrollOvershoot( 0.0f );
1198 RemoveAnimation( mScrollAnimation );
1202 // Anchoring may be triggered when there was no swipe
1203 if (!mScrollAnimation)
1205 mScrollAnimation = DoAnchoring();
1208 // Reset the overshoot if no scroll animation.
1209 if (!mScrollAnimation)
1211 mScrollCompletedSignal.Emit(GetCurrentScrollPosition());
1213 AnimateScrollOvershoot(0.0f, false);
1218 case Gesture::Started: // Fall through
1220 mTotalPanDisplacement = Vector2::ZERO;
1221 mScrollStartedSignal.Emit(GetCurrentScrollPosition());
1222 mRefreshEnabled = true;
1225 case Gesture::Continuing:
1227 mScrollDistance = CalculateScrollDistance(gesture.displacement, *mActiveLayout);
1228 mScrollSpeed = Clamp((gesture.GetSpeed() * gesture.GetSpeed() * mActiveLayout->GetFlickSpeedFactor() * MILLISECONDS_PER_SECONDS), 0.0f, mActiveLayout->GetMaximumSwipeSpeed());
1230 // Refresh order depends on the direction of the scroll; negative is towards the last item.
1231 mRefreshOrderHint = mScrollDistance < 0.0f;
1233 float layoutPositionDelta = GetCurrentLayoutPosition(0) + (mScrollDistance * mActiveLayout->GetScrollSpeedFactor());
1235 float firstItemScrollPosition = ClampFirstItemPosition(layoutPositionDelta, layoutSize, *mActiveLayout);
1237 float currentOvershoot = DevelHandle::GetCurrentProperty< float >( self, Toolkit::ItemView::Property::OVERSHOOT );
1239 self.SetProperty(Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1241 if( ( firstItemScrollPosition >= 0.0f &&
1242 currentOvershoot < 1.0f ) ||
1243 ( firstItemScrollPosition <= mActiveLayout->GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), layoutSize) &&
1244 currentOvershoot > -1.0f ) )
1246 mTotalPanDisplacement += gesture.displacement;
1249 mScrollOvershoot = CalculateScrollOvershoot();
1251 // If the view is moved in a direction against the overshoot indicator, then the indicator should be animated off.
1252 // First make sure we are not in an animation, otherwise a previously started
1253 // off-animation will be overwritten as the user continues scrolling.
1256 // Check if the movement is against the current overshoot amount (if we are currently displaying the indicator).
1257 if( ( ( mScrollOvershoot > Math::MACHINE_EPSILON_0 ) && ( mScrollDistance < -Math::MACHINE_EPSILON_0 ) ) ||
1258 ( ( mScrollOvershoot < Math::MACHINE_EPSILON_0 ) && ( mScrollDistance > Math::MACHINE_EPSILON_0 ) ) )
1260 // The user has moved against the indicator direction.
1261 // First, we reset the total displacement. This means the overshoot amount will become zero the next frame,
1262 // and if the user starts dragging in the overshoot direction again, the indicator will appear once more.
1263 mTotalPanDisplacement = Vector2::ZERO;
1264 // Animate the overshoot indicator off.
1265 AnimateScrollOvershoot( 0.0f, false );
1269 // Only set the property directly if we are not animating the overshoot away,
1270 // as otherwise this will overwrite the animation generated value.
1271 self.SetProperty( Toolkit::ItemView::Property::OVERSHOOT, mScrollOvershoot );
1277 case Gesture::Cancelled:
1279 mScrollAnimation = DoAnchoring();
1287 if (mScrollAnimation)
1289 mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
1290 mScrollAnimation.Play();
1294 bool ItemView::OnAccessibilityPan(PanGesture gesture)
1300 Actor ItemView::GetNextKeyboardFocusableActor(Actor actor, Toolkit::Control::KeyboardFocus::Direction direction, bool loopEnabled)
1302 Actor nextFocusActor;
1306 if(!actor || actor == this->Self())
1308 nextFocusActor = GetItem(nextItemID);
1310 else if(actor && actor.GetParent() == this->Self())
1312 int itemID = GetItemId(actor);
1313 nextItemID = mActiveLayout->GetNextFocusItemID(itemID, mItemFactory.GetNumberOfItems(), direction, loopEnabled);
1314 nextFocusActor = GetItem(nextItemID);
1315 if(nextFocusActor == actor)
1317 // need to pass NULL actor back to focus manager
1318 nextFocusActor.Reset();
1319 return nextFocusActor;
1322 float layoutPosition = mActiveLayout->GetClosestAnchorPosition( GetCurrentLayoutPosition(0) );
1323 Vector3 layoutSize = Self().GetCurrentSize();
1326 // likely the current item is not buffered, so not in our item pool, probably best to get first viewable item
1327 ItemRange viewableItems = mActiveLayout->GetItemsWithinArea(layoutPosition, layoutSize);
1328 nextItemID = viewableItems.begin;
1329 nextFocusActor = GetItem(nextItemID);
1332 return nextFocusActor;
1335 void ItemView::OnKeyboardFocusChangeCommitted(Actor commitedFocusableActor)
1337 // only in this function if our chosen focus actor was actually used
1338 if(commitedFocusableActor)
1340 int nextItemID = GetItemId(commitedFocusableActor);
1341 float layoutPosition = GetCurrentLayoutPosition(0);
1342 Vector3 layoutSize = Self().GetCurrentSize();
1344 float scrollTo = mActiveLayout->GetClosestOnScreenLayoutPosition(nextItemID, layoutPosition, layoutSize);
1345 ScrollTo(Vector2(0.0f, scrollTo), DEFAULT_KEYBOARD_FOCUS_SCROLL_DURATION);
1349 Animation ItemView::DoAnchoring()
1351 Animation anchoringAnimation;
1352 Actor self = Self();
1354 if (mActiveLayout && mAnchoringEnabled)
1356 float anchorPosition = mActiveLayout->GetClosestAnchorPosition( GetCurrentLayoutPosition(0) );
1358 anchoringAnimation = Animation::New(mAnchoringDuration);
1359 anchoringAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), anchorPosition, AlphaFunction::EASE_OUT );
1360 anchoringAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::SCROLL_SPEED), 0.0f, AlphaFunction::EASE_OUT );
1363 AnimateScrollOvershoot(0.0f);
1367 return anchoringAnimation;
1370 void ItemView::OnScrollFinished(Animation& source)
1372 Actor self = Self();
1374 RemoveAnimation(mScrollAnimation); // mScrollAnimation is used to query whether we're scrolling
1376 mScrollCompletedSignal.Emit(GetCurrentScrollPosition());
1378 if(mIsFlicking && fabsf(mScrollOvershoot) > Math::MACHINE_EPSILON_1)
1380 AnimateScrollOvershoot( mScrollOvershoot > 0.0f ? 1.0f : -1.0f, true);
1384 // Reset the overshoot
1385 AnimateScrollOvershoot( 0.0f );
1387 mIsFlicking = false;
1389 mScrollOvershoot = 0.0f;
1392 void ItemView::OnLayoutActivationScrollFinished(Animation& source)
1394 RemoveAnimation(mScrollAnimation);
1395 mRefreshEnabled = true;
1396 DoRefresh(GetCurrentLayoutPosition(0), true);
1398 // Emit the layout activated signal
1399 mLayoutActivatedSignal.Emit();
1402 void ItemView::OnOvershootOnFinished(Animation& animation)
1404 mAnimatingOvershootOn = false;
1405 mScrollOvershootAnimation.FinishedSignal().Disconnect(this, &ItemView::OnOvershootOnFinished);
1406 RemoveAnimation(mScrollOvershootAnimation);
1407 if(mAnimateOvershootOff)
1409 AnimateScrollOvershoot(0.0f);
1411 mInAnimation = false;
1414 void ItemView::ScrollToItem(unsigned int itemId, float durationSeconds)
1416 Actor self = Self();
1417 const Vector3 layoutSize = Self().GetCurrentSize();
1418 float firstItemScrollPosition = ClampFirstItemPosition(mActiveLayout->GetItemScrollToPosition(itemId), layoutSize, *mActiveLayout);
1420 if(durationSeconds > 0.0f)
1422 RemoveAnimation(mScrollAnimation);
1423 mScrollAnimation = Animation::New(durationSeconds);
1424 mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), firstItemScrollPosition, mScrollToAlphaFunction );
1425 mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
1426 mScrollAnimation.Play();
1430 self.SetProperty( Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1431 AnimateScrollOvershoot(0.0f);
1434 mScrollStartedSignal.Emit(GetCurrentScrollPosition());
1435 mRefreshEnabled = true;
1438 void ItemView::RemoveAnimation(Animation& animation)
1442 // Cease animating, and reset handle.
1448 void ItemView::CalculateDomainSize(const Vector3& layoutSize)
1450 Actor self = Self();
1452 Vector3 firstItemPosition(Vector3::ZERO);
1453 Vector3 lastItemPosition(Vector3::ZERO);
1457 firstItemPosition = mActiveLayout->GetItemPosition( 0,0,layoutSize );
1459 float minLayoutPosition = mActiveLayout->GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), layoutSize);
1460 lastItemPosition = mActiveLayout->GetItemPosition( fabs(minLayoutPosition),fabs(minLayoutPosition),layoutSize );
1464 if(IsHorizontal(mActiveLayout->GetOrientation()))
1466 domainSize = fabs(firstItemPosition.x - lastItemPosition.x);
1470 domainSize = fabs(firstItemPosition.y - lastItemPosition.y);
1473 self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MIN, Vector2::ZERO);
1474 self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX, Vector2(0.0f, -minLayoutPosition));
1476 self.SetProperty(Toolkit::ItemView::Property::SCROLL_CONTENT_SIZE, domainSize);
1478 bool isLayoutScrollable = IsLayoutScrollable(layoutSize);
1479 self.SetProperty(Toolkit::Scrollable::Property::CAN_SCROLL_VERTICAL, isLayoutScrollable);
1480 self.SetProperty(Toolkit::Scrollable::Property::CAN_SCROLL_HORIZONTAL, false);
1484 bool ItemView::IsLayoutScrollable(const Vector3& layoutSize)
1486 Actor self = Self();
1488 float currentLayoutPosition = ClampFirstItemPosition( GetCurrentLayoutPosition(0), layoutSize, *mActiveLayout, false );
1489 float forwardClampedPosition = ClampFirstItemPosition( currentLayoutPosition + 1.0, layoutSize, *mActiveLayout, false );
1490 float backwardClampedPosition = ClampFirstItemPosition( currentLayoutPosition - 1.0, layoutSize, *mActiveLayout, false );
1492 return (fabs(forwardClampedPosition - backwardClampedPosition) > Math::MACHINE_EPSILON_0);
1495 float ItemView::GetScrollPosition(float layoutPosition, const Vector3& layoutSize) const
1497 Vector3 firstItemPosition( mActiveLayout->GetItemPosition(0, layoutPosition, layoutSize ) );
1498 return IsHorizontal(mActiveLayout->GetOrientation()) ? firstItemPosition.x: firstItemPosition.y;
1501 Vector2 ItemView::GetCurrentScrollPosition() const
1503 return Vector2(0.0f, GetScrollPosition(GetCurrentLayoutPosition(0), Self().GetCurrentSize()));
1506 void ItemView::AddOverlay(Actor actor)
1508 actor.SetDrawMode( DrawMode::OVERLAY_2D );
1512 void ItemView::RemoveOverlay(Actor actor)
1514 Self().Remove(actor);
1517 void ItemView::ScrollTo(const Vector2& position, float duration)
1519 Actor self = Self();
1520 const Vector3 layoutSize = Self().GetCurrentSize();
1522 float firstItemScrollPosition = ClampFirstItemPosition(position.y, layoutSize, *mActiveLayout);
1526 RemoveAnimation(mScrollAnimation);
1527 mScrollAnimation = Animation::New(duration);
1528 mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), firstItemScrollPosition, mScrollToAlphaFunction );
1529 mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
1530 mScrollAnimation.Play();
1534 self.SetProperty( Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1535 AnimateScrollOvershoot(0.0f);
1538 mScrollStartedSignal.Emit(GetCurrentScrollPosition());
1539 mRefreshEnabled = true;
1542 void ItemView::SetOvershootSize( const Vector2& size )
1544 mOvershootSize = size;
1546 if( mOvershootOverlay )
1548 // Remove old & add new size constraint
1549 mOvershootOverlay.RemoveConstraints( OVERSHOOT_SIZE_CONSTRAINT_TAG );
1550 ApplyOvershootSizeConstraint( mOvershootOverlay, mOvershootSize.height );
1554 void ItemView::SetOvershootEffectColor( const Vector4& color )
1556 mOvershootEffectColor = color;
1557 if( mOvershootOverlay )
1559 mOvershootOverlay.SetColor( color );
1563 void ItemView::EnableScrollOvershoot( bool enable )
1565 Actor self = Self();
1568 if( !mOvershootOverlay )
1570 Property::Index effectOvershootPropertyIndex = Property::INVALID_INDEX;
1571 mOvershootOverlay = CreateBouncingEffectActor( effectOvershootPropertyIndex );
1572 mOvershootOverlay.SetColor(mOvershootEffectColor);
1573 mOvershootOverlay.SetParentOrigin(ParentOrigin::TOP_LEFT);
1574 mOvershootOverlay.SetAnchorPoint(AnchorPoint::TOP_LEFT);
1575 mOvershootOverlay.SetDrawMode( DrawMode::OVERLAY_2D );
1576 self.Add(mOvershootOverlay);
1578 ApplyOvershootSizeConstraint( mOvershootOverlay, mOvershootSize.height );
1580 Constraint constraint = Constraint::New<Quaternion>( mOvershootOverlay, Actor::Property::ORIENTATION, OvershootOverlayRotationConstraint );
1581 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::SCROLL_DIRECTION ) );
1582 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_ORIENTATION ) );
1583 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::OVERSHOOT ) );
1586 constraint = Constraint::New<Vector3>( mOvershootOverlay, Actor::Property::POSITION, OvershootOverlayPositionConstraint );
1587 constraint.AddSource( ParentSource( Actor::Property::SIZE ) );
1588 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::SCROLL_DIRECTION ) );
1589 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_ORIENTATION ) );
1590 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::OVERSHOOT ) );
1593 constraint = Constraint::New<bool>( mOvershootOverlay, Actor::Property::VISIBLE, OvershootOverlayVisibilityConstraint );
1594 constraint.AddSource( ParentSource( Toolkit::Scrollable::Property::CAN_SCROLL_VERTICAL ) );
1597 constraint = Constraint::New<float>( mOvershootOverlay, effectOvershootPropertyIndex, EqualToConstraint() );
1598 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::OVERSHOOT ) );
1604 if( mOvershootOverlay )
1606 self.Remove(mOvershootOverlay);
1607 mOvershootOverlay.Reset();
1612 float ItemView::CalculateScrollOvershoot()
1614 float overshoot = 0.0f;
1618 // The overshoot must be calculated from the accumulated pan gesture displacement
1619 // since the pan gesture starts.
1620 Actor self = Self();
1621 float scrollDistance = CalculateScrollDistance(mTotalPanDisplacement, *mActiveLayout) * mActiveLayout->GetScrollSpeedFactor();
1622 float positionDelta = GetCurrentLayoutPosition(0) + scrollDistance;
1623 float minLayoutPosition = mActiveLayout->GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), Self().GetCurrentSize());
1624 self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX, Vector2(0.0f, -minLayoutPosition));
1625 float clamppedPosition = std::min(0.0f, std::max(minLayoutPosition, positionDelta));
1626 overshoot = positionDelta - clamppedPosition;
1629 return overshoot > 0.0f ? std::min(overshoot, 1.0f) : std::max(overshoot, -1.0f);
1632 void ItemView::AnimateScrollOvershoot(float overshootAmount, bool animateBack)
1634 bool animatingOn = fabsf(overshootAmount) > Math::MACHINE_EPSILON_1;
1636 // make sure we animate back if needed
1637 mAnimateOvershootOff = animateBack || (!animatingOn && mAnimatingOvershootOn);
1639 if( mAnimatingOvershootOn )
1641 // animating on, do not allow animate off
1645 Actor self = Self();
1647 if(mOvershootAnimationSpeed > Math::MACHINE_EPSILON_0)
1649 float currentOvershoot = DevelHandle::GetCurrentProperty< float >( self, Toolkit::ItemView::Property::OVERSHOOT );
1650 float duration = 0.0f;
1652 if (mOvershootOverlay)
1654 duration = mOvershootOverlay.GetCurrentSize().height * (animatingOn ? (1.0f - fabsf(currentOvershoot)) : fabsf(currentOvershoot)) / mOvershootAnimationSpeed;
1657 // Mark the animation as in progress to prevent manual property sets overwriting it.
1658 mInAnimation = true;
1659 mAnimatingOvershootOn = animatingOn;
1660 RemoveAnimation(mScrollOvershootAnimation);
1661 mScrollOvershootAnimation = Animation::New(duration);
1662 mScrollOvershootAnimation.FinishedSignal().Connect(this, &ItemView::OnOvershootOnFinished);
1663 mScrollOvershootAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::OVERSHOOT), overshootAmount, TimePeriod(0.0f, duration) );
1664 mScrollOvershootAnimation.Play();
1668 self.SetProperty( Toolkit::ItemView::Property::OVERSHOOT, overshootAmount );
1672 void ItemView::SetItemsParentOrigin( const Vector3& parentOrigin )
1674 if( parentOrigin != mItemsParentOrigin )
1676 mItemsParentOrigin = parentOrigin;
1677 for (ItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
1679 iter->second.SetParentOrigin(parentOrigin);
1684 Vector3 ItemView::GetItemsParentOrigin() const
1686 return mItemsParentOrigin;
1689 void ItemView::SetItemsAnchorPoint( const Vector3& anchorPoint )
1691 if( anchorPoint != mItemsAnchorPoint )
1693 mItemsAnchorPoint = anchorPoint;
1694 for (ItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
1696 iter->second.SetAnchorPoint(anchorPoint);
1701 Vector3 ItemView::GetItemsAnchorPoint() const
1703 return mItemsAnchorPoint;
1706 void ItemView::GetItemsRange(ItemRange& range)
1708 if( !mItemPool.empty() )
1710 range.begin = mItemPool.begin()->first;
1711 range.end = mItemPool.rbegin()->first + 1;
1720 bool ItemView::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
1722 Dali::BaseHandle handle( object );
1724 bool connected( true );
1725 Toolkit::ItemView itemView = Toolkit::ItemView::DownCast( handle );
1727 if( 0 == strcmp( signalName.c_str(), LAYOUT_ACTIVATED_SIGNAL ) )
1729 itemView.LayoutActivatedSignal().Connect( tracker, functor );
1733 // signalName does not match any signal
1740 void ItemView::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
1742 Toolkit::ItemView itemView = Toolkit::ItemView::DownCast( Dali::BaseHandle( object ) );
1746 ItemView& itemViewImpl( GetImpl( itemView ) );
1749 case Toolkit::ItemView::Property::MINIMUM_SWIPE_SPEED:
1751 itemViewImpl.SetMinimumSwipeSpeed( value.Get<float>() );
1754 case Toolkit::ItemView::Property::MINIMUM_SWIPE_DISTANCE:
1756 itemViewImpl.SetMinimumSwipeDistance( value.Get<float>() );
1759 case Toolkit::ItemView::Property::WHEEL_SCROLL_DISTANCE_STEP:
1761 itemViewImpl.SetWheelScrollDistanceStep( value.Get<float>() );
1764 case Toolkit::ItemView::Property::SNAP_TO_ITEM_ENABLED:
1766 itemViewImpl.SetAnchoring( value.Get<bool>() );
1769 case Toolkit::ItemView::Property::REFRESH_INTERVAL:
1771 itemViewImpl.SetRefreshInterval( value.Get<float>() );
1774 case Toolkit::DevelItemView::Property::LAYOUT:
1776 // Get a Property::Array from the property if possible.
1777 Property::Array layoutArray;
1778 if( value.Get( layoutArray ) )
1780 itemViewImpl.SetLayoutArray( layoutArray );
1788 Property::Array ItemView::GetLayoutArray()
1790 return mlayoutArray;
1793 void ItemView::SetLayoutArray( const Property::Array& layouts )
1795 mlayoutArray = layouts;
1796 const int layoutCount = GetLayoutCount();
1797 if( layoutCount > 0 )
1799 for(int index = layoutCount - 1; index >= 0; --index)
1801 RemoveLayout(index);
1802 if(index == 0) break;
1806 for( unsigned int arrayIdx = 0, arrayCount = layouts.Count(); arrayIdx < arrayCount; ++arrayIdx )
1808 const Property::Value& element = layouts.GetElementAt( arrayIdx );
1810 Property::Map* layout = element.GetMap();
1811 if( layout != NULL )
1813 for( unsigned int mapIdx = 0, mapCount = (*layout).Count(); mapIdx < mapCount; ++mapIdx )
1815 KeyValuePair propertyPair( (*layout).GetKeyValue( mapIdx ) );
1817 if(propertyPair.first == DefaultItemLayoutProperty::TYPE)
1819 int layoutType = propertyPair.second.Get<int>();
1820 if(layoutType <= DefaultItemLayout::SPIRAL && layoutType >= DefaultItemLayout::DEPTH)
1822 //DEPTH, GRID, LIST, SPIRAL
1823 switch(DefaultItemLayout::Type(layoutType))
1825 case DefaultItemLayout::DEPTH:
1827 Internal::DepthLayoutPtr depthLayout = Internal::DepthLayout::New();
1828 (*depthLayout).SetLayoutProperties(*layout);
1829 (*depthLayout).SetDepthLayoutProperties(*layout);
1830 AddLayout(*depthLayout);
1833 case DefaultItemLayout::GRID:
1835 Internal::GridLayoutPtr gridLayout = Internal::GridLayout::New();
1836 (*gridLayout).SetLayoutProperties(*layout);
1837 (*gridLayout).SetGridLayoutProperties(*layout);
1838 AddLayout(*gridLayout);
1841 case DefaultItemLayout::LIST:
1843 Internal::GridLayoutPtr listLayout = Internal::GridLayout::New();
1844 listLayout->SetNumberOfColumns( 1 );
1845 (*listLayout).SetLayoutProperties(*layout);
1846 (*listLayout).SetGridLayoutProperties(*layout);
1847 AddLayout(*listLayout);
1850 case DefaultItemLayout::SPIRAL:
1852 Internal::SpiralLayoutPtr spiralLayout = Internal::SpiralLayout::New();
1853 (*spiralLayout).SetLayoutProperties(*layout);
1854 (*spiralLayout).SetSpiralLayoutProperties(*layout);
1855 AddLayout(*spiralLayout);
1866 Property::Value ItemView::GetProperty( BaseObject* object, Property::Index index )
1868 Property::Value value;
1870 Toolkit::ItemView itemView = Toolkit::ItemView::DownCast( Dali::BaseHandle( object ) );
1874 ItemView& itemViewImpl( GetImpl( itemView ) );
1877 case Toolkit::ItemView::Property::MINIMUM_SWIPE_SPEED:
1879 value = itemViewImpl.GetMinimumSwipeSpeed();
1882 case Toolkit::ItemView::Property::MINIMUM_SWIPE_DISTANCE:
1884 value = itemViewImpl.GetMinimumSwipeDistance();
1887 case Toolkit::ItemView::Property::WHEEL_SCROLL_DISTANCE_STEP:
1889 value = itemViewImpl.GetWheelScrollDistanceStep();
1892 case Toolkit::ItemView::Property::SNAP_TO_ITEM_ENABLED:
1894 value = itemViewImpl.GetAnchoring();
1897 case Toolkit::ItemView::Property::REFRESH_INTERVAL:
1899 value = itemViewImpl.GetRefreshInterval();
1902 case Toolkit::DevelItemView::Property::LAYOUT:
1904 Property::Array layouts= itemViewImpl.GetLayoutArray();
1915 bool ItemView::DoAction( BaseObject* object, const std::string& actionName, const Property::Map& attributes )
1917 Dali::BaseHandle handle( object );
1919 Toolkit::ItemView itemView = Toolkit::ItemView::DownCast( handle );
1921 DALI_ASSERT_ALWAYS( itemView );
1923 if( 0 == strcmp( actionName.c_str(), ACTION_STOP_SCROLLING ) )
1925 GetImpl( itemView ).DoStopScrolling();
1927 else if ( 0 == strcmp( actionName.c_str(), ACTION_ENABLE_REFRESH ) )
1929 GetImpl( itemView ).SetRefreshNotificationEnabled( true );
1931 else if ( 0 == strcmp( actionName.c_str(), ACTION_DISABLE_REFRESH ) )
1933 GetImpl( itemView ).SetRefreshNotificationEnabled( false );
1939 void ItemView::DoStopScrolling()
1941 if( mScrollAnimation )
1943 mScrollAnimation.Stop();
1944 mScrollAnimation.Reset();
1948 void ItemView::SetRefreshNotificationEnabled( bool enabled )
1950 mRefreshNotificationEnabled = enabled;
1953 } // namespace Internal
1955 } // namespace Toolkit