2 * Copyright (c) 2020 Samsung Electronics Co., Ltd.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 #include <dali-toolkit/internal/controls/scrollable/item-view/item-view-impl.h>
22 #include <cstring> // for strcmp
24 #include <dali/public-api/actors/layer.h>
26 #include <dali/public-api/animation/constraint.h>
27 #include <dali/public-api/animation/constraints.h>
28 #include <dali/devel-api/common/stage.h>
29 #include <dali/public-api/events/wheel-event.h>
30 #include <dali/public-api/events/touch-event.h>
31 #include <dali/public-api/object/type-registry.h>
32 #include <dali/public-api/object/type-registry-helper.h>
33 #include <dali/devel-api/object/property-helper-devel.h>
36 #include <dali-toolkit/devel-api/controls/scroll-bar/scroll-bar.h>
37 #include <dali-toolkit/public-api/controls/scrollable/item-view/item-factory.h>
38 #include <dali-toolkit/public-api/controls/scrollable/item-view/default-item-layout.h>
39 #include <dali-toolkit/public-api/controls/scrollable/item-view/default-item-layout-property.h>
40 #include <dali-toolkit/internal/controls/scrollable/item-view/grid-layout.h>
41 #include <dali-toolkit/internal/controls/scrollable/item-view/depth-layout.h>
42 #include <dali-toolkit/internal/controls/scrollable/item-view/spiral-layout.h>
43 #include <dali-toolkit/internal/controls/scrollable/bouncing-effect-actor.h>
48 namespace // Unnamed namespace
51 const float DEFAULT_MINIMUM_SWIPE_SPEED = 1.0f;
52 const float DEFAULT_MINIMUM_SWIPE_DISTANCE = 3.0f;
53 const float DEFAULT_WHEEL_SCROLL_DISTANCE_STEP_PROPORTION = 0.1f;
55 const float DEFAULT_MINIMUM_SWIPE_DURATION = 0.45f;
56 const float DEFAULT_MAXIMUM_SWIPE_DURATION = 2.6f;
58 const float DEFAULT_REFRESH_INTERVAL_LAYOUT_POSITIONS = 20.0f; // 1 updates per 20 items
59 const int WHEEL_EVENT_FINISHED_TIME_OUT = 500; // 0.5 second
61 const float DEFAULT_ANCHORING_DURATION = 1.0f; // 1 second
63 const float MILLISECONDS_PER_SECONDS = 1000.0f;
65 const float OVERSHOOT_BOUNCE_ACTOR_RESIZE_THRESHOLD = 180.0f;
66 const Vector4 OVERSHOOT_OVERLAY_NINE_PATCH_BORDER(0.0f, 0.0f, 1.0f, 12.0f);
67 const float DEFAULT_KEYBOARD_FOCUS_SCROLL_DURATION = 0.2f;
69 const unsigned int OVERSHOOT_SIZE_CONSTRAINT_TAG(42);
72 * Local helper to convert pan distance (in actor coordinates) to the layout-specific scrolling direction
74 float CalculateScrollDistance(Vector2 panDistance, Toolkit::ItemLayout& layout)
76 Radian scrollDirection(layout.GetScrollDirection());
78 float cosTheta = cosf(scrollDirection);
79 float sinTheta = sinf(scrollDirection);
81 return panDistance.x * sinTheta + panDistance.y * cosTheta;
84 // Overshoot overlay constraints
85 struct OvershootOverlaySizeConstraint
87 OvershootOverlaySizeConstraint( float height )
88 : mOvershootHeight( height )
92 void operator()( Vector3& current, const PropertyInputContainer& inputs )
94 const Vector2& parentScrollDirection = inputs[0]->GetVector2();
95 const Toolkit::ControlOrientation::Type& layoutOrientation = static_cast<Toolkit::ControlOrientation::Type>(inputs[1]->GetInteger());
96 const Vector3& parentSize = inputs[2]->GetVector3();
98 if(Toolkit::IsVertical(layoutOrientation))
100 current.width = fabsf(parentScrollDirection.y) > Math::MACHINE_EPSILON_1 ? parentSize.x : parentSize.y;
104 current.width = fabsf(parentScrollDirection.x) > Math::MACHINE_EPSILON_1 ? parentSize.y : parentSize.x;
107 current.height = ( current.width > OVERSHOOT_BOUNCE_ACTOR_RESIZE_THRESHOLD ) ? mOvershootHeight : mOvershootHeight*0.5f;
110 float mOvershootHeight;
113 void OvershootOverlayRotationConstraint( Quaternion& current, const PropertyInputContainer& inputs )
115 const Vector2& parentScrollDirection = inputs[0]->GetVector2();
116 const Toolkit::ControlOrientation::Type& layoutOrientation = static_cast<Toolkit::ControlOrientation::Type>(inputs[1]->GetInteger());
117 const float parentOvershoot = inputs[2]->GetFloat();
119 float multiplier = 0;
120 if(Toolkit::IsVertical(layoutOrientation))
122 if(fabsf(parentScrollDirection.y) <= Math::MACHINE_EPSILON_1)
124 if( (layoutOrientation == Toolkit::ControlOrientation::Up && parentOvershoot < Math::MACHINE_EPSILON_0)
125 || (layoutOrientation == Toolkit::ControlOrientation::Down && parentOvershoot > Math::MACHINE_EPSILON_0) )
134 else if( (parentOvershoot > Math::MACHINE_EPSILON_0 && parentScrollDirection.y > Math::MACHINE_EPSILON_0)
135 || (parentOvershoot < Math::MACHINE_EPSILON_0 && parentScrollDirection.y < Math::MACHINE_EPSILON_0) )
146 if(fabsf(parentScrollDirection.x) <= Math::MACHINE_EPSILON_1)
148 if( (layoutOrientation == Toolkit::ControlOrientation::Left && parentOvershoot > Math::MACHINE_EPSILON_0)
149 ||(layoutOrientation == Toolkit::ControlOrientation::Right && parentOvershoot < Math::MACHINE_EPSILON_0) )
158 else if( (parentOvershoot > Math::MACHINE_EPSILON_0 && parentScrollDirection.x > Math::MACHINE_EPSILON_0)
159 || (parentOvershoot < Math::MACHINE_EPSILON_0 && parentScrollDirection.x < Math::MACHINE_EPSILON_0) )
169 current = Quaternion( Radian( multiplier * Math::PI ), Vector3::ZAXIS );
172 void OvershootOverlayPositionConstraint( Vector3& current, const PropertyInputContainer& inputs )
174 const Vector3& parentSize = inputs[0]->GetVector3();
175 const Vector2& parentScrollDirection = inputs[1]->GetVector2();
176 const Toolkit::ControlOrientation::Type& layoutOrientation = static_cast<Toolkit::ControlOrientation::Type>(inputs[2]->GetInteger());
177 const float parentOvershoot = inputs[3]->GetFloat();
179 Vector3 relativeOffset;
181 if(Toolkit::IsVertical(layoutOrientation))
183 if(fabsf(parentScrollDirection.y) <= Math::MACHINE_EPSILON_1)
185 if( (layoutOrientation == Toolkit::ControlOrientation::Up && parentOvershoot < Math::MACHINE_EPSILON_0)
186 || (layoutOrientation == Toolkit::ControlOrientation::Down && parentOvershoot > Math::MACHINE_EPSILON_0) )
188 relativeOffset = Vector3(1.0f, 0.0f, 0.0f);
192 relativeOffset =Vector3(0.0f, 1.0f, 0.0f);
195 else if( (parentOvershoot > Math::MACHINE_EPSILON_0 && parentScrollDirection.y > Math::MACHINE_EPSILON_0)
196 || (parentOvershoot < Math::MACHINE_EPSILON_0 && parentScrollDirection.y < Math::MACHINE_EPSILON_0) )
198 relativeOffset = Vector3(0.0f, 0.0f, 0.0f);
202 relativeOffset = Vector3(1.0f, 1.0f, 0.0f);
207 if(fabsf(parentScrollDirection.x) <= Math::MACHINE_EPSILON_1)
209 if( (layoutOrientation == Toolkit::ControlOrientation::Left && parentOvershoot < Math::MACHINE_EPSILON_0)
210 || (layoutOrientation == Toolkit::ControlOrientation::Right && parentOvershoot > Math::MACHINE_EPSILON_0) )
212 relativeOffset = Vector3(0.0f, 0.0f, 0.0f);
216 relativeOffset = Vector3(1.0f, 1.0f, 0.0f);
219 else if( (parentOvershoot > Math::MACHINE_EPSILON_0 && parentScrollDirection.x > Math::MACHINE_EPSILON_0)
220 || (parentOvershoot < Math::MACHINE_EPSILON_0 && parentScrollDirection.x < Math::MACHINE_EPSILON_0) )
222 relativeOffset = Vector3(0.0f, 1.0f, 0.0f);
226 relativeOffset = Vector3(1.0f, 0.0f, 0.0f);
230 current = relativeOffset * parentSize;
233 void OvershootOverlayVisibilityConstraint( bool& current, const PropertyInputContainer& inputs )
235 current = inputs[0]->GetBoolean();
238 } // unnamed namespace
249 namespace // unnamed namespace
254 DALI_TYPE_REGISTRATION_BEGIN( Toolkit::ItemView, Toolkit::Scrollable, NULL)
256 DALI_PROPERTY_REGISTRATION( Toolkit, ItemView, "minimumSwipeSpeed", FLOAT, MINIMUM_SWIPE_SPEED )
257 DALI_PROPERTY_REGISTRATION( Toolkit, ItemView, "minimumSwipeDistance", FLOAT, MINIMUM_SWIPE_DISTANCE )
258 DALI_PROPERTY_REGISTRATION( Toolkit, ItemView, "wheelScrollDistanceStep", FLOAT, WHEEL_SCROLL_DISTANCE_STEP )
259 DALI_PROPERTY_REGISTRATION( Toolkit, ItemView, "snapToItemEnabled", BOOLEAN, SNAP_TO_ITEM_ENABLED )
260 DALI_PROPERTY_REGISTRATION( Toolkit, ItemView, "refreshInterval", FLOAT, REFRESH_INTERVAL )
261 DALI_PROPERTY_REGISTRATION( Toolkit, ItemView, "layout", ARRAY, LAYOUT )
264 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "layoutPosition", FLOAT, LAYOUT_POSITION)
265 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "scrollSpeed", FLOAT, SCROLL_SPEED)
266 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "overshoot", FLOAT, OVERSHOOT)
267 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "scrollDirection", VECTOR2, SCROLL_DIRECTION)
268 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "layoutOrientation", INTEGER, LAYOUT_ORIENTATION)
269 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "scrollContentSize", FLOAT, SCROLL_CONTENT_SIZE)
271 DALI_SIGNAL_REGISTRATION( Toolkit, ItemView, "layoutActivated", LAYOUT_ACTIVATED_SIGNAL )
273 DALI_ACTION_REGISTRATION( Toolkit, ItemView, "stopScrolling", ACTION_STOP_SCROLLING )
275 DALI_ACTION_REGISTRATION( Toolkit, ItemView, "enableRefresh", ACTION_ENABLE_REFRESH )
276 DALI_ACTION_REGISTRATION( Toolkit, ItemView, "disableRefresh", ACTION_DISABLE_REFRESH )
278 DALI_TYPE_REGISTRATION_END()
280 const ItemIter FindItemById( ItemContainer& items, ItemId id )
282 for( ItemIter iter = items.begin(); items.end() != iter; ++iter )
284 if( iter->first == id )
293 void InsertToItemContainer( ItemContainer& items, Item item )
295 if( items.end() == FindItemById( items, item.first ) )
297 ItemIter iterToInsert = std::lower_bound( items.begin(), items.end(), item );
298 items.insert( iterToInsert, item );
304 * Helper to apply size constraint to mOvershootOverlay
305 * @param[in] overshootOverlay The overshootOverlay actor
306 * @param[in] The required height
308 void ApplyOvershootSizeConstraint( Actor overshootOverlay, float height )
310 Constraint constraint = Constraint::New<Vector3>( overshootOverlay, Actor::Property::SIZE, OvershootOverlaySizeConstraint( height ) );
311 constraint.AddSource( ParentSource( Dali::Toolkit::ItemView::Property::SCROLL_DIRECTION ) );
312 constraint.AddSource( ParentSource( Dali::Toolkit::ItemView::Property::LAYOUT_ORIENTATION ) );
313 constraint.AddSource( ParentSource( Dali::Actor::Property::SIZE ) );
314 constraint.SetTag( OVERSHOOT_SIZE_CONSTRAINT_TAG );
318 } // unnamed namespace
320 Dali::Toolkit::ItemView ItemView::New(ItemFactory& factory)
322 // Create the implementation
323 ItemViewPtr itemView(new ItemView(factory));
325 // Pass ownership to CustomActor via derived handle
326 Dali::Toolkit::ItemView handle(*itemView);
328 // Second-phase init of the implementation
329 // This can only be done after the CustomActor connection has been made...
330 itemView->Initialize();
335 ItemView::ItemView(ItemFactory& factory)
336 : Scrollable( ControlBehaviour( DISABLE_SIZE_NEGOTIATION | DISABLE_STYLE_CHANGE_SIGNALS | REQUIRES_KEYBOARD_NAVIGATION_SUPPORT ) ),
337 mItemFactory(factory),
338 mItemsParentOrigin(ParentOrigin::CENTER),
339 mItemsAnchorPoint(AnchorPoint::CENTER),
340 mTotalPanDisplacement(Vector2::ZERO),
342 mAnchoringDuration(DEFAULT_ANCHORING_DURATION),
343 mRefreshIntervalLayoutPositions(0.0f),
344 mMinimumSwipeSpeed(DEFAULT_MINIMUM_SWIPE_SPEED),
345 mMinimumSwipeDistance(DEFAULT_MINIMUM_SWIPE_DISTANCE),
346 mWheelScrollDistanceStep(0.0f),
347 mScrollDistance(0.0f),
349 mScrollOvershoot(0.0f),
350 mGestureState(GestureState::CLEAR),
351 mAnimatingOvershootOn(false),
352 mAnimateOvershootOff(false),
353 mAnchoringEnabled(false),
354 mRefreshOrderHint(true/*Refresh item 0 first*/),
357 mRefreshEnabled(true),
358 mRefreshNotificationEnabled(true),
363 void ItemView::OnInitialize()
365 Scrollable::OnInitialize();
369 Vector2 stageSize = Stage::GetCurrent().GetSize();
370 mWheelScrollDistanceStep = stageSize.y * DEFAULT_WHEEL_SCROLL_DISTANCE_STEP_PROPORTION;
372 self.TouchedSignal().Connect( this, &ItemView::OnTouch );
373 EnableGestureDetection(GestureType::Value(GestureType::PAN));
375 mWheelEventFinishedTimer = Timer::New( WHEEL_EVENT_FINISHED_TIME_OUT );
376 mWheelEventFinishedTimer.TickSignal().Connect( this, &ItemView::OnWheelEventFinished );
378 SetRefreshInterval(DEFAULT_REFRESH_INTERVAL_LAYOUT_POSITIONS);
380 // Connect wheel event
381 self.WheelEventSignal().Connect( this, &ItemView::OnWheelEvent );
384 ItemView::~ItemView()
388 unsigned int ItemView::GetLayoutCount() const
390 return mLayouts.size();
393 void ItemView::AddLayout(ItemLayout& layout)
395 mLayouts.push_back(ItemLayoutPtr(&layout));
398 void ItemView::RemoveLayout(unsigned int layoutIndex)
400 DALI_ASSERT_ALWAYS(layoutIndex < mLayouts.size());
402 if (mActiveLayout == mLayouts[layoutIndex].Get())
404 mActiveLayout = NULL;
407 mLayouts.erase(mLayouts.begin() + layoutIndex);
410 ItemLayoutPtr ItemView::GetLayout(unsigned int layoutIndex) const
412 return mLayouts[layoutIndex];
415 ItemLayoutPtr ItemView::GetActiveLayout() const
417 return ItemLayoutPtr(mActiveLayout);
420 float ItemView::GetCurrentLayoutPosition(unsigned int itemId) const
422 return Self().GetCurrentProperty< float >( Toolkit::ItemView::Property::LAYOUT_POSITION ) + static_cast<float>( itemId );
425 void ItemView::ActivateLayout(unsigned int layoutIndex, const Vector3& targetSize, float durationSeconds)
427 DALI_ASSERT_ALWAYS(layoutIndex < mLayouts.size());
429 mRefreshEnabled = false;
433 // The ItemView size should match the active layout size
434 self.SetProperty( Actor::Property::SIZE, targetSize);
435 mActiveLayoutTargetSize = targetSize;
437 // Switch to the new layout
438 mActiveLayout = mLayouts[layoutIndex].Get();
440 // Move the items to the new layout positions...
442 for (ConstItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
444 unsigned int itemId = iter->first;
445 Actor actor = iter->second;
447 // Remove constraints from previous layout
448 actor.RemoveConstraints();
450 mActiveLayout->ApplyConstraints(actor, itemId, targetSize, Self() );
453 mActiveLayout->GetItemSize( itemId, targetSize, size );
454 actor.SetProperty( Actor::Property::SIZE, size.GetVectorXY() );
457 // Refresh the new layout
458 ItemRange range = GetItemRange(*mActiveLayout, targetSize, GetCurrentLayoutPosition(0), false/* don't reserve extra*/);
459 AddActorsWithinRange( range, targetSize );
461 // Scroll to an appropriate layout position
463 bool scrollAnimationNeeded(false);
464 float firstItemScrollPosition(0.0f);
466 float current = GetCurrentLayoutPosition(0);
467 float minimum = ClampFirstItemPosition(current, targetSize, *mActiveLayout);
469 if (current < minimum)
471 scrollAnimationNeeded = true;
472 firstItemScrollPosition = minimum;
474 else if (mAnchoringEnabled)
476 scrollAnimationNeeded = true;
477 firstItemScrollPosition = mActiveLayout->GetClosestAnchorPosition(current);
480 if (scrollAnimationNeeded)
482 RemoveAnimation(mScrollAnimation);
483 mScrollAnimation = Animation::New(durationSeconds);
484 mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), firstItemScrollPosition, AlphaFunction::EASE_OUT );
485 mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnLayoutActivationScrollFinished);
486 mScrollAnimation.Play();
490 // Emit the layout activated signal
491 mLayoutActivatedSignal.Emit();
494 AnimateScrollOvershoot(0.0f);
495 mScrollOvershoot = 0.0f;
497 Radian scrollDirection(mActiveLayout->GetScrollDirection());
498 self.SetProperty(Toolkit::ItemView::Property::SCROLL_DIRECTION, Vector2(sinf(scrollDirection), cosf(scrollDirection)));
499 self.SetProperty(Toolkit::ItemView::Property::LAYOUT_ORIENTATION, static_cast<int>(mActiveLayout->GetOrientation()));
500 self.SetProperty(Toolkit::ItemView::Property::SCROLL_SPEED, mScrollSpeed);
502 CalculateDomainSize(targetSize);
505 void ItemView::DeactivateCurrentLayout()
509 for (ConstItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
511 Actor actor = iter->second;
512 actor.RemoveConstraints();
515 mActiveLayout = NULL;
519 void ItemView::OnRefreshNotification(PropertyNotification& source)
521 if( mRefreshNotificationEnabled )
523 // Cancel scroll animation to prevent any fighting of setting the scroll position property by scroll bar during fast scroll.
524 if(!mRefreshEnabled && mScrollAnimation)
526 RemoveAnimation(mScrollAnimation);
529 // Only cache extra items when it is not a fast scroll
530 DoRefresh(GetCurrentLayoutPosition(0), mRefreshEnabled || mScrollAnimation);
534 void ItemView::Refresh()
536 for (ConstItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter )
538 ReleaseActor( iter->first, iter->second );
542 DoRefresh(GetCurrentLayoutPosition(0), true);
545 void ItemView::DoRefresh(float currentLayoutPosition, bool cacheExtra)
549 ItemRange range = GetItemRange(*mActiveLayout, mActiveLayoutTargetSize, currentLayoutPosition, cacheExtra/*reserve extra*/);
550 RemoveActorsOutsideRange( range );
551 AddActorsWithinRange( range, Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ) );
553 mScrollUpdatedSignal.Emit( Vector2(0.0f, currentLayoutPosition) );
557 void ItemView::SetMinimumSwipeSpeed(float speed)
559 mMinimumSwipeSpeed = speed;
562 float ItemView::GetMinimumSwipeSpeed() const
564 return mMinimumSwipeSpeed;
567 void ItemView::SetMinimumSwipeDistance(float distance)
569 mMinimumSwipeDistance = distance;
572 float ItemView::GetMinimumSwipeDistance() const
574 return mMinimumSwipeDistance;
577 void ItemView::SetWheelScrollDistanceStep(float step)
579 mWheelScrollDistanceStep = step;
582 float ItemView::GetWheelScrollDistanceStep() const
584 return mWheelScrollDistanceStep;
587 void ItemView::SetAnchoring(bool enabled)
589 mAnchoringEnabled = enabled;
592 bool ItemView::GetAnchoring() const
594 return mAnchoringEnabled;
597 void ItemView::SetAnchoringDuration(float durationSeconds)
599 mAnchoringDuration = durationSeconds;
602 float ItemView::GetAnchoringDuration() const
604 return mAnchoringDuration;
607 void ItemView::SetRefreshInterval(float intervalLayoutPositions)
609 if( !Equals(mRefreshIntervalLayoutPositions, intervalLayoutPositions) )
611 mRefreshIntervalLayoutPositions = intervalLayoutPositions;
614 if(mRefreshNotification)
616 self.RemovePropertyNotification(mRefreshNotification);
618 mRefreshNotification = self.AddPropertyNotification( Toolkit::ItemView::Property::LAYOUT_POSITION, StepCondition(mRefreshIntervalLayoutPositions, 0.0f) );
619 mRefreshNotification.NotifySignal().Connect( this, &ItemView::OnRefreshNotification );
623 float ItemView::GetRefreshInterval() const
625 return mRefreshIntervalLayoutPositions;
628 void ItemView::SetRefreshEnabled(bool enabled)
630 mRefreshEnabled = enabled;
633 Actor ItemView::GetItem(unsigned int itemId) const
637 for ( ConstItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter )
639 if( iter->first == itemId )
641 actor = iter->second;
649 unsigned int ItemView::GetItemId( Actor actor ) const
651 unsigned int itemId( 0 );
653 for ( ConstItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter )
655 if( iter->second == actor )
657 itemId = iter->first;
665 void ItemView::InsertItem( Item newItem, float durationSeconds )
668 Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
670 Actor displacedActor;
671 ItemIter afterDisplacedIter = mItemPool.end();
673 ItemIter foundIter = FindItemById( mItemPool, newItem.first );
674 if( mItemPool.end() != foundIter )
676 SetupActor( newItem, layoutSize );
677 Self().Add( newItem.second );
679 displacedActor = foundIter->second;
680 foundIter->second = newItem.second;
682 afterDisplacedIter = ++foundIter;
686 // Inserting before the existing item range?
687 ItemIter iter = mItemPool.begin();
688 if( iter != mItemPool.end() &&
689 iter->first > newItem.first )
691 displacedActor = iter->second;
692 iter = mItemPool.erase( iter ); // iter is still valid after the erase
694 afterDisplacedIter = iter;
700 // Move the existing actors to make room
701 for( ItemIter iter = afterDisplacedIter; mItemPool.end() != iter; ++iter )
703 Actor temp = iter->second;
704 iter->second = displacedActor;
705 displacedActor = temp;
707 iter->second.RemoveConstraints();
708 mActiveLayout->ApplyConstraints( iter->second, iter->first, layoutSize, Self() );
712 ItemContainer::reverse_iterator lastIter = mItemPool.rbegin();
713 if ( lastIter != mItemPool.rend() )
715 ItemId lastId = lastIter->first;
716 Item lastItem( lastId + 1, displacedActor );
717 InsertToItemContainer( mItemPool, lastItem );
719 lastItem.second.RemoveConstraints();
720 mActiveLayout->ApplyConstraints( lastItem.second, lastItem.first, layoutSize, Self() );
724 CalculateDomainSize( layoutSize );
726 mAddingItems = false;
729 void ItemView::InsertItems( const ItemContainer& newItems, float durationSeconds )
732 Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
734 // Insert from lowest id to highest
735 ItemContainer sortedItems(newItems);
736 std::sort( sortedItems.begin(), sortedItems.end() );
738 for( ItemIter iter = sortedItems.begin(); sortedItems.end() != iter; ++iter )
740 Self().Add( iter->second );
742 ItemIter foundIter = FindItemById( mItemPool, iter->first );
743 if( mItemPool.end() != foundIter )
745 Actor moveMe = foundIter->second;
746 foundIter->second = iter->second;
748 // Move the existing actors to make room
749 for( ItemIter iter = ++foundIter; mItemPool.end() != iter; ++iter )
751 Actor temp = iter->second;
752 iter->second = moveMe;
757 ItemId lastId = mItemPool.rbegin()->first;
758 Item lastItem( lastId + 1, moveMe );
759 InsertToItemContainer( mItemPool, lastItem );
763 InsertToItemContainer( mItemPool, *iter );
767 // Relayout everything
768 for (ItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
771 if( std::binary_search( sortedItems.begin(), sortedItems.end(), *iter ) )
773 SetupActor( *iter, layoutSize );
777 iter->second.RemoveConstraints();
778 mActiveLayout->ApplyConstraints( iter->second, iter->first, layoutSize, Self() );
782 CalculateDomainSize( layoutSize );
784 mAddingItems = false;
787 void ItemView::RemoveItem( unsigned int itemId, float durationSeconds )
789 bool actorsReordered = RemoveActor( itemId );
790 if( actorsReordered )
792 ReapplyAllConstraints();
798 void ItemView::RemoveItems( const ItemIdContainer& itemIds, float durationSeconds )
800 bool actorsReordered( false );
802 // Remove from highest id to lowest
803 ItemIdContainer sortedItems(itemIds);
804 std::sort( sortedItems.begin(), sortedItems.end() );
806 for( ItemIdContainer::reverse_iterator iter = sortedItems.rbegin(); sortedItems.rend() != iter; ++iter )
808 if( RemoveActor( *iter ) )
810 actorsReordered = true;
814 if( actorsReordered )
816 ReapplyAllConstraints();
822 bool ItemView::RemoveActor(unsigned int itemId)
824 bool reordered( false );
826 ItemIter removeIter = FindItemById( mItemPool, itemId );
827 if( removeIter != mItemPool.end() )
829 ReleaseActor(itemId, removeIter->second);
833 // Removing before the existing item range?
834 ItemIter iter = mItemPool.begin();
835 if( iter != mItemPool.end() &&
836 iter->first > itemId )
838 // In order to decrement the first visible item ID
839 InsertToItemContainer( mItemPool, Item(iter->first - 1, Actor()) );
841 removeIter = mItemPool.begin();
845 if( removeIter != mItemPool.end() )
849 // Adjust the remaining item IDs, for example if item 2 is removed:
850 // Initial actors: After insert:
851 // ID 1 - ActorA ID 1 - ActorA
852 // ID 2 - ActorB ID 2 - ActorC (previously ID 3)
853 // ID 3 - ActorC ID 3 - ActorB (previously ID 4)
855 for (ItemIter iter = removeIter; iter != mItemPool.end(); ++iter)
857 if( iter->first < mItemPool.rbegin()->first )
859 iter->second = ( iter + 1 )->second;
863 mItemPool.erase( iter );
872 void ItemView::ReplaceItem( Item replacementItem, float durationSeconds )
875 Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
877 SetupActor( replacementItem, layoutSize );
878 Self().Add( replacementItem.second );
880 const ItemIter iter = FindItemById( mItemPool, replacementItem.first );
881 if( mItemPool.end() != iter )
883 ReleaseActor(iter->first, iter->second);
884 iter->second = replacementItem.second;
888 InsertToItemContainer( mItemPool, replacementItem );
891 CalculateDomainSize( layoutSize );
893 mAddingItems = false;
896 void ItemView::ReplaceItems( const ItemContainer& replacementItems, float durationSeconds )
898 for( ConstItemIter iter = replacementItems.begin(); replacementItems.end() != iter; ++iter )
900 ReplaceItem( *iter, durationSeconds );
904 void ItemView::RemoveActorsOutsideRange( ItemRange range )
906 // Remove unwanted actors from the ItemView & ItemPool
907 for (ItemIter iter = mItemPool.begin(); iter != mItemPool.end(); )
909 unsigned int current = iter->first;
911 if( ! range.Within( current ) )
913 ReleaseActor(iter->first, iter->second);
915 iter = mItemPool.erase( iter ); // iter is still valid after the erase
924 void ItemView::AddActorsWithinRange( ItemRange range, const Vector3& layoutSize )
926 range.end = std::min(mItemFactory.GetNumberOfItems(), range.end);
928 // The order of addition depends on the scroll direction.
929 if (mRefreshOrderHint)
931 for (unsigned int itemId = range.begin; itemId < range.end; ++itemId)
933 AddNewActor( itemId, layoutSize );
938 for (unsigned int itemId = range.end; itemId > range.begin; --itemId)
940 AddNewActor( itemId-1, layoutSize );
944 // Total number of items may change dynamically.
945 // Always recalculate the domain size to reflect that.
946 CalculateDomainSize(Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ));
949 void ItemView::AddNewActor( unsigned int itemId, const Vector3& layoutSize )
953 if( mItemPool.end() == FindItemById( mItemPool, itemId ) )
955 Actor actor = mItemFactory.NewItem( itemId );
959 Item newItem( itemId, actor );
961 InsertToItemContainer( mItemPool, newItem );
963 SetupActor( newItem, layoutSize );
968 mAddingItems = false;
971 void ItemView::SetupActor( Item item, const Vector3& layoutSize )
973 item.second.SetProperty( Actor::Property::PARENT_ORIGIN, mItemsParentOrigin );
974 item.second.SetProperty( Actor::Property::ANCHOR_POINT, mItemsAnchorPoint );
979 mActiveLayout->GetItemSize( item.first, mActiveLayoutTargetSize, size );
980 item.second.SetProperty( Actor::Property::SIZE, size.GetVectorXY() );
982 mActiveLayout->ApplyConstraints( item.second, item.first, layoutSize, Self() );
986 void ItemView::ReleaseActor( ItemId item, Actor actor )
988 Self().Remove( actor );
989 mItemFactory.ItemReleased(item, actor);
992 ItemRange ItemView::GetItemRange(ItemLayout& layout, const Vector3& layoutSize, float layoutPosition, bool reserveExtra)
994 unsigned int itemCount = mItemFactory.GetNumberOfItems();
996 ItemRange available(0u, itemCount);
998 ItemRange range = layout.GetItemsWithinArea( layoutPosition, layoutSize );
1002 // Add the reserve items for scrolling
1003 unsigned int extra = layout.GetReserveItemCount(layoutSize);
1004 range.begin = (range.begin >= extra) ? (range.begin - extra) : 0u;
1008 return range.Intersection(available);
1011 void ItemView::OnChildAdd(Actor& child)
1015 // We don't want to do this downcast check for any item added by ItemView itself.
1016 Dali::Toolkit::ScrollBar scrollBar = Dali::Toolkit::ScrollBar::DownCast(child);
1019 scrollBar.SetScrollPropertySource(Self(),
1020 Toolkit::ItemView::Property::LAYOUT_POSITION,
1021 Toolkit::Scrollable::Property::SCROLL_POSITION_MIN_Y,
1022 Toolkit::Scrollable::Property::SCROLL_POSITION_MAX_Y,
1023 Toolkit::ItemView::Property::SCROLL_CONTENT_SIZE);
1027 Scrollable::OnChildAdd( child );
1030 bool ItemView::OnWheelEvent(Actor actor, const WheelEvent& event)
1032 // Respond the wheel event to scroll
1035 Actor self = Self();
1036 const Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
1037 float layoutPositionDelta = GetCurrentLayoutPosition(0) - (event.GetDelta() * mWheelScrollDistanceStep * mActiveLayout->GetScrollSpeedFactor());
1038 float firstItemScrollPosition = ClampFirstItemPosition(layoutPositionDelta, layoutSize, *mActiveLayout);
1040 self.SetProperty(Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1042 mScrollStartedSignal.Emit(GetCurrentScrollPosition());
1043 mRefreshEnabled = true;
1046 if (mWheelEventFinishedTimer.IsRunning())
1048 mWheelEventFinishedTimer.Stop();
1051 mWheelEventFinishedTimer.Start();
1056 bool ItemView::OnWheelEventFinished()
1060 RemoveAnimation(mScrollAnimation);
1062 // No more wheel events coming. Do the anchoring if enabled.
1063 mScrollAnimation = DoAnchoring();
1064 if (mScrollAnimation)
1066 mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
1067 mScrollAnimation.Play();
1071 mScrollOvershoot = 0.0f;
1072 AnimateScrollOvershoot(0.0f);
1074 mScrollCompletedSignal.Emit(GetCurrentScrollPosition());
1081 void ItemView::ReapplyAllConstraints()
1083 Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
1085 for (ConstItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
1087 unsigned int id = iter->first;
1088 Actor actor = iter->second;
1090 actor.RemoveConstraints();
1091 mActiveLayout->ApplyConstraints(actor, id, layoutSize, Self());
1095 void ItemView::OnItemsRemoved()
1097 CalculateDomainSize(Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ));
1099 // Adjust scroll-position after an item is removed
1102 float firstItemScrollPosition = ClampFirstItemPosition(GetCurrentLayoutPosition(0), Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ), *mActiveLayout);
1103 Self().SetProperty( Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1107 float ItemView::ClampFirstItemPosition( float targetPosition, const Vector3& targetSize, ItemLayout& layout, bool updateOvershoot )
1109 Actor self = Self();
1110 float minLayoutPosition = layout.GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), targetSize);
1111 float clamppedPosition = std::min(0.0f, std::max(minLayoutPosition, targetPosition));
1112 self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX, Vector2(0.0f, -minLayoutPosition));
1114 if( updateOvershoot )
1116 mScrollOvershoot = targetPosition - clamppedPosition;
1119 return clamppedPosition;
1122 bool ItemView::OnTouch( Actor actor, const TouchEvent& touch )
1124 // Ignore events with multiple-touch points
1125 if (touch.GetPointCount() != 1)
1130 if ( touch.GetState( 0 ) == PointState::DOWN )
1132 // Cancel ongoing scrolling etc.
1133 mGestureState = GestureState::CLEAR;
1135 mScrollDistance = 0.0f;
1136 mScrollSpeed = 0.0f;
1137 Self().SetProperty(Toolkit::ItemView::Property::SCROLL_SPEED, mScrollSpeed);
1139 mScrollOvershoot = 0.0f;
1140 AnimateScrollOvershoot(0.0f);
1142 if(mScrollAnimation)
1144 mScrollCompletedSignal.Emit(GetCurrentScrollPosition());
1147 RemoveAnimation(mScrollAnimation);
1150 return false; // Do not consume as we're potentially scrolling (detecting pan gestures)
1153 void ItemView::OnPan( const PanGesture& gesture )
1155 Actor self = Self();
1156 const Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
1158 RemoveAnimation(mScrollAnimation);
1160 // Short-circuit if there is no active layout
1163 mGestureState = GestureState::CLEAR;
1167 mGestureState = gesture.GetState();
1169 switch (mGestureState)
1171 case GestureState::FINISHED:
1174 if (fabsf(mScrollDistance) > mMinimumSwipeDistance &&
1175 mScrollSpeed > mMinimumSwipeSpeed)
1177 float direction = (mScrollDistance < 0.0f) ? -1.0f : 1.0f;
1179 mRefreshOrderHint = true;
1181 float currentLayoutPosition = GetCurrentLayoutPosition(0);
1182 float firstItemScrollPosition = ClampFirstItemPosition(currentLayoutPosition + mScrollSpeed * direction,
1186 if (mAnchoringEnabled)
1188 firstItemScrollPosition = mActiveLayout->GetClosestAnchorPosition(firstItemScrollPosition);
1191 RemoveAnimation(mScrollAnimation);
1193 float flickAnimationDuration = Clamp( mActiveLayout->GetItemFlickAnimationDuration() * std::max(1.0f, fabsf(firstItemScrollPosition - GetCurrentLayoutPosition(0)))
1194 , DEFAULT_MINIMUM_SWIPE_DURATION, DEFAULT_MAXIMUM_SWIPE_DURATION);
1196 mScrollAnimation = Animation::New(flickAnimationDuration);
1197 mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION ), firstItemScrollPosition, AlphaFunction::EASE_OUT );
1198 mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::SCROLL_SPEED), 0.0f, AlphaFunction::EASE_OUT );
1202 // Check whether it has already scrolled to the end
1203 if( fabs(currentLayoutPosition - firstItemScrollPosition) < Math::MACHINE_EPSILON_0 )
1205 AnimateScrollOvershoot( 0.0f );
1206 RemoveAnimation( mScrollAnimation );
1210 // Anchoring may be triggered when there was no swipe
1211 if (!mScrollAnimation)
1213 mScrollAnimation = DoAnchoring();
1216 // Reset the overshoot if no scroll animation.
1217 if (!mScrollAnimation)
1219 mScrollCompletedSignal.Emit(GetCurrentScrollPosition());
1221 AnimateScrollOvershoot(0.0f, false);
1226 case GestureState::STARTED: // Fall through
1228 mTotalPanDisplacement = Vector2::ZERO;
1229 mScrollStartedSignal.Emit(GetCurrentScrollPosition());
1230 mRefreshEnabled = true;
1233 case GestureState::CONTINUING:
1235 const Vector2& displacement = gesture.GetDisplacement();
1236 mScrollDistance = CalculateScrollDistance(displacement, *mActiveLayout);
1237 mScrollSpeed = Clamp((gesture.GetSpeed() * gesture.GetSpeed() * mActiveLayout->GetFlickSpeedFactor() * MILLISECONDS_PER_SECONDS), 0.0f, mActiveLayout->GetMaximumSwipeSpeed());
1239 // Refresh order depends on the direction of the scroll; negative is towards the last item.
1240 mRefreshOrderHint = mScrollDistance < 0.0f;
1242 float layoutPositionDelta = GetCurrentLayoutPosition(0) + (mScrollDistance * mActiveLayout->GetScrollSpeedFactor());
1244 float firstItemScrollPosition = ClampFirstItemPosition(layoutPositionDelta, layoutSize, *mActiveLayout);
1246 float currentOvershoot = self.GetCurrentProperty< float >( Toolkit::ItemView::Property::OVERSHOOT );
1248 self.SetProperty(Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1250 if( ( firstItemScrollPosition >= 0.0f &&
1251 currentOvershoot < 1.0f ) ||
1252 ( firstItemScrollPosition <= mActiveLayout->GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), layoutSize) &&
1253 currentOvershoot > -1.0f ) )
1255 mTotalPanDisplacement += displacement;
1258 mScrollOvershoot = CalculateScrollOvershoot();
1260 // If the view is moved in a direction against the overshoot indicator, then the indicator should be animated off.
1261 // First make sure we are not in an animation, otherwise a previously started
1262 // off-animation will be overwritten as the user continues scrolling.
1265 // Check if the movement is against the current overshoot amount (if we are currently displaying the indicator).
1266 if( ( ( mScrollOvershoot > Math::MACHINE_EPSILON_0 ) && ( mScrollDistance < -Math::MACHINE_EPSILON_0 ) ) ||
1267 ( ( mScrollOvershoot < Math::MACHINE_EPSILON_0 ) && ( mScrollDistance > Math::MACHINE_EPSILON_0 ) ) )
1269 // The user has moved against the indicator direction.
1270 // First, we reset the total displacement. This means the overshoot amount will become zero the next frame,
1271 // and if the user starts dragging in the overshoot direction again, the indicator will appear once more.
1272 mTotalPanDisplacement = Vector2::ZERO;
1273 // Animate the overshoot indicator off.
1274 AnimateScrollOvershoot( 0.0f, false );
1278 // Only set the property directly if we are not animating the overshoot away,
1279 // as otherwise this will overwrite the animation generated value.
1280 self.SetProperty( Toolkit::ItemView::Property::OVERSHOOT, mScrollOvershoot );
1286 case GestureState::CANCELLED:
1288 mScrollAnimation = DoAnchoring();
1296 if (mScrollAnimation)
1298 mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
1299 mScrollAnimation.Play();
1303 bool ItemView::OnAccessibilityPan(PanGesture gesture)
1309 Actor ItemView::GetNextKeyboardFocusableActor(Actor actor, Toolkit::Control::KeyboardFocus::Direction direction, bool loopEnabled)
1311 Actor nextFocusActor;
1315 if(!actor || actor == this->Self())
1317 nextFocusActor = GetItem(nextItemID);
1319 else if(actor && actor.GetParent() == this->Self())
1321 int itemID = GetItemId(actor);
1322 nextItemID = mActiveLayout->GetNextFocusItemID(itemID, mItemFactory.GetNumberOfItems(), direction, loopEnabled);
1323 nextFocusActor = GetItem(nextItemID);
1324 if(nextFocusActor == actor)
1326 // need to pass NULL actor back to focus manager
1327 nextFocusActor.Reset();
1328 return nextFocusActor;
1331 float layoutPosition = mActiveLayout->GetClosestAnchorPosition( GetCurrentLayoutPosition(0) );
1332 Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
1335 // likely the current item is not buffered, so not in our item pool, probably best to get first viewable item
1336 ItemRange viewableItems = mActiveLayout->GetItemsWithinArea(layoutPosition, layoutSize);
1337 nextItemID = viewableItems.begin;
1338 nextFocusActor = GetItem(nextItemID);
1341 return nextFocusActor;
1344 void ItemView::OnKeyboardFocusChangeCommitted(Actor commitedFocusableActor)
1346 // only in this function if our chosen focus actor was actually used
1347 if(commitedFocusableActor)
1349 int nextItemID = GetItemId(commitedFocusableActor);
1350 float layoutPosition = GetCurrentLayoutPosition(0);
1351 Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
1353 float scrollTo = mActiveLayout->GetClosestOnScreenLayoutPosition(nextItemID, layoutPosition, layoutSize);
1354 ScrollTo(Vector2(0.0f, scrollTo), DEFAULT_KEYBOARD_FOCUS_SCROLL_DURATION);
1358 Animation ItemView::DoAnchoring()
1360 Animation anchoringAnimation;
1361 Actor self = Self();
1363 if (mActiveLayout && mAnchoringEnabled)
1365 float anchorPosition = mActiveLayout->GetClosestAnchorPosition( GetCurrentLayoutPosition(0) );
1367 anchoringAnimation = Animation::New(mAnchoringDuration);
1368 anchoringAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), anchorPosition, AlphaFunction::EASE_OUT );
1369 anchoringAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::SCROLL_SPEED), 0.0f, AlphaFunction::EASE_OUT );
1372 AnimateScrollOvershoot(0.0f);
1376 return anchoringAnimation;
1379 void ItemView::OnScrollFinished(Animation& source)
1381 Actor self = Self();
1383 RemoveAnimation(mScrollAnimation); // mScrollAnimation is used to query whether we're scrolling
1385 mScrollCompletedSignal.Emit(GetCurrentScrollPosition());
1387 if(mIsFlicking && fabsf(mScrollOvershoot) > Math::MACHINE_EPSILON_1)
1389 AnimateScrollOvershoot( mScrollOvershoot > 0.0f ? 1.0f : -1.0f, true);
1393 // Reset the overshoot
1394 AnimateScrollOvershoot( 0.0f );
1396 mIsFlicking = false;
1398 mScrollOvershoot = 0.0f;
1401 void ItemView::OnLayoutActivationScrollFinished(Animation& source)
1403 RemoveAnimation(mScrollAnimation);
1404 mRefreshEnabled = true;
1405 DoRefresh(GetCurrentLayoutPosition(0), true);
1407 // Emit the layout activated signal
1408 mLayoutActivatedSignal.Emit();
1411 void ItemView::OnOvershootOnFinished(Animation& animation)
1413 mAnimatingOvershootOn = false;
1414 mScrollOvershootAnimation.FinishedSignal().Disconnect(this, &ItemView::OnOvershootOnFinished);
1415 RemoveAnimation(mScrollOvershootAnimation);
1416 if(mAnimateOvershootOff)
1418 AnimateScrollOvershoot(0.0f);
1420 mInAnimation = false;
1423 void ItemView::ScrollToItem(unsigned int itemId, float durationSeconds)
1425 Actor self = Self();
1426 const Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
1427 float firstItemScrollPosition = ClampFirstItemPosition(mActiveLayout->GetItemScrollToPosition(itemId), layoutSize, *mActiveLayout);
1429 if(durationSeconds > 0.0f)
1431 RemoveAnimation(mScrollAnimation);
1432 mScrollAnimation = Animation::New(durationSeconds);
1433 mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), firstItemScrollPosition, mScrollToAlphaFunction );
1434 mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
1435 mScrollAnimation.Play();
1439 self.SetProperty( Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1440 AnimateScrollOvershoot(0.0f);
1443 mScrollStartedSignal.Emit(GetCurrentScrollPosition());
1444 mRefreshEnabled = true;
1447 void ItemView::RemoveAnimation(Animation& animation)
1451 // Cease animating, and reset handle.
1457 void ItemView::CalculateDomainSize(const Vector3& layoutSize)
1459 Actor self = Self();
1461 Vector3 firstItemPosition(Vector3::ZERO);
1462 Vector3 lastItemPosition(Vector3::ZERO);
1466 firstItemPosition = mActiveLayout->GetItemPosition( 0,0,layoutSize );
1468 float minLayoutPosition = mActiveLayout->GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), layoutSize);
1469 lastItemPosition = mActiveLayout->GetItemPosition( fabs(minLayoutPosition),fabs(minLayoutPosition),layoutSize );
1473 if(IsHorizontal(mActiveLayout->GetOrientation()))
1475 domainSize = fabs(firstItemPosition.x - lastItemPosition.x);
1479 domainSize = fabs(firstItemPosition.y - lastItemPosition.y);
1482 self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MIN, Vector2::ZERO);
1483 self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX, Vector2(0.0f, -minLayoutPosition));
1485 self.SetProperty(Toolkit::ItemView::Property::SCROLL_CONTENT_SIZE, domainSize);
1487 bool isLayoutScrollable = IsLayoutScrollable(layoutSize);
1488 self.SetProperty(Toolkit::Scrollable::Property::CAN_SCROLL_VERTICAL, isLayoutScrollable);
1489 self.SetProperty(Toolkit::Scrollable::Property::CAN_SCROLL_HORIZONTAL, false);
1493 bool ItemView::IsLayoutScrollable(const Vector3& layoutSize)
1495 Actor self = Self();
1497 float currentLayoutPosition = ClampFirstItemPosition( GetCurrentLayoutPosition(0), layoutSize, *mActiveLayout, false );
1498 float forwardClampedPosition = ClampFirstItemPosition( currentLayoutPosition + 1.0, layoutSize, *mActiveLayout, false );
1499 float backwardClampedPosition = ClampFirstItemPosition( currentLayoutPosition - 1.0, layoutSize, *mActiveLayout, false );
1501 return (fabs(forwardClampedPosition - backwardClampedPosition) > Math::MACHINE_EPSILON_0);
1504 float ItemView::GetScrollPosition(float layoutPosition, const Vector3& layoutSize) const
1506 Vector3 firstItemPosition( mActiveLayout->GetItemPosition(0, layoutPosition, layoutSize ) );
1507 return IsHorizontal(mActiveLayout->GetOrientation()) ? firstItemPosition.x: firstItemPosition.y;
1510 Vector2 ItemView::GetCurrentScrollPosition() const
1512 return Vector2(0.0f, GetScrollPosition(GetCurrentLayoutPosition(0), Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE )));
1515 void ItemView::AddOverlay(Actor actor)
1517 actor.SetProperty( Actor::Property::DRAW_MODE, DrawMode::OVERLAY_2D );
1521 void ItemView::RemoveOverlay(Actor actor)
1523 Self().Remove(actor);
1526 void ItemView::ScrollTo(const Vector2& position, float duration)
1528 Actor self = Self();
1529 const Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
1531 float firstItemScrollPosition = ClampFirstItemPosition(position.y, layoutSize, *mActiveLayout);
1535 RemoveAnimation(mScrollAnimation);
1536 mScrollAnimation = Animation::New(duration);
1537 mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), firstItemScrollPosition, mScrollToAlphaFunction );
1538 mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
1539 mScrollAnimation.Play();
1543 self.SetProperty( Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1544 AnimateScrollOvershoot(0.0f);
1547 mScrollStartedSignal.Emit(GetCurrentScrollPosition());
1548 mRefreshEnabled = true;
1551 void ItemView::SetOvershootSize( const Vector2& size )
1553 mOvershootSize = size;
1555 if( mOvershootOverlay )
1557 // Remove old & add new size constraint
1558 mOvershootOverlay.RemoveConstraints( OVERSHOOT_SIZE_CONSTRAINT_TAG );
1559 ApplyOvershootSizeConstraint( mOvershootOverlay, mOvershootSize.height );
1563 void ItemView::SetOvershootEffectColor( const Vector4& color )
1565 mOvershootEffectColor = color;
1566 if( mOvershootOverlay )
1568 mOvershootOverlay.SetProperty( Actor::Property::COLOR, color );
1572 void ItemView::EnableScrollOvershoot( bool enable )
1574 Actor self = Self();
1577 if( !mOvershootOverlay )
1579 Property::Index effectOvershootPropertyIndex = Property::INVALID_INDEX;
1580 mOvershootOverlay = CreateBouncingEffectActor( effectOvershootPropertyIndex );
1581 mOvershootOverlay.SetProperty( Actor::Property::COLOR,mOvershootEffectColor);
1582 mOvershootOverlay.SetProperty( Actor::Property::PARENT_ORIGIN,ParentOrigin::TOP_LEFT );
1583 mOvershootOverlay.SetProperty( Actor::Property::ANCHOR_POINT,AnchorPoint::TOP_LEFT);
1584 mOvershootOverlay.SetProperty( Actor::Property::DRAW_MODE, DrawMode::OVERLAY_2D );
1585 self.Add(mOvershootOverlay);
1587 ApplyOvershootSizeConstraint( mOvershootOverlay, mOvershootSize.height );
1589 Constraint constraint = Constraint::New<Quaternion>( mOvershootOverlay, Actor::Property::ORIENTATION, OvershootOverlayRotationConstraint );
1590 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::SCROLL_DIRECTION ) );
1591 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_ORIENTATION ) );
1592 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::OVERSHOOT ) );
1595 constraint = Constraint::New<Vector3>( mOvershootOverlay, Actor::Property::POSITION, OvershootOverlayPositionConstraint );
1596 constraint.AddSource( ParentSource( Actor::Property::SIZE ) );
1597 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::SCROLL_DIRECTION ) );
1598 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_ORIENTATION ) );
1599 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::OVERSHOOT ) );
1602 constraint = Constraint::New<bool>( mOvershootOverlay, Actor::Property::VISIBLE, OvershootOverlayVisibilityConstraint );
1603 constraint.AddSource( ParentSource( Toolkit::Scrollable::Property::CAN_SCROLL_VERTICAL ) );
1606 constraint = Constraint::New<float>( mOvershootOverlay, effectOvershootPropertyIndex, EqualToConstraint() );
1607 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::OVERSHOOT ) );
1613 if( mOvershootOverlay )
1615 self.Remove(mOvershootOverlay);
1616 mOvershootOverlay.Reset();
1621 float ItemView::CalculateScrollOvershoot()
1623 float overshoot = 0.0f;
1627 // The overshoot must be calculated from the accumulated pan gesture displacement
1628 // since the pan gesture starts.
1629 Actor self = Self();
1630 float scrollDistance = CalculateScrollDistance(mTotalPanDisplacement, *mActiveLayout) * mActiveLayout->GetScrollSpeedFactor();
1631 float positionDelta = GetCurrentLayoutPosition(0) + scrollDistance;
1632 float minLayoutPosition = mActiveLayout->GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ));
1633 self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX, Vector2(0.0f, -minLayoutPosition));
1634 float clamppedPosition = std::min(0.0f, std::max(minLayoutPosition, positionDelta));
1635 overshoot = positionDelta - clamppedPosition;
1638 return overshoot > 0.0f ? std::min(overshoot, 1.0f) : std::max(overshoot, -1.0f);
1641 void ItemView::AnimateScrollOvershoot(float overshootAmount, bool animateBack)
1643 bool animatingOn = fabsf(overshootAmount) > Math::MACHINE_EPSILON_1;
1645 // make sure we animate back if needed
1646 mAnimateOvershootOff = animateBack || (!animatingOn && mAnimatingOvershootOn);
1648 if( mAnimatingOvershootOn )
1650 // animating on, do not allow animate off
1654 Actor self = Self();
1656 if(mOvershootAnimationSpeed > Math::MACHINE_EPSILON_0)
1658 float currentOvershoot = self.GetCurrentProperty< float >( Toolkit::ItemView::Property::OVERSHOOT );
1659 float duration = 0.0f;
1661 if (mOvershootOverlay)
1663 duration = mOvershootOverlay.GetCurrentProperty< Vector3 >( Actor::Property::SIZE ).height * (animatingOn ? (1.0f - fabsf(currentOvershoot)) : fabsf(currentOvershoot)) / mOvershootAnimationSpeed;
1666 // Mark the animation as in progress to prevent manual property sets overwriting it.
1667 mInAnimation = true;
1668 mAnimatingOvershootOn = animatingOn;
1669 RemoveAnimation(mScrollOvershootAnimation);
1670 mScrollOvershootAnimation = Animation::New(duration);
1671 mScrollOvershootAnimation.FinishedSignal().Connect(this, &ItemView::OnOvershootOnFinished);
1672 mScrollOvershootAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::OVERSHOOT), overshootAmount, TimePeriod(0.0f, duration) );
1673 mScrollOvershootAnimation.Play();
1677 self.SetProperty( Toolkit::ItemView::Property::OVERSHOOT, overshootAmount );
1681 void ItemView::SetItemsParentOrigin( const Vector3& parentOrigin )
1683 if( parentOrigin != mItemsParentOrigin )
1685 mItemsParentOrigin = parentOrigin;
1686 for (ItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
1688 iter->second.SetProperty( Actor::Property::PARENT_ORIGIN,parentOrigin );
1693 Vector3 ItemView::GetItemsParentOrigin() const
1695 return mItemsParentOrigin;
1698 void ItemView::SetItemsAnchorPoint( const Vector3& anchorPoint )
1700 if( anchorPoint != mItemsAnchorPoint )
1702 mItemsAnchorPoint = anchorPoint;
1703 for (ItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
1705 iter->second.SetProperty( Actor::Property::ANCHOR_POINT,anchorPoint);
1710 Vector3 ItemView::GetItemsAnchorPoint() const
1712 return mItemsAnchorPoint;
1715 void ItemView::GetItemsRange(ItemRange& range)
1717 if( !mItemPool.empty() )
1719 range.begin = mItemPool.begin()->first;
1720 range.end = mItemPool.rbegin()->first + 1;
1729 bool ItemView::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
1731 Dali::BaseHandle handle( object );
1733 bool connected( true );
1734 Toolkit::ItemView itemView = Toolkit::ItemView::DownCast( handle );
1736 if( 0 == strcmp( signalName.c_str(), LAYOUT_ACTIVATED_SIGNAL ) )
1738 itemView.LayoutActivatedSignal().Connect( tracker, functor );
1742 // signalName does not match any signal
1749 void ItemView::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
1751 Toolkit::ItemView itemView = Toolkit::ItemView::DownCast( Dali::BaseHandle( object ) );
1755 ItemView& itemViewImpl( GetImpl( itemView ) );
1758 case Toolkit::ItemView::Property::MINIMUM_SWIPE_SPEED:
1760 itemViewImpl.SetMinimumSwipeSpeed( value.Get<float>() );
1764 case Toolkit::ItemView::Property::MINIMUM_SWIPE_DISTANCE:
1766 itemViewImpl.SetMinimumSwipeDistance( value.Get<float>() );
1770 case Toolkit::ItemView::Property::WHEEL_SCROLL_DISTANCE_STEP:
1772 itemViewImpl.SetWheelScrollDistanceStep( value.Get<float>() );
1776 case Toolkit::ItemView::Property::SNAP_TO_ITEM_ENABLED:
1778 itemViewImpl.SetAnchoring( value.Get<bool>() );
1782 case Toolkit::ItemView::Property::REFRESH_INTERVAL:
1784 itemViewImpl.SetRefreshInterval( value.Get<float>() );
1788 case Toolkit::ItemView::Property::LAYOUT:
1790 // Get a Property::Array from the property if possible.
1791 Property::Array layoutArray;
1792 if( value.Get( layoutArray ) )
1794 itemViewImpl.SetLayoutArray( layoutArray );
1802 Property::Array ItemView::GetLayoutArray()
1804 return mlayoutArray;
1807 void ItemView::SetLayoutArray( const Property::Array& layouts )
1809 mlayoutArray = layouts;
1810 const int layoutCount = GetLayoutCount();
1811 if( layoutCount > 0 )
1813 for(int index = layoutCount - 1; index >= 0; --index)
1815 RemoveLayout(index);
1816 if(index == 0) break;
1820 for( unsigned int arrayIdx = 0, arrayCount = layouts.Count(); arrayIdx < arrayCount; ++arrayIdx )
1822 const Property::Value& element = layouts.GetElementAt( arrayIdx );
1824 const Property::Map* layout = element.GetMap();
1825 if( layout != NULL )
1827 for( unsigned int mapIdx = 0, mapCount = (*layout).Count(); mapIdx < mapCount; ++mapIdx )
1829 KeyValuePair propertyPair( (*layout).GetKeyValue( mapIdx ) );
1831 if(propertyPair.first == DefaultItemLayoutProperty::TYPE)
1833 int layoutType = propertyPair.second.Get<int>();
1834 if(layoutType <= DefaultItemLayout::SPIRAL && layoutType >= DefaultItemLayout::DEPTH)
1836 //DEPTH, GRID, LIST, SPIRAL
1837 switch(DefaultItemLayout::Type(layoutType))
1839 case DefaultItemLayout::DEPTH:
1841 Internal::DepthLayoutPtr depthLayout = Internal::DepthLayout::New();
1842 (*depthLayout).SetLayoutProperties(*layout);
1843 (*depthLayout).SetDepthLayoutProperties(*layout);
1844 AddLayout(*depthLayout);
1847 case DefaultItemLayout::GRID:
1849 Internal::GridLayoutPtr gridLayout = Internal::GridLayout::New();
1850 (*gridLayout).SetLayoutProperties(*layout);
1851 (*gridLayout).SetGridLayoutProperties(*layout);
1852 AddLayout(*gridLayout);
1855 case DefaultItemLayout::LIST:
1857 Internal::GridLayoutPtr listLayout = Internal::GridLayout::New();
1858 listLayout->SetNumberOfColumns( 1 );
1859 (*listLayout).SetLayoutProperties(*layout);
1860 (*listLayout).SetGridLayoutProperties(*layout);
1861 AddLayout(*listLayout);
1864 case DefaultItemLayout::SPIRAL:
1866 Internal::SpiralLayoutPtr spiralLayout = Internal::SpiralLayout::New();
1867 (*spiralLayout).SetLayoutProperties(*layout);
1868 (*spiralLayout).SetSpiralLayoutProperties(*layout);
1869 AddLayout(*spiralLayout);
1880 Property::Value ItemView::GetProperty( BaseObject* object, Property::Index index )
1882 Property::Value value;
1884 Toolkit::ItemView itemView = Toolkit::ItemView::DownCast( Dali::BaseHandle( object ) );
1888 ItemView& itemViewImpl( GetImpl( itemView ) );
1891 case Toolkit::ItemView::Property::MINIMUM_SWIPE_SPEED:
1893 value = itemViewImpl.GetMinimumSwipeSpeed();
1897 case Toolkit::ItemView::Property::MINIMUM_SWIPE_DISTANCE:
1899 value = itemViewImpl.GetMinimumSwipeDistance();
1903 case Toolkit::ItemView::Property::WHEEL_SCROLL_DISTANCE_STEP:
1905 value = itemViewImpl.GetWheelScrollDistanceStep();
1909 case Toolkit::ItemView::Property::SNAP_TO_ITEM_ENABLED:
1911 value = itemViewImpl.GetAnchoring();
1915 case Toolkit::ItemView::Property::REFRESH_INTERVAL:
1917 value = itemViewImpl.GetRefreshInterval();
1921 case Toolkit::ItemView::Property::LAYOUT:
1923 Property::Array layouts= itemViewImpl.GetLayoutArray();
1933 bool ItemView::DoAction( BaseObject* object, const std::string& actionName, const Property::Map& attributes )
1935 Dali::BaseHandle handle( object );
1937 Toolkit::ItemView itemView = Toolkit::ItemView::DownCast( handle );
1939 DALI_ASSERT_ALWAYS( itemView );
1941 if( 0 == strcmp( actionName.c_str(), ACTION_STOP_SCROLLING ) )
1943 GetImpl( itemView ).DoStopScrolling();
1945 else if ( 0 == strcmp( actionName.c_str(), ACTION_ENABLE_REFRESH ) )
1947 GetImpl( itemView ).SetRefreshNotificationEnabled( true );
1949 else if ( 0 == strcmp( actionName.c_str(), ACTION_DISABLE_REFRESH ) )
1951 GetImpl( itemView ).SetRefreshNotificationEnabled( false );
1957 void ItemView::DoStopScrolling()
1959 if( mScrollAnimation )
1961 mScrollAnimation.Stop();
1962 mScrollAnimation.Reset();
1966 void ItemView::SetRefreshNotificationEnabled( bool enabled )
1968 mRefreshNotificationEnabled = enabled;
1971 } // namespace Internal
1973 } // namespace Toolkit