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()
367 Vector2 stageSize = Stage::GetCurrent().GetSize();
368 mWheelScrollDistanceStep = stageSize.y * DEFAULT_WHEEL_SCROLL_DISTANCE_STEP_PROPORTION;
370 self.TouchedSignal().Connect( this, &ItemView::OnTouch );
371 EnableGestureDetection(GestureType::Value(GestureType::PAN));
373 mWheelEventFinishedTimer = Timer::New( WHEEL_EVENT_FINISHED_TIME_OUT );
374 mWheelEventFinishedTimer.TickSignal().Connect( this, &ItemView::OnWheelEventFinished );
376 SetRefreshInterval(DEFAULT_REFRESH_INTERVAL_LAYOUT_POSITIONS);
378 // Connect wheel event
379 self.WheelEventSignal().Connect( this, &ItemView::OnWheelEvent );
382 ItemView::~ItemView()
386 unsigned int ItemView::GetLayoutCount() const
388 return mLayouts.size();
391 void ItemView::AddLayout(ItemLayout& layout)
393 mLayouts.push_back(ItemLayoutPtr(&layout));
396 void ItemView::RemoveLayout(unsigned int layoutIndex)
398 DALI_ASSERT_ALWAYS(layoutIndex < mLayouts.size());
400 if (mActiveLayout == mLayouts[layoutIndex].Get())
402 mActiveLayout = NULL;
405 mLayouts.erase(mLayouts.begin() + layoutIndex);
408 ItemLayoutPtr ItemView::GetLayout(unsigned int layoutIndex) const
410 return mLayouts[layoutIndex];
413 ItemLayoutPtr ItemView::GetActiveLayout() const
415 return ItemLayoutPtr(mActiveLayout);
418 float ItemView::GetCurrentLayoutPosition(unsigned int itemId) const
420 return Self().GetCurrentProperty< float >( Toolkit::ItemView::Property::LAYOUT_POSITION ) + static_cast<float>( itemId );
423 void ItemView::ActivateLayout(unsigned int layoutIndex, const Vector3& targetSize, float durationSeconds)
425 DALI_ASSERT_ALWAYS(layoutIndex < mLayouts.size());
427 mRefreshEnabled = false;
431 // The ItemView size should match the active layout size
432 self.SetProperty( Actor::Property::SIZE, targetSize);
433 mActiveLayoutTargetSize = targetSize;
435 // Switch to the new layout
436 mActiveLayout = mLayouts[layoutIndex].Get();
438 // Move the items to the new layout positions...
440 for (ConstItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
442 unsigned int itemId = iter->first;
443 Actor actor = iter->second;
445 // Remove constraints from previous layout
446 actor.RemoveConstraints();
448 mActiveLayout->ApplyConstraints(actor, itemId, targetSize, Self() );
451 mActiveLayout->GetItemSize( itemId, targetSize, size );
452 actor.SetProperty( Actor::Property::SIZE, size.GetVectorXY() );
455 // Refresh the new layout
456 ItemRange range = GetItemRange(*mActiveLayout, targetSize, GetCurrentLayoutPosition(0), false/* don't reserve extra*/);
457 AddActorsWithinRange( range, targetSize );
459 // Scroll to an appropriate layout position
461 bool scrollAnimationNeeded(false);
462 float firstItemScrollPosition(0.0f);
464 float current = GetCurrentLayoutPosition(0);
465 float minimum = ClampFirstItemPosition(current, targetSize, *mActiveLayout);
467 if (current < minimum)
469 scrollAnimationNeeded = true;
470 firstItemScrollPosition = minimum;
472 else if (mAnchoringEnabled)
474 scrollAnimationNeeded = true;
475 firstItemScrollPosition = mActiveLayout->GetClosestAnchorPosition(current);
478 if (scrollAnimationNeeded)
480 RemoveAnimation(mScrollAnimation);
481 mScrollAnimation = Animation::New(durationSeconds);
482 mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), firstItemScrollPosition, AlphaFunction::EASE_OUT );
483 mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnLayoutActivationScrollFinished);
484 mScrollAnimation.Play();
488 // Emit the layout activated signal
489 mLayoutActivatedSignal.Emit();
492 AnimateScrollOvershoot(0.0f);
493 mScrollOvershoot = 0.0f;
495 Radian scrollDirection(mActiveLayout->GetScrollDirection());
496 self.SetProperty(Toolkit::ItemView::Property::SCROLL_DIRECTION, Vector2(sinf(scrollDirection), cosf(scrollDirection)));
497 self.SetProperty(Toolkit::ItemView::Property::LAYOUT_ORIENTATION, static_cast<int>(mActiveLayout->GetOrientation()));
498 self.SetProperty(Toolkit::ItemView::Property::SCROLL_SPEED, mScrollSpeed);
500 CalculateDomainSize(targetSize);
503 void ItemView::DeactivateCurrentLayout()
507 for (ConstItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
509 Actor actor = iter->second;
510 actor.RemoveConstraints();
513 mActiveLayout = NULL;
517 void ItemView::OnRefreshNotification(PropertyNotification& source)
519 if( mRefreshNotificationEnabled )
521 // Cancel scroll animation to prevent any fighting of setting the scroll position property by scroll bar during fast scroll.
522 if(!mRefreshEnabled && mScrollAnimation)
524 RemoveAnimation(mScrollAnimation);
527 // Only cache extra items when it is not a fast scroll
528 DoRefresh(GetCurrentLayoutPosition(0), mRefreshEnabled || mScrollAnimation);
532 void ItemView::Refresh()
534 for (ConstItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter )
536 ReleaseActor( iter->first, iter->second );
540 DoRefresh(GetCurrentLayoutPosition(0), true);
543 void ItemView::DoRefresh(float currentLayoutPosition, bool cacheExtra)
547 ItemRange range = GetItemRange(*mActiveLayout, mActiveLayoutTargetSize, currentLayoutPosition, cacheExtra/*reserve extra*/);
548 RemoveActorsOutsideRange( range );
549 AddActorsWithinRange( range, Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ) );
551 mScrollUpdatedSignal.Emit( Vector2(0.0f, currentLayoutPosition) );
555 void ItemView::SetMinimumSwipeSpeed(float speed)
557 mMinimumSwipeSpeed = speed;
560 float ItemView::GetMinimumSwipeSpeed() const
562 return mMinimumSwipeSpeed;
565 void ItemView::SetMinimumSwipeDistance(float distance)
567 mMinimumSwipeDistance = distance;
570 float ItemView::GetMinimumSwipeDistance() const
572 return mMinimumSwipeDistance;
575 void ItemView::SetWheelScrollDistanceStep(float step)
577 mWheelScrollDistanceStep = step;
580 float ItemView::GetWheelScrollDistanceStep() const
582 return mWheelScrollDistanceStep;
585 void ItemView::SetAnchoring(bool enabled)
587 mAnchoringEnabled = enabled;
590 bool ItemView::GetAnchoring() const
592 return mAnchoringEnabled;
595 void ItemView::SetAnchoringDuration(float durationSeconds)
597 mAnchoringDuration = durationSeconds;
600 float ItemView::GetAnchoringDuration() const
602 return mAnchoringDuration;
605 void ItemView::SetRefreshInterval(float intervalLayoutPositions)
607 if( !Equals(mRefreshIntervalLayoutPositions, intervalLayoutPositions) )
609 mRefreshIntervalLayoutPositions = intervalLayoutPositions;
612 if(mRefreshNotification)
614 self.RemovePropertyNotification(mRefreshNotification);
616 mRefreshNotification = self.AddPropertyNotification( Toolkit::ItemView::Property::LAYOUT_POSITION, StepCondition(mRefreshIntervalLayoutPositions, 0.0f) );
617 mRefreshNotification.NotifySignal().Connect( this, &ItemView::OnRefreshNotification );
621 float ItemView::GetRefreshInterval() const
623 return mRefreshIntervalLayoutPositions;
626 void ItemView::SetRefreshEnabled(bool enabled)
628 mRefreshEnabled = enabled;
631 Actor ItemView::GetItem(unsigned int itemId) const
635 for ( ConstItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter )
637 if( iter->first == itemId )
639 actor = iter->second;
647 unsigned int ItemView::GetItemId( Actor actor ) const
649 unsigned int itemId( 0 );
651 for ( ConstItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter )
653 if( iter->second == actor )
655 itemId = iter->first;
663 void ItemView::InsertItem( Item newItem, float durationSeconds )
666 Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
668 Actor displacedActor;
669 ItemIter afterDisplacedIter = mItemPool.end();
671 ItemIter foundIter = FindItemById( mItemPool, newItem.first );
672 if( mItemPool.end() != foundIter )
674 SetupActor( newItem, layoutSize );
675 Self().Add( newItem.second );
677 displacedActor = foundIter->second;
678 foundIter->second = newItem.second;
680 afterDisplacedIter = ++foundIter;
684 // Inserting before the existing item range?
685 ItemIter iter = mItemPool.begin();
686 if( iter != mItemPool.end() &&
687 iter->first > newItem.first )
689 displacedActor = iter->second;
690 iter = mItemPool.erase( iter ); // iter is still valid after the erase
692 afterDisplacedIter = iter;
698 // Move the existing actors to make room
699 for( ItemIter iter = afterDisplacedIter; mItemPool.end() != iter; ++iter )
701 Actor temp = iter->second;
702 iter->second = displacedActor;
703 displacedActor = temp;
705 iter->second.RemoveConstraints();
706 mActiveLayout->ApplyConstraints( iter->second, iter->first, layoutSize, Self() );
710 ItemContainer::reverse_iterator lastIter = mItemPool.rbegin();
711 if ( lastIter != mItemPool.rend() )
713 ItemId lastId = lastIter->first;
714 Item lastItem( lastId + 1, displacedActor );
715 InsertToItemContainer( mItemPool, lastItem );
717 lastItem.second.RemoveConstraints();
718 mActiveLayout->ApplyConstraints( lastItem.second, lastItem.first, layoutSize, Self() );
722 CalculateDomainSize( layoutSize );
724 mAddingItems = false;
727 void ItemView::InsertItems( const ItemContainer& newItems, float durationSeconds )
730 Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
732 // Insert from lowest id to highest
733 ItemContainer sortedItems(newItems);
734 std::sort( sortedItems.begin(), sortedItems.end() );
736 for( ItemIter iter = sortedItems.begin(); sortedItems.end() != iter; ++iter )
738 Self().Add( iter->second );
740 ItemIter foundIter = FindItemById( mItemPool, iter->first );
741 if( mItemPool.end() != foundIter )
743 Actor moveMe = foundIter->second;
744 foundIter->second = iter->second;
746 // Move the existing actors to make room
747 for( ItemIter iter = ++foundIter; mItemPool.end() != iter; ++iter )
749 Actor temp = iter->second;
750 iter->second = moveMe;
755 ItemId lastId = mItemPool.rbegin()->first;
756 Item lastItem( lastId + 1, moveMe );
757 InsertToItemContainer( mItemPool, lastItem );
761 InsertToItemContainer( mItemPool, *iter );
765 // Relayout everything
766 for (ItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
769 if( std::binary_search( sortedItems.begin(), sortedItems.end(), *iter ) )
771 SetupActor( *iter, layoutSize );
775 iter->second.RemoveConstraints();
776 mActiveLayout->ApplyConstraints( iter->second, iter->first, layoutSize, Self() );
780 CalculateDomainSize( layoutSize );
782 mAddingItems = false;
785 void ItemView::RemoveItem( unsigned int itemId, float durationSeconds )
787 bool actorsReordered = RemoveActor( itemId );
788 if( actorsReordered )
790 ReapplyAllConstraints();
796 void ItemView::RemoveItems( const ItemIdContainer& itemIds, float durationSeconds )
798 bool actorsReordered( false );
800 // Remove from highest id to lowest
801 ItemIdContainer sortedItems(itemIds);
802 std::sort( sortedItems.begin(), sortedItems.end() );
804 for( ItemIdContainer::reverse_iterator iter = sortedItems.rbegin(); sortedItems.rend() != iter; ++iter )
806 if( RemoveActor( *iter ) )
808 actorsReordered = true;
812 if( actorsReordered )
814 ReapplyAllConstraints();
820 bool ItemView::RemoveActor(unsigned int itemId)
822 bool reordered( false );
824 ItemIter removeIter = FindItemById( mItemPool, itemId );
825 if( removeIter != mItemPool.end() )
827 ReleaseActor(itemId, removeIter->second);
831 // Removing before the existing item range?
832 ItemIter iter = mItemPool.begin();
833 if( iter != mItemPool.end() &&
834 iter->first > itemId )
836 // In order to decrement the first visible item ID
837 InsertToItemContainer( mItemPool, Item(iter->first - 1, Actor()) );
839 removeIter = mItemPool.begin();
843 if( removeIter != mItemPool.end() )
847 // Adjust the remaining item IDs, for example if item 2 is removed:
848 // Initial actors: After insert:
849 // ID 1 - ActorA ID 1 - ActorA
850 // ID 2 - ActorB ID 2 - ActorC (previously ID 3)
851 // ID 3 - ActorC ID 3 - ActorB (previously ID 4)
853 for (ItemIter iter = removeIter; iter != mItemPool.end(); ++iter)
855 if( iter->first < mItemPool.rbegin()->first )
857 iter->second = ( iter + 1 )->second;
861 mItemPool.erase( iter );
870 void ItemView::ReplaceItem( Item replacementItem, float durationSeconds )
873 Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
875 SetupActor( replacementItem, layoutSize );
876 Self().Add( replacementItem.second );
878 const ItemIter iter = FindItemById( mItemPool, replacementItem.first );
879 if( mItemPool.end() != iter )
881 ReleaseActor(iter->first, iter->second);
882 iter->second = replacementItem.second;
886 InsertToItemContainer( mItemPool, replacementItem );
889 CalculateDomainSize( layoutSize );
891 mAddingItems = false;
894 void ItemView::ReplaceItems( const ItemContainer& replacementItems, float durationSeconds )
896 for( ConstItemIter iter = replacementItems.begin(); replacementItems.end() != iter; ++iter )
898 ReplaceItem( *iter, durationSeconds );
902 void ItemView::RemoveActorsOutsideRange( ItemRange range )
904 // Remove unwanted actors from the ItemView & ItemPool
905 for (ItemIter iter = mItemPool.begin(); iter != mItemPool.end(); )
907 unsigned int current = iter->first;
909 if( ! range.Within( current ) )
911 ReleaseActor(iter->first, iter->second);
913 iter = mItemPool.erase( iter ); // iter is still valid after the erase
922 void ItemView::AddActorsWithinRange( ItemRange range, const Vector3& layoutSize )
924 range.end = std::min(mItemFactory.GetNumberOfItems(), range.end);
926 // The order of addition depends on the scroll direction.
927 if (mRefreshOrderHint)
929 for (unsigned int itemId = range.begin; itemId < range.end; ++itemId)
931 AddNewActor( itemId, layoutSize );
936 for (unsigned int itemId = range.end; itemId > range.begin; --itemId)
938 AddNewActor( itemId-1, layoutSize );
942 // Total number of items may change dynamically.
943 // Always recalculate the domain size to reflect that.
944 CalculateDomainSize(Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ));
947 void ItemView::AddNewActor( unsigned int itemId, const Vector3& layoutSize )
951 if( mItemPool.end() == FindItemById( mItemPool, itemId ) )
953 Actor actor = mItemFactory.NewItem( itemId );
957 Item newItem( itemId, actor );
959 InsertToItemContainer( mItemPool, newItem );
961 SetupActor( newItem, layoutSize );
966 mAddingItems = false;
969 void ItemView::SetupActor( Item item, const Vector3& layoutSize )
971 item.second.SetProperty( Actor::Property::PARENT_ORIGIN, mItemsParentOrigin );
972 item.second.SetProperty( Actor::Property::ANCHOR_POINT, mItemsAnchorPoint );
977 mActiveLayout->GetItemSize( item.first, mActiveLayoutTargetSize, size );
978 item.second.SetProperty( Actor::Property::SIZE, size.GetVectorXY() );
980 mActiveLayout->ApplyConstraints( item.second, item.first, layoutSize, Self() );
984 void ItemView::ReleaseActor( ItemId item, Actor actor )
986 Self().Remove( actor );
987 mItemFactory.ItemReleased(item, actor);
990 ItemRange ItemView::GetItemRange(ItemLayout& layout, const Vector3& layoutSize, float layoutPosition, bool reserveExtra)
992 unsigned int itemCount = mItemFactory.GetNumberOfItems();
994 ItemRange available(0u, itemCount);
996 ItemRange range = layout.GetItemsWithinArea( layoutPosition, layoutSize );
1000 // Add the reserve items for scrolling
1001 unsigned int extra = layout.GetReserveItemCount(layoutSize);
1002 range.begin = (range.begin >= extra) ? (range.begin - extra) : 0u;
1006 return range.Intersection(available);
1009 void ItemView::OnChildAdd(Actor& child)
1013 // We don't want to do this downcast check for any item added by ItemView itself.
1014 Dali::Toolkit::ScrollBar scrollBar = Dali::Toolkit::ScrollBar::DownCast(child);
1017 scrollBar.SetScrollPropertySource(Self(),
1018 Toolkit::ItemView::Property::LAYOUT_POSITION,
1019 Toolkit::Scrollable::Property::SCROLL_POSITION_MIN_Y,
1020 Toolkit::Scrollable::Property::SCROLL_POSITION_MAX_Y,
1021 Toolkit::ItemView::Property::SCROLL_CONTENT_SIZE);
1025 Scrollable::OnChildAdd( child );
1028 bool ItemView::OnWheelEvent(Actor actor, const WheelEvent& event)
1030 // Respond the wheel event to scroll
1033 Actor self = Self();
1034 const Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
1035 float layoutPositionDelta = GetCurrentLayoutPosition(0) - (event.GetDelta() * mWheelScrollDistanceStep * mActiveLayout->GetScrollSpeedFactor());
1036 float firstItemScrollPosition = ClampFirstItemPosition(layoutPositionDelta, layoutSize, *mActiveLayout);
1038 self.SetProperty(Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1040 mScrollStartedSignal.Emit(GetCurrentScrollPosition());
1041 mRefreshEnabled = true;
1044 if (mWheelEventFinishedTimer.IsRunning())
1046 mWheelEventFinishedTimer.Stop();
1049 mWheelEventFinishedTimer.Start();
1054 bool ItemView::OnWheelEventFinished()
1058 RemoveAnimation(mScrollAnimation);
1060 // No more wheel events coming. Do the anchoring if enabled.
1061 mScrollAnimation = DoAnchoring();
1062 if (mScrollAnimation)
1064 mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
1065 mScrollAnimation.Play();
1069 mScrollOvershoot = 0.0f;
1070 AnimateScrollOvershoot(0.0f);
1072 mScrollCompletedSignal.Emit(GetCurrentScrollPosition());
1079 void ItemView::ReapplyAllConstraints()
1081 Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
1083 for (ConstItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
1085 unsigned int id = iter->first;
1086 Actor actor = iter->second;
1088 actor.RemoveConstraints();
1089 mActiveLayout->ApplyConstraints(actor, id, layoutSize, Self());
1093 void ItemView::OnItemsRemoved()
1095 CalculateDomainSize(Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ));
1097 // Adjust scroll-position after an item is removed
1100 float firstItemScrollPosition = ClampFirstItemPosition(GetCurrentLayoutPosition(0), Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ), *mActiveLayout);
1101 Self().SetProperty( Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1105 float ItemView::ClampFirstItemPosition( float targetPosition, const Vector3& targetSize, ItemLayout& layout, bool updateOvershoot )
1107 Actor self = Self();
1108 float minLayoutPosition = layout.GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), targetSize);
1109 float clamppedPosition = std::min(0.0f, std::max(minLayoutPosition, targetPosition));
1110 self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX, Vector2(0.0f, -minLayoutPosition));
1112 if( updateOvershoot )
1114 mScrollOvershoot = targetPosition - clamppedPosition;
1117 return clamppedPosition;
1120 bool ItemView::OnTouch( Actor actor, const TouchEvent& touch )
1122 // Ignore events with multiple-touch points
1123 if (touch.GetPointCount() != 1)
1128 if ( touch.GetState( 0 ) == PointState::DOWN )
1130 // Cancel ongoing scrolling etc.
1131 mGestureState = GestureState::CLEAR;
1133 mScrollDistance = 0.0f;
1134 mScrollSpeed = 0.0f;
1135 Self().SetProperty(Toolkit::ItemView::Property::SCROLL_SPEED, mScrollSpeed);
1137 mScrollOvershoot = 0.0f;
1138 AnimateScrollOvershoot(0.0f);
1140 if(mScrollAnimation)
1142 mScrollCompletedSignal.Emit(GetCurrentScrollPosition());
1145 RemoveAnimation(mScrollAnimation);
1148 return false; // Do not consume as we're potentially scrolling (detecting pan gestures)
1151 void ItemView::OnPan( const PanGesture& gesture )
1153 Actor self = Self();
1154 const Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
1156 RemoveAnimation(mScrollAnimation);
1158 // Short-circuit if there is no active layout
1161 mGestureState = GestureState::CLEAR;
1165 mGestureState = gesture.GetState();
1167 switch (mGestureState)
1169 case GestureState::FINISHED:
1172 if (fabsf(mScrollDistance) > mMinimumSwipeDistance &&
1173 mScrollSpeed > mMinimumSwipeSpeed)
1175 float direction = (mScrollDistance < 0.0f) ? -1.0f : 1.0f;
1177 mRefreshOrderHint = true;
1179 float currentLayoutPosition = GetCurrentLayoutPosition(0);
1180 float firstItemScrollPosition = ClampFirstItemPosition(currentLayoutPosition + mScrollSpeed * direction,
1184 if (mAnchoringEnabled)
1186 firstItemScrollPosition = mActiveLayout->GetClosestAnchorPosition(firstItemScrollPosition);
1189 RemoveAnimation(mScrollAnimation);
1191 float flickAnimationDuration = Clamp( mActiveLayout->GetItemFlickAnimationDuration() * std::max(1.0f, fabsf(firstItemScrollPosition - GetCurrentLayoutPosition(0)))
1192 , DEFAULT_MINIMUM_SWIPE_DURATION, DEFAULT_MAXIMUM_SWIPE_DURATION);
1194 mScrollAnimation = Animation::New(flickAnimationDuration);
1195 mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION ), firstItemScrollPosition, AlphaFunction::EASE_OUT );
1196 mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::SCROLL_SPEED), 0.0f, AlphaFunction::EASE_OUT );
1200 // Check whether it has already scrolled to the end
1201 if( fabs(currentLayoutPosition - firstItemScrollPosition) < Math::MACHINE_EPSILON_0 )
1203 AnimateScrollOvershoot( 0.0f );
1204 RemoveAnimation( mScrollAnimation );
1208 // Anchoring may be triggered when there was no swipe
1209 if (!mScrollAnimation)
1211 mScrollAnimation = DoAnchoring();
1214 // Reset the overshoot if no scroll animation.
1215 if (!mScrollAnimation)
1217 mScrollCompletedSignal.Emit(GetCurrentScrollPosition());
1219 AnimateScrollOvershoot(0.0f, false);
1224 case GestureState::STARTED: // Fall through
1226 mTotalPanDisplacement = Vector2::ZERO;
1227 mScrollStartedSignal.Emit(GetCurrentScrollPosition());
1228 mRefreshEnabled = true;
1231 case GestureState::CONTINUING:
1233 const Vector2& displacement = gesture.GetDisplacement();
1234 mScrollDistance = CalculateScrollDistance(displacement, *mActiveLayout);
1235 mScrollSpeed = Clamp((gesture.GetSpeed() * gesture.GetSpeed() * mActiveLayout->GetFlickSpeedFactor() * MILLISECONDS_PER_SECONDS), 0.0f, mActiveLayout->GetMaximumSwipeSpeed());
1237 // Refresh order depends on the direction of the scroll; negative is towards the last item.
1238 mRefreshOrderHint = mScrollDistance < 0.0f;
1240 float layoutPositionDelta = GetCurrentLayoutPosition(0) + (mScrollDistance * mActiveLayout->GetScrollSpeedFactor());
1242 float firstItemScrollPosition = ClampFirstItemPosition(layoutPositionDelta, layoutSize, *mActiveLayout);
1244 float currentOvershoot = self.GetCurrentProperty< float >( Toolkit::ItemView::Property::OVERSHOOT );
1246 self.SetProperty(Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1248 if( ( firstItemScrollPosition >= 0.0f &&
1249 currentOvershoot < 1.0f ) ||
1250 ( firstItemScrollPosition <= mActiveLayout->GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), layoutSize) &&
1251 currentOvershoot > -1.0f ) )
1253 mTotalPanDisplacement += displacement;
1256 mScrollOvershoot = CalculateScrollOvershoot();
1258 // If the view is moved in a direction against the overshoot indicator, then the indicator should be animated off.
1259 // First make sure we are not in an animation, otherwise a previously started
1260 // off-animation will be overwritten as the user continues scrolling.
1263 // Check if the movement is against the current overshoot amount (if we are currently displaying the indicator).
1264 if( ( ( mScrollOvershoot > Math::MACHINE_EPSILON_0 ) && ( mScrollDistance < -Math::MACHINE_EPSILON_0 ) ) ||
1265 ( ( mScrollOvershoot < Math::MACHINE_EPSILON_0 ) && ( mScrollDistance > Math::MACHINE_EPSILON_0 ) ) )
1267 // The user has moved against the indicator direction.
1268 // First, we reset the total displacement. This means the overshoot amount will become zero the next frame,
1269 // and if the user starts dragging in the overshoot direction again, the indicator will appear once more.
1270 mTotalPanDisplacement = Vector2::ZERO;
1271 // Animate the overshoot indicator off.
1272 AnimateScrollOvershoot( 0.0f, false );
1276 // Only set the property directly if we are not animating the overshoot away,
1277 // as otherwise this will overwrite the animation generated value.
1278 self.SetProperty( Toolkit::ItemView::Property::OVERSHOOT, mScrollOvershoot );
1284 case GestureState::CANCELLED:
1286 mScrollAnimation = DoAnchoring();
1294 if (mScrollAnimation)
1296 mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
1297 mScrollAnimation.Play();
1301 bool ItemView::OnAccessibilityPan(PanGesture gesture)
1307 Actor ItemView::GetNextKeyboardFocusableActor(Actor actor, Toolkit::Control::KeyboardFocus::Direction direction, bool loopEnabled)
1309 Actor nextFocusActor;
1313 if(!actor || actor == this->Self())
1315 nextFocusActor = GetItem(nextItemID);
1317 else if(actor && actor.GetParent() == this->Self())
1319 int itemID = GetItemId(actor);
1320 nextItemID = mActiveLayout->GetNextFocusItemID(itemID, mItemFactory.GetNumberOfItems(), direction, loopEnabled);
1321 nextFocusActor = GetItem(nextItemID);
1322 if(nextFocusActor == actor)
1324 // need to pass NULL actor back to focus manager
1325 nextFocusActor.Reset();
1326 return nextFocusActor;
1329 float layoutPosition = mActiveLayout->GetClosestAnchorPosition( GetCurrentLayoutPosition(0) );
1330 Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
1333 // likely the current item is not buffered, so not in our item pool, probably best to get first viewable item
1334 ItemRange viewableItems = mActiveLayout->GetItemsWithinArea(layoutPosition, layoutSize);
1335 nextItemID = viewableItems.begin;
1336 nextFocusActor = GetItem(nextItemID);
1339 return nextFocusActor;
1342 void ItemView::OnKeyboardFocusChangeCommitted(Actor commitedFocusableActor)
1344 // only in this function if our chosen focus actor was actually used
1345 if(commitedFocusableActor)
1347 int nextItemID = GetItemId(commitedFocusableActor);
1348 float layoutPosition = GetCurrentLayoutPosition(0);
1349 Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
1351 float scrollTo = mActiveLayout->GetClosestOnScreenLayoutPosition(nextItemID, layoutPosition, layoutSize);
1352 ScrollTo(Vector2(0.0f, scrollTo), DEFAULT_KEYBOARD_FOCUS_SCROLL_DURATION);
1356 Animation ItemView::DoAnchoring()
1358 Animation anchoringAnimation;
1359 Actor self = Self();
1361 if (mActiveLayout && mAnchoringEnabled)
1363 float anchorPosition = mActiveLayout->GetClosestAnchorPosition( GetCurrentLayoutPosition(0) );
1365 anchoringAnimation = Animation::New(mAnchoringDuration);
1366 anchoringAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), anchorPosition, AlphaFunction::EASE_OUT );
1367 anchoringAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::SCROLL_SPEED), 0.0f, AlphaFunction::EASE_OUT );
1370 AnimateScrollOvershoot(0.0f);
1374 return anchoringAnimation;
1377 void ItemView::OnScrollFinished(Animation& source)
1379 Actor self = Self();
1381 RemoveAnimation(mScrollAnimation); // mScrollAnimation is used to query whether we're scrolling
1383 mScrollCompletedSignal.Emit(GetCurrentScrollPosition());
1385 if(mIsFlicking && fabsf(mScrollOvershoot) > Math::MACHINE_EPSILON_1)
1387 AnimateScrollOvershoot( mScrollOvershoot > 0.0f ? 1.0f : -1.0f, true);
1391 // Reset the overshoot
1392 AnimateScrollOvershoot( 0.0f );
1394 mIsFlicking = false;
1396 mScrollOvershoot = 0.0f;
1399 void ItemView::OnLayoutActivationScrollFinished(Animation& source)
1401 RemoveAnimation(mScrollAnimation);
1402 mRefreshEnabled = true;
1403 DoRefresh(GetCurrentLayoutPosition(0), true);
1405 // Emit the layout activated signal
1406 mLayoutActivatedSignal.Emit();
1409 void ItemView::OnOvershootOnFinished(Animation& animation)
1411 mAnimatingOvershootOn = false;
1412 mScrollOvershootAnimation.FinishedSignal().Disconnect(this, &ItemView::OnOvershootOnFinished);
1413 RemoveAnimation(mScrollOvershootAnimation);
1414 if(mAnimateOvershootOff)
1416 AnimateScrollOvershoot(0.0f);
1418 mInAnimation = false;
1421 void ItemView::ScrollToItem(unsigned int itemId, float durationSeconds)
1423 Actor self = Self();
1424 const Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
1425 float firstItemScrollPosition = ClampFirstItemPosition(mActiveLayout->GetItemScrollToPosition(itemId), layoutSize, *mActiveLayout);
1427 if(durationSeconds > 0.0f)
1429 RemoveAnimation(mScrollAnimation);
1430 mScrollAnimation = Animation::New(durationSeconds);
1431 mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), firstItemScrollPosition, mScrollToAlphaFunction );
1432 mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
1433 mScrollAnimation.Play();
1437 self.SetProperty( Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1438 AnimateScrollOvershoot(0.0f);
1441 mScrollStartedSignal.Emit(GetCurrentScrollPosition());
1442 mRefreshEnabled = true;
1445 void ItemView::RemoveAnimation(Animation& animation)
1449 // Cease animating, and reset handle.
1455 void ItemView::CalculateDomainSize(const Vector3& layoutSize)
1457 Actor self = Self();
1459 Vector3 firstItemPosition(Vector3::ZERO);
1460 Vector3 lastItemPosition(Vector3::ZERO);
1464 firstItemPosition = mActiveLayout->GetItemPosition( 0,0,layoutSize );
1466 float minLayoutPosition = mActiveLayout->GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), layoutSize);
1467 lastItemPosition = mActiveLayout->GetItemPosition( fabs(minLayoutPosition),fabs(minLayoutPosition),layoutSize );
1471 if(IsHorizontal(mActiveLayout->GetOrientation()))
1473 domainSize = fabs(firstItemPosition.x - lastItemPosition.x);
1477 domainSize = fabs(firstItemPosition.y - lastItemPosition.y);
1480 self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MIN, Vector2::ZERO);
1481 self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX, Vector2(0.0f, -minLayoutPosition));
1483 self.SetProperty(Toolkit::ItemView::Property::SCROLL_CONTENT_SIZE, domainSize);
1485 bool isLayoutScrollable = IsLayoutScrollable(layoutSize);
1486 self.SetProperty(Toolkit::Scrollable::Property::CAN_SCROLL_VERTICAL, isLayoutScrollable);
1487 self.SetProperty(Toolkit::Scrollable::Property::CAN_SCROLL_HORIZONTAL, false);
1491 bool ItemView::IsLayoutScrollable(const Vector3& layoutSize)
1493 Actor self = Self();
1495 float currentLayoutPosition = ClampFirstItemPosition( GetCurrentLayoutPosition(0), layoutSize, *mActiveLayout, false );
1496 float forwardClampedPosition = ClampFirstItemPosition( currentLayoutPosition + 1.0, layoutSize, *mActiveLayout, false );
1497 float backwardClampedPosition = ClampFirstItemPosition( currentLayoutPosition - 1.0, layoutSize, *mActiveLayout, false );
1499 return (fabs(forwardClampedPosition - backwardClampedPosition) > Math::MACHINE_EPSILON_0);
1502 float ItemView::GetScrollPosition(float layoutPosition, const Vector3& layoutSize) const
1504 Vector3 firstItemPosition( mActiveLayout->GetItemPosition(0, layoutPosition, layoutSize ) );
1505 return IsHorizontal(mActiveLayout->GetOrientation()) ? firstItemPosition.x: firstItemPosition.y;
1508 Vector2 ItemView::GetCurrentScrollPosition() const
1510 return Vector2(0.0f, GetScrollPosition(GetCurrentLayoutPosition(0), Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE )));
1513 void ItemView::AddOverlay(Actor actor)
1515 actor.SetProperty( Actor::Property::DRAW_MODE, DrawMode::OVERLAY_2D );
1519 void ItemView::RemoveOverlay(Actor actor)
1521 Self().Remove(actor);
1524 void ItemView::ScrollTo(const Vector2& position, float duration)
1526 Actor self = Self();
1527 const Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE );
1529 float firstItemScrollPosition = ClampFirstItemPosition(position.y, layoutSize, *mActiveLayout);
1533 RemoveAnimation(mScrollAnimation);
1534 mScrollAnimation = Animation::New(duration);
1535 mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), firstItemScrollPosition, mScrollToAlphaFunction );
1536 mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
1537 mScrollAnimation.Play();
1541 self.SetProperty( Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1542 AnimateScrollOvershoot(0.0f);
1545 mScrollStartedSignal.Emit(GetCurrentScrollPosition());
1546 mRefreshEnabled = true;
1549 void ItemView::SetOvershootSize( const Vector2& size )
1551 mOvershootSize = size;
1553 if( mOvershootOverlay )
1555 // Remove old & add new size constraint
1556 mOvershootOverlay.RemoveConstraints( OVERSHOOT_SIZE_CONSTRAINT_TAG );
1557 ApplyOvershootSizeConstraint( mOvershootOverlay, mOvershootSize.height );
1561 void ItemView::SetOvershootEffectColor( const Vector4& color )
1563 mOvershootEffectColor = color;
1564 if( mOvershootOverlay )
1566 mOvershootOverlay.SetProperty( Actor::Property::COLOR, color );
1570 void ItemView::EnableScrollOvershoot( bool enable )
1572 Actor self = Self();
1575 if( !mOvershootOverlay )
1577 Property::Index effectOvershootPropertyIndex = Property::INVALID_INDEX;
1578 mOvershootOverlay = CreateBouncingEffectActor( effectOvershootPropertyIndex );
1579 mOvershootOverlay.SetProperty( Actor::Property::COLOR,mOvershootEffectColor);
1580 mOvershootOverlay.SetProperty( Actor::Property::PARENT_ORIGIN,ParentOrigin::TOP_LEFT );
1581 mOvershootOverlay.SetProperty( Actor::Property::ANCHOR_POINT,AnchorPoint::TOP_LEFT);
1582 mOvershootOverlay.SetProperty( Actor::Property::DRAW_MODE, DrawMode::OVERLAY_2D );
1583 self.Add(mOvershootOverlay);
1585 ApplyOvershootSizeConstraint( mOvershootOverlay, mOvershootSize.height );
1587 Constraint constraint = Constraint::New<Quaternion>( mOvershootOverlay, Actor::Property::ORIENTATION, OvershootOverlayRotationConstraint );
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<Vector3>( mOvershootOverlay, Actor::Property::POSITION, OvershootOverlayPositionConstraint );
1594 constraint.AddSource( ParentSource( Actor::Property::SIZE ) );
1595 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::SCROLL_DIRECTION ) );
1596 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_ORIENTATION ) );
1597 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::OVERSHOOT ) );
1600 constraint = Constraint::New<bool>( mOvershootOverlay, Actor::Property::VISIBLE, OvershootOverlayVisibilityConstraint );
1601 constraint.AddSource( ParentSource( Toolkit::Scrollable::Property::CAN_SCROLL_VERTICAL ) );
1604 constraint = Constraint::New<float>( mOvershootOverlay, effectOvershootPropertyIndex, EqualToConstraint() );
1605 constraint.AddSource( ParentSource( Toolkit::ItemView::Property::OVERSHOOT ) );
1611 if( mOvershootOverlay )
1613 self.Remove(mOvershootOverlay);
1614 mOvershootOverlay.Reset();
1619 float ItemView::CalculateScrollOvershoot()
1621 float overshoot = 0.0f;
1625 // The overshoot must be calculated from the accumulated pan gesture displacement
1626 // since the pan gesture starts.
1627 Actor self = Self();
1628 float scrollDistance = CalculateScrollDistance(mTotalPanDisplacement, *mActiveLayout) * mActiveLayout->GetScrollSpeedFactor();
1629 float positionDelta = GetCurrentLayoutPosition(0) + scrollDistance;
1630 float minLayoutPosition = mActiveLayout->GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ));
1631 self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX, Vector2(0.0f, -minLayoutPosition));
1632 float clamppedPosition = std::min(0.0f, std::max(minLayoutPosition, positionDelta));
1633 overshoot = positionDelta - clamppedPosition;
1636 return overshoot > 0.0f ? std::min(overshoot, 1.0f) : std::max(overshoot, -1.0f);
1639 void ItemView::AnimateScrollOvershoot(float overshootAmount, bool animateBack)
1641 bool animatingOn = fabsf(overshootAmount) > Math::MACHINE_EPSILON_1;
1643 // make sure we animate back if needed
1644 mAnimateOvershootOff = animateBack || (!animatingOn && mAnimatingOvershootOn);
1646 if( mAnimatingOvershootOn )
1648 // animating on, do not allow animate off
1652 Actor self = Self();
1654 if(mOvershootAnimationSpeed > Math::MACHINE_EPSILON_0)
1656 float currentOvershoot = self.GetCurrentProperty< float >( Toolkit::ItemView::Property::OVERSHOOT );
1657 float duration = 0.0f;
1659 if (mOvershootOverlay)
1661 duration = mOvershootOverlay.GetCurrentProperty< Vector3 >( Actor::Property::SIZE ).height * (animatingOn ? (1.0f - fabsf(currentOvershoot)) : fabsf(currentOvershoot)) / mOvershootAnimationSpeed;
1664 // Mark the animation as in progress to prevent manual property sets overwriting it.
1665 mInAnimation = true;
1666 mAnimatingOvershootOn = animatingOn;
1667 RemoveAnimation(mScrollOvershootAnimation);
1668 mScrollOvershootAnimation = Animation::New(duration);
1669 mScrollOvershootAnimation.FinishedSignal().Connect(this, &ItemView::OnOvershootOnFinished);
1670 mScrollOvershootAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::OVERSHOOT), overshootAmount, TimePeriod(0.0f, duration) );
1671 mScrollOvershootAnimation.Play();
1675 self.SetProperty( Toolkit::ItemView::Property::OVERSHOOT, overshootAmount );
1679 void ItemView::SetItemsParentOrigin( const Vector3& parentOrigin )
1681 if( parentOrigin != mItemsParentOrigin )
1683 mItemsParentOrigin = parentOrigin;
1684 for (ItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
1686 iter->second.SetProperty( Actor::Property::PARENT_ORIGIN,parentOrigin );
1691 Vector3 ItemView::GetItemsParentOrigin() const
1693 return mItemsParentOrigin;
1696 void ItemView::SetItemsAnchorPoint( const Vector3& anchorPoint )
1698 if( anchorPoint != mItemsAnchorPoint )
1700 mItemsAnchorPoint = anchorPoint;
1701 for (ItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
1703 iter->second.SetProperty( Actor::Property::ANCHOR_POINT,anchorPoint);
1708 Vector3 ItemView::GetItemsAnchorPoint() const
1710 return mItemsAnchorPoint;
1713 void ItemView::GetItemsRange(ItemRange& range)
1715 if( !mItemPool.empty() )
1717 range.begin = mItemPool.begin()->first;
1718 range.end = mItemPool.rbegin()->first + 1;
1727 bool ItemView::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
1729 Dali::BaseHandle handle( object );
1731 bool connected( true );
1732 Toolkit::ItemView itemView = Toolkit::ItemView::DownCast( handle );
1734 if( 0 == strcmp( signalName.c_str(), LAYOUT_ACTIVATED_SIGNAL ) )
1736 itemView.LayoutActivatedSignal().Connect( tracker, functor );
1740 // signalName does not match any signal
1747 void ItemView::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
1749 Toolkit::ItemView itemView = Toolkit::ItemView::DownCast( Dali::BaseHandle( object ) );
1753 ItemView& itemViewImpl( GetImpl( itemView ) );
1756 case Toolkit::ItemView::Property::MINIMUM_SWIPE_SPEED:
1758 itemViewImpl.SetMinimumSwipeSpeed( value.Get<float>() );
1762 case Toolkit::ItemView::Property::MINIMUM_SWIPE_DISTANCE:
1764 itemViewImpl.SetMinimumSwipeDistance( value.Get<float>() );
1768 case Toolkit::ItemView::Property::WHEEL_SCROLL_DISTANCE_STEP:
1770 itemViewImpl.SetWheelScrollDistanceStep( value.Get<float>() );
1774 case Toolkit::ItemView::Property::SNAP_TO_ITEM_ENABLED:
1776 itemViewImpl.SetAnchoring( value.Get<bool>() );
1780 case Toolkit::ItemView::Property::REFRESH_INTERVAL:
1782 itemViewImpl.SetRefreshInterval( value.Get<float>() );
1786 case Toolkit::ItemView::Property::LAYOUT:
1788 // Get a Property::Array from the property if possible.
1789 Property::Array layoutArray;
1790 if( value.Get( layoutArray ) )
1792 itemViewImpl.SetLayoutArray( layoutArray );
1800 Property::Array ItemView::GetLayoutArray()
1802 return mlayoutArray;
1805 void ItemView::SetLayoutArray( const Property::Array& layouts )
1807 mlayoutArray = layouts;
1808 const int layoutCount = GetLayoutCount();
1809 if( layoutCount > 0 )
1811 for(int index = layoutCount - 1; index >= 0; --index)
1813 RemoveLayout(index);
1814 if(index == 0) break;
1818 for( unsigned int arrayIdx = 0, arrayCount = layouts.Count(); arrayIdx < arrayCount; ++arrayIdx )
1820 const Property::Value& element = layouts.GetElementAt( arrayIdx );
1822 Property::Map* layout = element.GetMap();
1823 if( layout != NULL )
1825 for( unsigned int mapIdx = 0, mapCount = (*layout).Count(); mapIdx < mapCount; ++mapIdx )
1827 KeyValuePair propertyPair( (*layout).GetKeyValue( mapIdx ) );
1829 if(propertyPair.first == DefaultItemLayoutProperty::TYPE)
1831 int layoutType = propertyPair.second.Get<int>();
1832 if(layoutType <= DefaultItemLayout::SPIRAL && layoutType >= DefaultItemLayout::DEPTH)
1834 //DEPTH, GRID, LIST, SPIRAL
1835 switch(DefaultItemLayout::Type(layoutType))
1837 case DefaultItemLayout::DEPTH:
1839 Internal::DepthLayoutPtr depthLayout = Internal::DepthLayout::New();
1840 (*depthLayout).SetLayoutProperties(*layout);
1841 (*depthLayout).SetDepthLayoutProperties(*layout);
1842 AddLayout(*depthLayout);
1845 case DefaultItemLayout::GRID:
1847 Internal::GridLayoutPtr gridLayout = Internal::GridLayout::New();
1848 (*gridLayout).SetLayoutProperties(*layout);
1849 (*gridLayout).SetGridLayoutProperties(*layout);
1850 AddLayout(*gridLayout);
1853 case DefaultItemLayout::LIST:
1855 Internal::GridLayoutPtr listLayout = Internal::GridLayout::New();
1856 listLayout->SetNumberOfColumns( 1 );
1857 (*listLayout).SetLayoutProperties(*layout);
1858 (*listLayout).SetGridLayoutProperties(*layout);
1859 AddLayout(*listLayout);
1862 case DefaultItemLayout::SPIRAL:
1864 Internal::SpiralLayoutPtr spiralLayout = Internal::SpiralLayout::New();
1865 (*spiralLayout).SetLayoutProperties(*layout);
1866 (*spiralLayout).SetSpiralLayoutProperties(*layout);
1867 AddLayout(*spiralLayout);
1878 Property::Value ItemView::GetProperty( BaseObject* object, Property::Index index )
1880 Property::Value value;
1882 Toolkit::ItemView itemView = Toolkit::ItemView::DownCast( Dali::BaseHandle( object ) );
1886 ItemView& itemViewImpl( GetImpl( itemView ) );
1889 case Toolkit::ItemView::Property::MINIMUM_SWIPE_SPEED:
1891 value = itemViewImpl.GetMinimumSwipeSpeed();
1895 case Toolkit::ItemView::Property::MINIMUM_SWIPE_DISTANCE:
1897 value = itemViewImpl.GetMinimumSwipeDistance();
1901 case Toolkit::ItemView::Property::WHEEL_SCROLL_DISTANCE_STEP:
1903 value = itemViewImpl.GetWheelScrollDistanceStep();
1907 case Toolkit::ItemView::Property::SNAP_TO_ITEM_ENABLED:
1909 value = itemViewImpl.GetAnchoring();
1913 case Toolkit::ItemView::Property::REFRESH_INTERVAL:
1915 value = itemViewImpl.GetRefreshInterval();
1919 case Toolkit::ItemView::Property::LAYOUT:
1921 Property::Array layouts= itemViewImpl.GetLayoutArray();
1931 bool ItemView::DoAction( BaseObject* object, const std::string& actionName, const Property::Map& attributes )
1933 Dali::BaseHandle handle( object );
1935 Toolkit::ItemView itemView = Toolkit::ItemView::DownCast( handle );
1937 DALI_ASSERT_ALWAYS( itemView );
1939 if( 0 == strcmp( actionName.c_str(), ACTION_STOP_SCROLLING ) )
1941 GetImpl( itemView ).DoStopScrolling();
1943 else if ( 0 == strcmp( actionName.c_str(), ACTION_ENABLE_REFRESH ) )
1945 GetImpl( itemView ).SetRefreshNotificationEnabled( true );
1947 else if ( 0 == strcmp( actionName.c_str(), ACTION_DISABLE_REFRESH ) )
1949 GetImpl( itemView ).SetRefreshNotificationEnabled( false );
1955 void ItemView::DoStopScrolling()
1957 if( mScrollAnimation )
1959 mScrollAnimation.Stop();
1960 mScrollAnimation.Reset();
1964 void ItemView::SetRefreshNotificationEnabled( bool enabled )
1966 mRefreshNotificationEnabled = enabled;
1969 } // namespace Internal
1971 } // namespace Toolkit