Improve fast scrolling performance in ItemView
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / controls / scrollable / item-view / item-view-impl.cpp
index acb74dc..001291f 100644 (file)
@@ -38,7 +38,7 @@ const float DEFAULT_MINIMUM_SWIPE_SPEED = 1.0f;
 const float DEFAULT_MINIMUM_SWIPE_DISTANCE = 3.0f;
 const float DEFAULT_MOUSE_WHEEL_SCROLL_DISTANCE_STEP_PROPORTION = 0.1f;
 
-const int DEFAULT_REFRESH_INTERVAL_MILLISECONDS = 50; // 20 updates per second
+const float DEFAULT_REFRESH_INTERVAL_LAYOUT_POSITIONS = 20.0f; // 1 updates per 20 items
 const int MOUSE_WHEEL_EVENT_FINISHED_TIME_OUT = 500;  // 0.5 second
 
 const float DEFAULT_ANCHORING_DURATION = 1.0f;  // 1 second
@@ -358,107 +358,23 @@ namespace Toolkit
 namespace Internal
 {
 
-///////////////////////////////////////////////////////////////////////////////////////////////////
-// ItemPool
-///////////////////////////////////////////////////////////////////////////////////////////////////
-
-void ItemPool::AddItems(bool scrollingTowardsLast, ItemRange range, const Vector3& targetSize)
+namespace // unnamed namespace
 {
-  // Add new actors to the ItemPool.
-  // The order of addition depends on the scroll direction.
-  if (scrollingTowardsLast)
-  {
-    for (unsigned int itemId = range.begin; itemId < range.end; ++itemId)
-    {
-      AddItem(itemId, targetSize);
-    }
-  }
-  else
-  {
-    for (unsigned int itemId = range.end; itemId > range.begin; --itemId)
-    {
-      AddItem(itemId-1, targetSize);
-    }
-  }
-}
 
-void ItemPool::RemoveItems(ItemRange range)
+bool FindById( const ItemContainer& items, ItemId id )
 {
-  // Remove unwanted actors from the ItemView & ItemPool
-  for (IDKeyIter iter = mIdKeyContainer.begin(); iter != mIdKeyContainer.end(); )
+  for( ConstItemIter iter = items.begin(); items.end() != iter; ++iter )
   {
-    unsigned int current = iter->first;
-
-    if (!range.Within(current))
-    {
-      mItemView.ActorRemovedFromItemPool(iter->second, iter->first);
-
-      mActorKeyContainer.erase(iter->second);
-      mIdKeyContainer.erase(iter++); // erase invalidates the current iter; the post-increment is important here
-    }
-    else
+    if( iter->first == id )
     {
-      ++iter;
+      return true;
     }
   }
-}
 
-void ItemPool::AddItem(unsigned int itemId, const Vector3& targetSize)
-{
-  if (mIdKeyContainer.find(itemId) == mIdKeyContainer.end())
-  {
-    Actor actor = mItemView.CreateActor(itemId);
-
-    if (actor)
-    {
-      mIdKeyContainer.insert(IDKeyPair(itemId, actor));
-      mActorKeyContainer.insert(ActorKeyPair(actor, itemId));
-
-      mItemView.ActorAddedToItemPool(actor, itemId, targetSize);
-    }
-  }
-}
-
-bool ItemPool::RemoveItem(unsigned int itemId)
-{
-  bool found = false;
-
-  IDKeyIter iter = mIdKeyContainer.find(itemId);
-  if (iter != mIdKeyContainer.end())
-  {
-    mItemView.ActorRemovedFromItemPool(iter->second, iter->first);
-
-    mActorKeyContainer.erase(iter->second);
-    for (ActorKeyIter iterActorKey = mActorKeyContainer.begin(); iterActorKey != mActorKeyContainer.end(); ++iterActorKey)
-    {
-      if(iterActorKey->second > itemId)
-      {
-        iterActorKey->second--;
-      }
-    }
-
-    for (IDKeyIter iterIDKey = iter; iterIDKey != mIdKeyContainer.end(); ++iterIDKey)
-    {
-      if(iterIDKey->first < mIdKeyContainer.rbegin()->first)
-      {
-        iterIDKey->second = mIdKeyContainer[iterIDKey->first + 1];
-      }
-      else
-      {
-        mIdKeyContainer.erase(iterIDKey);
-        break;
-      }
-    }
-
-    found = true;
-  }
-
-  return found;
+  return false;
 }
 
-///////////////////////////////////////////////////////////////////////////////////////////////////
-// ItemView
-///////////////////////////////////////////////////////////////////////////////////////////////////
+} // unnamed namespace
 
 Dali::Toolkit::ItemView ItemView::New(ItemFactory& factory)
 {
@@ -478,13 +394,13 @@ Dali::Toolkit::ItemView ItemView::New(ItemFactory& factory)
 ItemView::ItemView(ItemFactory& factory)
 : Scrollable(),
   mItemFactory(factory),
-  mItemPool(*this),
   mActiveLayout(NULL),
+  mDefaultAlphaFunction(Dali::Constraint::DEFAULT_ALPHA_FUNCTION),
   mAnimatingOvershootOn(false),
   mAnimateOvershootOff(false),
   mAnchoringEnabled(true),
   mAnchoringDuration(DEFAULT_ANCHORING_DURATION),
-  mRefreshIntervalMilliseconds(DEFAULT_REFRESH_INTERVAL_MILLISECONDS),
+  mRefreshIntervalLayoutPositions(DEFAULT_REFRESH_INTERVAL_LAYOUT_POSITIONS),
   mRefreshOrderHint(true/*Refresh item 0 first*/),
   mMinimumSwipeSpeed(DEFAULT_MINIMUM_SWIPE_SPEED),
   mMinimumSwipeDistance(DEFAULT_MINIMUM_SWIPE_DISTANCE),
@@ -493,7 +409,9 @@ ItemView::ItemView(ItemFactory& factory)
   mTotalPanDisplacement(Vector2::ZERO),
   mScrollOvershoot(0.0f),
   mIsFlicking(false),
-  mGestureState(Gesture::Clear)
+  mGestureState(Gesture::Clear),
+  mAddingItems(false),
+  mRefreshEnabled(true)
 {
   SetRequiresMouseWheelEvents(true);
   SetKeyboardNavigationSupport(true);
@@ -523,7 +441,6 @@ void ItemView::OnInitialize()
   mPropertyMinimumLayoutPosition = self.RegisterProperty(MINIMUM_LAYOUT_POSITION_PROPERTY_NAME, 0.0f);
   mPropertyPosition = self.RegisterProperty(POSITION_PROPERTY_NAME, 0.0f);
   mPropertyScrollSpeed = self.RegisterProperty(SCROLL_SPEED_PROPERTY_NAME, 0.0f);
-  mPropertyOvershoot = self.RegisterProperty(OVERSHOOT_PROPERTY_NAME, 0.0f);
 
   ApplyOvershootOverlayConstraints();
 
@@ -542,6 +459,8 @@ void ItemView::OnInitialize()
 
   mMouseWheelEventFinishedTimer = Timer::New( MOUSE_WHEEL_EVENT_FINISHED_TIME_OUT );
   mMouseWheelEventFinishedTimer.TickSignal().Connect( this, &ItemView::OnMouseWheelEventFinished );
+
+  SetRefreshInterval(mRefreshIntervalLayoutPositions);
 }
 
 ItemView::~ItemView()
@@ -598,37 +517,27 @@ void ItemView::ActivateLayout(unsigned int layoutIndex, const Vector3& targetSiz
 
   // The ItemView size should match the active layout size
   self.SetSize(targetSize);
+  mActiveLayoutTargetSize = targetSize;
 
   // Switch to the new layout
-  ItemLayout* previousLayout = mActiveLayout;
   mActiveLayout = mLayouts[layoutIndex].Get();
 
-  // Calculate which items are within either layout
-  ItemRange oldRange = previousLayout ? GetItemRange(*previousLayout, targetSize, false/*don't reserve extra*/) : ItemRange(0u, 0u);
-  ItemRange newRange = GetItemRange(*mActiveLayout, targetSize, false/*don't reserve extra*/);
-
   // Move the items to the new layout positions...
 
   bool resizeAnimationNeeded(false);
 
-  const ItemPool::IDKeyContainer& itemPool = mItemPool.GetIDKeyContainer();
-  for (ItemPool::IDKeyConstIter iter = itemPool.begin(); iter != itemPool.end(); ++iter)
+  for (ConstItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
   {
     unsigned int itemId = iter->first;
     Actor actor = iter->second;
 
-    // Immediately relayout items that aren't within either layout
-    bool immediate = !oldRange.Within(itemId) &&
-                     !newRange.Within(itemId);
-
     // Remove constraints from previous layout
     actor.RemoveConstraints();
 
     Vector3 size;
     if(mActiveLayout->GetItemSize(itemId, targetSize, size))
     {
-      if (!immediate &&
-          durationSeconds > 0.0f)
+      if( durationSeconds > 0.0f )
       {
         // Use a size animation
         if (!resizeAnimationNeeded)
@@ -648,7 +557,7 @@ void ItemView::ActivateLayout(unsigned int layoutIndex, const Vector3& targetSiz
       }
     }
 
-    ApplyConstraints(actor, *mActiveLayout, itemId, immediate ? 0.0f : durationSeconds);
+    ApplyConstraints(actor, *mActiveLayout, itemId, durationSeconds);
   }
 
   if (resizeAnimationNeeded)
@@ -657,8 +566,8 @@ void ItemView::ActivateLayout(unsigned int layoutIndex, const Vector3& targetSiz
   }
 
   // Refresh the new layout
-  ItemRange range = GetItemRange(*mActiveLayout, targetSize, true/*reserve extra*/);
-  AddItems(*mActiveLayout, targetSize, range);
+  ItemRange range = GetItemRange(*mActiveLayout, targetSize, GetCurrentLayoutPosition(0), true/*reserve extra*/);
+  AddActorsWithinRange( range, durationSeconds );
 
   // Scroll to an appropriate layout position
 
@@ -706,8 +615,7 @@ void ItemView::DeactivateCurrentLayout()
 {
   if (mActiveLayout)
   {
-    const ItemPool::IDKeyContainer& itemPool = mItemPool.GetIDKeyContainer();
-    for (ItemPool::IDKeyConstIter iter = itemPool.begin(); iter != itemPool.end(); ++iter)
+    for (ConstItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
     {
       Actor actor = iter->second;
       actor.RemoveConstraints();
@@ -715,27 +623,37 @@ void ItemView::DeactivateCurrentLayout()
 
     mActiveLayout = NULL;
   }
+}
 
-  CancelRefreshTimer();
+void ItemView::SetDefaultAlphaFunction(AlphaFunction func)
+{
+  mDefaultAlphaFunction = func;
 }
 
-bool ItemView::OnRefreshTick()
+AlphaFunction ItemView::GetDefaultAlphaFunction() const
 {
-  // Short-circuit if there is no active layout
-  if (!mActiveLayout)
+  return mDefaultAlphaFunction;
+}
+
+void ItemView::OnRefreshNotification(PropertyNotification& source)
+{
+  if(mRefreshEnabled)
   {
-    return false;
+    // Only refresh the cache during normal scrolling
+    DoRefresh(GetCurrentLayoutPosition(0), true);
   }
+}
 
-  const Vector3 layoutSize = Self().GetCurrentSize();
-
-  ItemRange range = GetItemRange(*mActiveLayout, layoutSize, true/*reserve extra*/);
-
-  RemoveItems(range);
-  AddItems(*mActiveLayout, layoutSize, range);
+void ItemView::DoRefresh(float currentLayoutPosition, bool cacheExtra)
+{
+  if (mActiveLayout)
+  {
+    ItemRange range = GetItemRange(*mActiveLayout, mActiveLayoutTargetSize, currentLayoutPosition, cacheExtra/*reserve extra*/);
+    RemoveActorsOutsideRange( range );
+    AddActorsWithinRange( range, 0.0f/*immediate*/ );
 
-  // Keep refreshing whilst the layout is moving
-  return mScrollAnimation || (mGestureState == Gesture::Started || mGestureState == Gesture::Continuing);
+    mScrollUpdatedSignalV2.Emit( Vector3(0.0f, currentLayoutPosition, 0.0f) );
+  }
 }
 
 void ItemView::SetMinimumSwipeSpeed(float speed)
@@ -788,111 +706,351 @@ float ItemView::GetAnchoringDuration() const
   return mAnchoringDuration;
 }
 
-void ItemView::SetRefreshInterval(unsigned int intervalMilliseconds)
+void ItemView::SetRefreshInterval(float intervalLayoutPositions)
 {
-  mRefreshIntervalMilliseconds = intervalMilliseconds;
+  mRefreshIntervalLayoutPositions = intervalLayoutPositions;
+
+  if(mRefreshNotification)
+  {
+    mScrollPositionObject.RemovePropertyNotification(mRefreshNotification);
+  }
+  mRefreshNotification = mScrollPositionObject.AddPropertyNotification( ScrollConnector::SCROLL_POSITION, StepCondition(mRefreshIntervalLayoutPositions, 0.0f) );
+  mRefreshNotification.NotifySignal().Connect( this, &ItemView::OnRefreshNotification );
 }
 
-unsigned int ItemView::GetRefreshInterval() const
+float ItemView::GetRefreshInterval() const
 {
-  return mRefreshIntervalMilliseconds;
+  return mRefreshIntervalLayoutPositions;
+}
+
+void ItemView::SetRefreshEnabled(bool enabled)
+{
+  mRefreshEnabled = enabled;
 }
 
 Actor ItemView::GetItem(unsigned int itemId) const
 {
   Actor actor;
 
-  ItemPool::IDKeyConstIter found = mItemPool.GetIDKeyContainer().find(itemId);
-  if (found != mItemPool.GetIDKeyContainer().end())
+  ConstItemPoolIter iter = mItemPool.find( itemId );
+  if( iter != mItemPool.end() )
   {
-    actor = found->second;
+    actor = iter->second;
   }
 
   return actor;
 }
 
-unsigned int ItemView::GetItemId(Actor actor) const
+unsigned int ItemView::GetItemId( Actor actor ) const
 {
-  unsigned int itemId(0);
+  unsigned int itemId( 0 );
 
-  ItemPool::ActorKeyConstIter found = mItemPool.GetActorKeyContainer().find(actor);
-  if (found != mItemPool.GetActorKeyContainer().end())
+  for ( ConstItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter )
   {
-    itemId = found->second;
+    if( iter->second == actor )
+    {
+      itemId = iter->first;
+      break;
+    }
   }
 
   return itemId;
 }
 
-void ItemView::RemoveItem(unsigned int itemId, float durationSeconds)
+void ItemView::InsertItem( Item newItem, float durationSeconds )
 {
-  if (mItemPool.RemoveItem(itemId))
+  mAddingItems = true;
+
+  SetupActor( newItem, durationSeconds );
+  Self().Add( newItem.second );
+
+  ItemPoolIter foundIter = mItemPool.find( newItem.first );
+  if( mItemPool.end() != foundIter )
   {
-    const ItemPool::IDKeyContainer& itemPool = mItemPool.GetIDKeyContainer();
-    for (ItemPool::IDKeyConstIter iter = itemPool.begin(); iter != itemPool.end(); ++iter)
+    Actor moveMe = foundIter->second;
+    foundIter->second = newItem.second;
+
+    // Move the existing actors to make room
+    for( ItemPoolIter iter = ++foundIter; mItemPool.end() != iter; ++iter )
     {
-      unsigned int id = iter->first;
-      Actor actor = iter->second;
+      Actor temp = iter->second;
+      iter->second = moveMe;
+      moveMe = temp;
 
-      // Reposition the items if necessary
-      actor.RemoveConstraints();
-      ApplyConstraints(actor, *mActiveLayout, id, durationSeconds);
+      iter->second.RemoveConstraints();
+      ApplyConstraints( iter->second, *mActiveLayout, iter->first, durationSeconds );
     }
 
-    CalculateDomainSize(Self().GetCurrentSize());
+    // Create last item
+    ItemId lastId = mItemPool.rbegin()->first;
+    Item lastItem( lastId + 1, moveMe );
+    mItemPool.insert( lastItem );
+
+    lastItem.second.RemoveConstraints();
+    ApplyConstraints( lastItem.second, *mActiveLayout, lastItem.first, durationSeconds );
   }
+  else
+  {
+    mItemPool.insert( newItem );
+  }
+
+  CalculateDomainSize(Self().GetCurrentSize());
+
+  mAddingItems = false;
 }
 
-Actor ItemView::CreateActor(unsigned int itemId)
+void ItemView::InsertItems( const ItemContainer& newItems, float durationSeconds )
 {
-  return mItemFactory.NewItem(itemId);
+  mAddingItems = true;
+
+  // Insert from lowest id to highest
+  set<Item> sortedItems;
+  for( ConstItemIter iter = newItems.begin(); newItems.end() != iter; ++iter )
+  {
+    sortedItems.insert( *iter );
+  }
+
+  for( set<Item>::iterator iter = sortedItems.begin(); sortedItems.end() != iter; ++iter )
+  {
+    Self().Add( iter->second );
+
+    cout << "inserting item: " << iter->first << endl;
+
+    ItemPoolIter foundIter = mItemPool.find( iter->first );
+    if( mItemPool.end() != foundIter )
+    {
+      Actor moveMe = foundIter->second;
+      foundIter->second = iter->second;
+
+      // Move the existing actors to make room
+      for( ItemPoolIter iter = ++foundIter; mItemPool.end() != iter; ++iter )
+      {
+        Actor temp = iter->second;
+        iter->second = moveMe;
+        moveMe = temp;
+      }
+
+      // Create last item
+      ItemId lastId = mItemPool.rbegin()->first;
+      Item lastItem( lastId + 1, moveMe );
+      mItemPool.insert( lastItem );
+    }
+    else
+    {
+      mItemPool.insert( *iter );
+    }
+  }
+
+  // Relayout everything
+  for (ItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
+  {
+    // If newly inserted
+    if( FindById( newItems, iter->first ) )
+    {
+      SetupActor( *iter, durationSeconds );
+    }
+    else
+    {
+      iter->second.RemoveConstraints();
+      ApplyConstraints( iter->second, *mActiveLayout, iter->first, durationSeconds );
+    }
+  }
+
+  CalculateDomainSize(Self().GetCurrentSize());
+
+  mAddingItems = false;
 }
 
-void ItemView::ActorAddedToItemPool(Actor actor, unsigned int itemId, const Vector3& targetSize)
+void ItemView::RemoveItem( unsigned int itemId, float durationSeconds )
 {
-  Actor self = Self();
+  bool actorRemoved = RemoveActor( itemId );
+  if( actorRemoved )
+  {
+    ReapplyAllConstraints( durationSeconds );
+  }
+}
 
-  actor.SetParentOrigin(ParentOrigin::CENTER);
-  actor.SetAnchorPoint(AnchorPoint::CENTER);
+void ItemView::RemoveItems( const ItemIdContainer& itemIds, float durationSeconds )
+{
+  bool actorRemoved( false );
 
-  if (mActiveLayout)
+  // Remove from highest id to lowest
+  set<ItemId> sortedItems;
+  for( ConstItemIdIter iter = itemIds.begin(); itemIds.end() != iter; ++iter )
   {
-    Vector3 size;
-    if(mActiveLayout->GetItemSize(itemId, targetSize, size))
+    sortedItems.insert( *iter );
+  }
+
+  for( set<ItemId>::reverse_iterator iter = sortedItems.rbegin(); sortedItems.rend() != iter; ++iter )
+  {
+    if( RemoveActor( *iter ) )
     {
-      actor.SetSize(size);
+      actorRemoved = true;
     }
+  }
 
-    ApplyConstraints(actor, *mActiveLayout, itemId, 0.0f/*immediate*/);
+  if( actorRemoved )
+  {
+    ReapplyAllConstraints( durationSeconds );
   }
+}
+
+bool ItemView::RemoveActor(unsigned int itemId)
+{
+  bool removed( false );
 
-  self.Add(actor);
+  const ItemPoolIter removeIter = mItemPool.find( itemId );
+
+  if( removeIter != mItemPool.end() )
+  {
+    Self().Remove( removeIter->second );
+    removed = true;
+
+    // Adjust the remaining item IDs, for example if item 2 is removed:
+    //   Initial actors:     After insert:
+    //     ID 1 - ActorA       ID 1 - ActorA
+    //     ID 2 - ActorB       ID 2 - ActorC (previously ID 3)
+    //     ID 3 - ActorC       ID 3 - ActorB (previously ID 4)
+    //     ID 4 - ActorD
+    for (ItemPoolIter iter = removeIter; iter != mItemPool.end(); ++iter)
+    {
+      if( iter->first < mItemPool.rbegin()->first )
+      {
+        iter->second = mItemPool[ iter->first + 1 ];
+      }
+      else
+      {
+        mItemPool.erase( iter );
+        break;
+      }
+    }
+  }
+
+  return removed;
 }
 
-void ItemView::ActorRemovedFromItemPool(Actor actor, unsigned int itemId)
+void ItemView::ReplaceItem( Item replacementItem, float durationSeconds )
 {
-  Self().Remove(actor);
+  mAddingItems = true;
+
+  SetupActor( replacementItem, durationSeconds );
+  Self().Add( replacementItem.second );
+
+  const ItemPoolIter iter = mItemPool.find( replacementItem.first );
+  if( mItemPool.end() != iter )
+  {
+    Self().Remove( iter->second );
+    iter->second = replacementItem.second;
+  }
+  else
+  {
+    mItemPool.insert( replacementItem );
+  }
+
+  CalculateDomainSize(Self().GetCurrentSize());
+
+  mAddingItems = false;
 }
 
-void ItemView::RemoveItems(ItemRange range)
+void ItemView::ReplaceItems( const ItemContainer& replacementItems, float durationSeconds )
 {
-  mItemPool.RemoveItems(range);
+  for( ConstItemIter iter = replacementItems.begin(); replacementItems.end() != iter; ++iter )
+  {
+    ReplaceItem( *iter, durationSeconds );
+  }
 }
 
-void ItemView::AddItems(ItemLayout& layout, const Vector3& layoutSize, ItemRange range)
+void ItemView::RemoveActorsOutsideRange( ItemRange range )
+{
+  // Remove unwanted actors from the ItemView & ItemPool
+  for (ItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); )
+  {
+    unsigned int current = iter->first;
+
+    if( ! range.Within( current ) )
+    {
+      Self().Remove( iter->second );
+
+      mItemPool.erase( iter++ ); // erase invalidates the return value of post-increment; iter remains valid
+    }
+    else
+    {
+      ++iter;
+    }
+  }
+}
+
+void ItemView::AddActorsWithinRange( ItemRange range, float durationSeconds )
 {
   range.end = min(mItemFactory.GetNumberOfItems(), range.end);
 
-  mItemPool.AddItems(mRefreshOrderHint, range, layoutSize);
+  // The order of addition depends on the scroll direction.
+  if (mRefreshOrderHint)
+  {
+    for (unsigned int itemId = range.begin; itemId < range.end; ++itemId)
+    {
+      AddNewActor( itemId, durationSeconds );
+    }
+  }
+  else
+  {
+    for (unsigned int itemId = range.end; itemId > range.begin; --itemId)
+    {
+      AddNewActor( itemId-1, durationSeconds );
+    }
+  }
+
+  // Total number of items may change dynamically.
+  // Always recalculate the domain size to reflect that.
+  CalculateDomainSize(Self().GetCurrentSize());
+}
+
+void ItemView::AddNewActor( unsigned int itemId, float durationSeconds )
+{
+  mAddingItems = true;
+
+  if( mItemPool.end() == mItemPool.find( itemId ) )
+  {
+    Actor actor = mItemFactory.NewItem( itemId );
+
+    if( actor )
+    {
+      Item newItem( itemId, actor );
+
+      mItemPool.insert( newItem );
+
+      SetupActor( newItem, durationSeconds );
+      Self().Add( actor );
+    }
+  }
+
+  mAddingItems = false;
 }
 
-ItemRange ItemView::GetItemRange(ItemLayout& layout, const Vector3& layoutSize, bool reserveExtra)
+void ItemView::SetupActor( Item item, float durationSeconds )
+{
+  item.second.SetParentOrigin( ParentOrigin::CENTER );
+  item.second.SetAnchorPoint( AnchorPoint::CENTER );
+
+  if( mActiveLayout )
+  {
+    Vector3 size;
+    if( mActiveLayout->GetItemSize( item.first, mActiveLayoutTargetSize, size ) )
+    {
+      item.second.SetSize( size );
+    }
+
+    ApplyConstraints( item.second, *mActiveLayout, item.first, durationSeconds );
+  }
+}
+
+ItemRange ItemView::GetItemRange(ItemLayout& layout, const Vector3& layoutSize, float layoutPosition, bool reserveExtra)
 {
   unsigned int itemCount = mItemFactory.GetNumberOfItems();
 
   ItemRange available(0u, itemCount);
 
-  ItemRange range = layout.GetItemsWithinArea( GetCurrentLayoutPosition(0), layoutSize );
+  ItemRange range = layout.GetItemsWithinArea( layoutPosition, layoutSize );
 
   if (reserveExtra)
   {
@@ -905,6 +1063,20 @@ ItemRange ItemView::GetItemRange(ItemLayout& layout, const Vector3& layoutSize,
   return range.Intersection(available);
 }
 
+void ItemView::OnChildAdd(Actor& child)
+{
+  if(!mAddingItems)
+  {
+    // We don't want to do this downcast check for any item added by ItemView itself.
+    Dali::Toolkit::ScrollComponent scrollComponent = Dali::Toolkit::ScrollComponent::DownCast(child);
+    if(scrollComponent)
+    {
+      // Set the scroll connector when scroll bar is being added
+      scrollComponent.SetScrollConnector(mScrollConnector);
+    }
+  }
+}
+
 bool ItemView::OnTouchEvent(const TouchEvent& event)
 {
   // Ignore events with multiple-touch points
@@ -946,7 +1118,6 @@ bool ItemView::OnMouseWheelEvent(const MouseWheelEvent& event)
     mScrollPositionObject.SetProperty( ScrollConnector::SCROLL_POSITION, firstItemScrollPosition );
     self.SetProperty(mPropertyPosition, GetScrollPosition(firstItemScrollPosition, layoutSize));
     mScrollStartedSignalV2.Emit(GetCurrentScrollPosition());
-    StartRefreshTimer();
   }
 
   if (mMouseWheelEventFinishedTimer.IsRunning())
@@ -969,8 +1140,6 @@ bool ItemView::OnMouseWheelEventFinished()
     mScrollAnimation = DoAnchoring();
     if (mScrollAnimation)
     {
-      StartRefreshTimer();
-
       mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
       mScrollAnimation.Play();
     }
@@ -999,6 +1168,7 @@ void ItemView::ApplyConstraints(Actor& actor, ItemLayout& layout, unsigned int i
                                                       ParentSource( Actor::SIZE ),
                                                       wrapped );
     constraint.SetApplyTime(duration);
+    constraint.SetAlphaFunction(mDefaultAlphaFunction);
 
     actor.ApplyConstraint(constraint);
   }
@@ -1014,6 +1184,7 @@ void ItemView::ApplyConstraints(Actor& actor, ItemLayout& layout, unsigned int i
                                                          ParentSource( Actor::SIZE ),
                                                          wrapped );
     constraint.SetApplyTime(duration);
+    constraint.SetAlphaFunction(mDefaultAlphaFunction);
 
     actor.ApplyConstraint(constraint);
   }
@@ -1029,6 +1200,7 @@ void ItemView::ApplyConstraints(Actor& actor, ItemLayout& layout, unsigned int i
                                                       ParentSource( Actor::SIZE ),
                                                       wrapped );
     constraint.SetApplyTime(duration);
+    constraint.SetAlphaFunction(mDefaultAlphaFunction);
 
     actor.ApplyConstraint(constraint);
   }
@@ -1044,6 +1216,7 @@ void ItemView::ApplyConstraints(Actor& actor, ItemLayout& layout, unsigned int i
                                                       ParentSource( Actor::SIZE ),
                                                       wrapped );
     constraint.SetApplyTime(duration);
+    constraint.SetAlphaFunction(mDefaultAlphaFunction);
 
     // Release color constraints slowly; this allows ItemView to co-exist with ImageActor fade-in
     constraint.SetRemoveTime(DEFAULT_COLOR_VISIBILITY_REMOVE_TIME);
@@ -1063,6 +1236,7 @@ void ItemView::ApplyConstraints(Actor& actor, ItemLayout& layout, unsigned int i
                                                    ParentSource( Actor::SIZE ),
                                                    wrapped );
     constraint.SetApplyTime(duration);
+    constraint.SetAlphaFunction(mDefaultAlphaFunction);
 
     // Release visibility constraints the same time as the color constraint
     constraint.SetRemoveTime(DEFAULT_COLOR_VISIBILITY_REMOVE_TIME);
@@ -1072,6 +1246,20 @@ void ItemView::ApplyConstraints(Actor& actor, ItemLayout& layout, unsigned int i
   }
 }
 
+void ItemView::ReapplyAllConstraints( float durationSeconds )
+{
+  for (ConstItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
+  {
+    unsigned int id = iter->first;
+    Actor actor = iter->second;
+
+    actor.RemoveConstraints();
+    ApplyConstraints(actor, *mActiveLayout, id, durationSeconds);
+  }
+
+  CalculateDomainSize(Self().GetCurrentSize());
+}
+
 float ItemView::ClampFirstItemPosition(float targetPosition, const Vector3& targetSize, ItemLayout& layout)
 {
   Actor self = Self();
@@ -1193,8 +1381,6 @@ void ItemView::OnPan(PanGesture gesture)
       {
         AnimateScrollOvershoot(0.0f);
       }
-
-      StartRefreshTimer();
     }
     break;
 
@@ -1210,8 +1396,6 @@ void ItemView::OnPan(PanGesture gesture)
 
   if (mScrollAnimation)
   {
-    StartRefreshTimer();
-
     mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
     mScrollAnimation.Play();
   }
@@ -1333,36 +1517,12 @@ void ItemView::OnOvershootOnFinished(Animation& animation)
   }
 }
 
-void ItemView::StartRefreshTimer()
-{
-  if (!mRefreshTimer)
-  {
-    mRefreshTimer = Timer::New( mRefreshIntervalMilliseconds );
-    mRefreshTimer.TickSignal().Connect( this, &ItemView::OnRefreshTick );
-  }
-
-  if (!mRefreshTimer.IsRunning())
-  {
-    mRefreshTimer.Start();
-  }
-}
-
-void ItemView::CancelRefreshTimer()
-{
-  if (mRefreshTimer)
-  {
-    mRefreshTimer.Stop();
-  }
-}
-
 void ItemView::ScrollToItem(unsigned int itemId, float durationSeconds)
 {
   Actor self = Self();
   const Vector3 layoutSize = Self().GetCurrentSize();
   float firstItemScrollPosition = ClampFirstItemPosition(mActiveLayout->GetItemScrollToPosition(itemId), layoutSize, *mActiveLayout);
 
-  StartRefreshTimer();
-
   if(durationSeconds > 0.0f)
   {
     RemoveAnimation(mScrollAnimation);
@@ -1407,23 +1567,31 @@ void ItemView::CalculateDomainSize(const Vector3& layoutSize)
     }
 
     float minLayoutPosition = mActiveLayout->GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), layoutSize);
+    self.SetProperty(mPropertyMinimumLayoutPosition, minLayoutPosition);
+
     ItemLayout::Vector3Function lastItemPositionConstraint;
     if (mActiveLayout->GetPositionConstraint(fabs(minLayoutPosition), lastItemPositionConstraint))
     {
       lastItemPosition = lastItemPositionConstraint(Vector3::ZERO, fabs(minLayoutPosition), 0.0f, layoutSize);
     }
 
+    float domainSize;
+
     if(IsHorizontal(mActiveLayout->GetOrientation()))
     {
       self.SetProperty(mPropertyPositionMin, Vector3(0.0f, firstItemPosition.x, 0.0f));
       self.SetProperty(mPropertyPositionMax, Vector3(0.0f, lastItemPosition.x, 0.0f));
+      domainSize = fabs(firstItemPosition.x - lastItemPosition.x);
     }
     else
     {
       self.SetProperty(mPropertyPositionMin, Vector3(0.0f, firstItemPosition.y, 0.0f));
       self.SetProperty(mPropertyPositionMax, Vector3(0.0f, lastItemPosition.y, 0.0f));
+      domainSize = fabs(firstItemPosition.y - lastItemPosition.y);
     }
 
+    mScrollConnector.SetScrollDomain(minLayoutPosition, 0.0f, domainSize);
+
     bool isLayoutScrollable = IsLayoutScrollable(layoutSize);
     self.SetProperty(mPropertyCanScrollVertical, isLayoutScrollable);
     self.SetProperty(mPropertyCanScrollHorizontal, false);
@@ -1486,8 +1654,6 @@ void ItemView::ScrollTo(const Vector3& position, float duration)
 
   float firstItemScrollPosition = ClampFirstItemPosition(position.y, layoutSize, *mActiveLayout);
 
-  StartRefreshTimer();
-
   if(duration > 0.0f)
   {
     RemoveAnimation(mScrollAnimation);
@@ -1510,7 +1676,7 @@ void ItemView::ApplyOvershootOverlayConstraints()
 {
   Constraint constraint = Constraint::New<float>( Actor::SIZE_WIDTH,
                                                     ParentSource( mPropertyScrollDirection ),
-                                                    ParentSource( mPropertyOvershoot ),
+                                                    Source( mScrollPositionObject, ScrollConnector::OVERSHOOT ),
                                                     ParentSource( Actor::SIZE ),
                                                     OvershootOverlaySizeConstraint() );
   mOvershootOverlay.ApplyConstraint(constraint);
@@ -1518,14 +1684,14 @@ void ItemView::ApplyOvershootOverlayConstraints()
 
   constraint = Constraint::New<Quaternion>( Actor::ROTATION,
                                             ParentSource( mPropertyScrollDirection ),
-                                            ParentSource( mPropertyOvershoot ),
+                                            Source( mScrollPositionObject, ScrollConnector::OVERSHOOT ),
                                             OvershootOverlayRotationConstraint() );
   mOvershootOverlay.ApplyConstraint(constraint);
 
   constraint = Constraint::New<Vector3>( Actor::POSITION,
                                          ParentSource( Actor::SIZE ),
                                          ParentSource( mPropertyScrollDirection ),
-                                         ParentSource( mPropertyOvershoot ),
+                                         Source( mScrollPositionObject, ScrollConnector::OVERSHOOT ),
                                          OvershootOverlayPositionConstraint() );
   mOvershootOverlay.ApplyConstraint(constraint);
 
@@ -1537,7 +1703,7 @@ void ItemView::ApplyOvershootOverlayConstraints()
   int effectOvershootPropertyIndex = mOvershootEffect.GetPropertyIndex(mOvershootEffect.GetOvershootPropertyName());
   Actor self = Self();
   constraint = Constraint::New<float>( effectOvershootPropertyIndex,
-                                       Source( self, mPropertyOvershoot ),
+                                       Source( mScrollPositionObject, ScrollConnector::OVERSHOOT ),
                                        EqualToConstraint() );
   mOvershootEffect.ApplyConstraint(constraint);
 }
@@ -1576,13 +1742,13 @@ void ItemView::AnimateScrollOvershoot(float overshootAmount, bool animateBack)
   }
 
   Actor self = Self();
-  float currentOvershoot = self.GetProperty<float>(mPropertyOvershoot);
+  float currentOvershoot = mScrollPositionObject.GetProperty<float>(ScrollConnector::OVERSHOOT);
   float duration = DEFAULT_OVERSHOOT_ANIMATION_DURATION * (animatingOn ? (1.0f - fabsf(currentOvershoot)) : fabsf(currentOvershoot));
 
   RemoveAnimation(mScrollOvershootAnimation);
   mScrollOvershootAnimation = Animation::New(duration);
   mScrollOvershootAnimation.FinishedSignal().Connect(this, &ItemView::OnOvershootOnFinished);
-  mScrollOvershootAnimation.AnimateTo( Property(self, mPropertyOvershoot), overshootAmount, TimePeriod(0.0f, duration) );
+  mScrollOvershootAnimation.AnimateTo( Property(mScrollPositionObject, ScrollConnector::OVERSHOOT), overshootAmount, TimePeriod(0.0f, duration) );
   mScrollOvershootAnimation.Play();
 
   mAnimatingOvershootOn = animatingOn;