Merge branch 'devel/master' into devel/new_mesh
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / controls / scrollable / item-view / item-view-impl.cpp
1 /*
2  * Copyright (c) 2014 Samsung Electronics Co., Ltd.
3  *
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
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  *
16  */
17
18 // CLASS HEADER
19 #include <dali-toolkit/internal/controls/scrollable/item-view/item-view-impl.h>
20
21 // EXTERNAL INCLUDES
22 #include <cstring> // for strcmp
23 #include <algorithm>
24 #include <dali/public-api/animation/constraint.h>
25 #include <dali/public-api/animation/constraints.h>
26 #include <dali/devel-api/common/set-wrapper.h>
27 #include <dali/public-api/common/stage.h>
28 #include <dali/public-api/events/wheel-event.h>
29 #include <dali/public-api/events/touch-event.h>
30 #include <dali/public-api/object/type-registry.h>
31 #include <dali/devel-api/object/type-registry-helper.h>
32
33 // INTERNAL INCLUDES
34 #include <dali-toolkit/public-api/controls/scroll-bar/scroll-bar.h>
35 #include <dali-toolkit/public-api/controls/scrollable/item-view/item-factory.h>
36 #include <dali-toolkit/internal/controls/scrollable/bouncing-effect-actor.h>
37
38 using std::string;
39 using std::set;
40 using namespace Dali;
41
42 namespace // Unnamed namespace
43 {
44
45 //Type registration
46
47 DALI_TYPE_REGISTRATION_BEGIN( Toolkit::ItemView, Toolkit::Scrollable, NULL)
48
49 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "layout-position",     FLOAT,    LAYOUT_POSITION)
50 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "scroll-speed",        FLOAT,    SCROLL_SPEED)
51 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "overshoot",           FLOAT,    OVERSHOOT)
52 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "scroll-direction",    VECTOR2,  SCROLL_DIRECTION)
53 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "layout-orientation",  INTEGER,  LAYOUT_ORIENTATION)
54 DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "scroll-content-size", FLOAT,    SCROLL_CONTENT_SIZE)
55
56 DALI_SIGNAL_REGISTRATION(              Toolkit, ItemView, "layout-activated",    LAYOUT_ACTIVATED_SIGNAL )
57
58 DALI_TYPE_REGISTRATION_END()
59
60 const float DEFAULT_MINIMUM_SWIPE_SPEED = 1.0f;
61 const float DEFAULT_MINIMUM_SWIPE_DISTANCE = 3.0f;
62 const float DEFAULT_WHEEL_SCROLL_DISTANCE_STEP_PROPORTION = 0.1f;
63
64 const float DEFAULT_MINIMUM_SWIPE_DURATION = 0.45f;
65 const float DEFAULT_MAXIMUM_SWIPE_DURATION = 2.6f;
66
67 const float DEFAULT_REFRESH_INTERVAL_LAYOUT_POSITIONS = 20.0f; // 1 updates per 20 items
68 const int WHEEL_EVENT_FINISHED_TIME_OUT = 500;  // 0.5 second
69
70 const float DEFAULT_ANCHORING_DURATION = 1.0f;  // 1 second
71
72 const float MILLISECONDS_PER_SECONDS = 1000.0f;
73
74 const Vector2 OVERSHOOT_BOUNCE_ACTOR_DEFAULT_SIZE( 720.0f, 42.0f );
75 const float OVERSHOOT_BOUNCE_ACTOR_RESIZE_THRESHOLD = 180.0f;
76 const Vector4 OVERSHOOT_OVERLAY_NINE_PATCH_BORDER(0.0f, 0.0f, 1.0f, 12.0f);
77 const float DEFAULT_KEYBOARD_FOCUS_SCROLL_DURATION = 0.2f;
78
79 /**
80  * Local helper to convert pan distance (in actor coordinates) to the layout-specific scrolling direction
81  */
82 float CalculateScrollDistance(Vector2 panDistance, Toolkit::ItemLayout& layout)
83 {
84   Radian scrollDirection(layout.GetScrollDirection());
85
86   float cosTheta = cosf(scrollDirection);
87   float sinTheta = sinf(scrollDirection);
88
89   return panDistance.x * sinTheta + panDistance.y * cosTheta;
90 }
91
92 // Overshoot overlay constraints
93 void OvershootOverlaySizeConstraint( Vector3& current, const PropertyInputContainer& inputs )
94 {
95   const Vector2& parentScrollDirection = inputs[0]->GetVector2();
96   const Toolkit::ControlOrientation::Type& layoutOrientation = static_cast<Toolkit::ControlOrientation::Type>(inputs[1]->GetInteger());
97   const Vector3& parentSize = inputs[2]->GetVector3();
98
99   if(Toolkit::IsVertical(layoutOrientation))
100   {
101     current.width = fabsf(parentScrollDirection.y) > Math::MACHINE_EPSILON_1 ? parentSize.x : parentSize.y;
102   }
103   else
104   {
105     current.width = fabsf(parentScrollDirection.x) > Math::MACHINE_EPSILON_1 ? parentSize.y : parentSize.x;
106   }
107
108   current.height = ( current.width > OVERSHOOT_BOUNCE_ACTOR_RESIZE_THRESHOLD ) ? OVERSHOOT_BOUNCE_ACTOR_DEFAULT_SIZE.height : OVERSHOOT_BOUNCE_ACTOR_DEFAULT_SIZE.height*0.5f;
109 }
110
111 void OvershootOverlayRotationConstraint( Quaternion& current, const PropertyInputContainer& inputs )
112 {
113   const Vector2& parentScrollDirection = inputs[0]->GetVector2();
114   const Toolkit::ControlOrientation::Type& layoutOrientation = static_cast<Toolkit::ControlOrientation::Type>(inputs[1]->GetInteger());
115   const float parentOvershoot = inputs[2]->GetFloat();
116
117   float multiplier = 0;
118   if(Toolkit::IsVertical(layoutOrientation))
119   {
120     if(fabsf(parentScrollDirection.y) <= Math::MACHINE_EPSILON_1)
121     {
122       if( (layoutOrientation == Toolkit::ControlOrientation::Up && parentOvershoot < Math::MACHINE_EPSILON_0)
123           || (layoutOrientation == Toolkit::ControlOrientation::Down && parentOvershoot > Math::MACHINE_EPSILON_0) )
124       {
125         multiplier = 0.5f;
126       }
127       else
128       {
129         multiplier = 1.5f;
130       }
131     }
132     else if( (parentOvershoot > Math::MACHINE_EPSILON_0 && parentScrollDirection.y > Math::MACHINE_EPSILON_0)
133           || (parentOvershoot < Math::MACHINE_EPSILON_0 && parentScrollDirection.y < Math::MACHINE_EPSILON_0) )
134     {
135       multiplier = 0.0f;
136     }
137     else
138     {
139       multiplier = 1.0f;
140     }
141   }
142   else
143   {
144     if(fabsf(parentScrollDirection.x) <= Math::MACHINE_EPSILON_1)
145     {
146       if( (layoutOrientation == Toolkit::ControlOrientation::Left && parentOvershoot > Math::MACHINE_EPSILON_0)
147           ||(layoutOrientation == Toolkit::ControlOrientation::Right && parentOvershoot < Math::MACHINE_EPSILON_0) )
148       {
149         multiplier = 1.0f;
150       }
151       else
152       {
153         multiplier = 0.0f;
154       }
155     }
156     else if( (parentOvershoot > Math::MACHINE_EPSILON_0 && parentScrollDirection.x > Math::MACHINE_EPSILON_0)
157           || (parentOvershoot < Math::MACHINE_EPSILON_0 && parentScrollDirection.x < Math::MACHINE_EPSILON_0) )
158     {
159       multiplier = 1.5f;
160     }
161     else
162     {
163       multiplier = 0.5f;
164     }
165   }
166
167   current = Quaternion( Radian( multiplier * Math::PI ), Vector3::ZAXIS );
168 }
169
170 void OvershootOverlayPositionConstraint( Vector3& current, const PropertyInputContainer& inputs )
171 {
172   const Vector3& parentSize = inputs[0]->GetVector3();
173   const Vector2& parentScrollDirection = inputs[1]->GetVector2();
174   const Toolkit::ControlOrientation::Type& layoutOrientation = static_cast<Toolkit::ControlOrientation::Type>(inputs[2]->GetInteger());
175   const float parentOvershoot = inputs[3]->GetFloat();
176
177   Vector3 relativeOffset;
178
179   if(Toolkit::IsVertical(layoutOrientation))
180   {
181     if(fabsf(parentScrollDirection.y) <= Math::MACHINE_EPSILON_1)
182     {
183       if( (layoutOrientation == Toolkit::ControlOrientation::Up && parentOvershoot < Math::MACHINE_EPSILON_0)
184           || (layoutOrientation == Toolkit::ControlOrientation::Down && parentOvershoot > Math::MACHINE_EPSILON_0) )
185       {
186         relativeOffset = Vector3(1.0f, 0.0f, 0.0f);
187       }
188       else
189       {
190         relativeOffset =Vector3(0.0f, 1.0f, 0.0f);
191       }
192     }
193     else if( (parentOvershoot > Math::MACHINE_EPSILON_0 && parentScrollDirection.y > Math::MACHINE_EPSILON_0)
194           || (parentOvershoot < Math::MACHINE_EPSILON_0 && parentScrollDirection.y < Math::MACHINE_EPSILON_0) )
195     {
196       relativeOffset = Vector3(0.0f, 0.0f, 0.0f);
197     }
198     else
199     {
200       relativeOffset = Vector3(1.0f, 1.0f, 0.0f);
201     }
202   }
203   else
204   {
205     if(fabsf(parentScrollDirection.x) <= Math::MACHINE_EPSILON_1)
206     {
207       if( (layoutOrientation == Toolkit::ControlOrientation::Left && parentOvershoot < Math::MACHINE_EPSILON_0)
208           || (layoutOrientation == Toolkit::ControlOrientation::Right && parentOvershoot > Math::MACHINE_EPSILON_0) )
209       {
210         relativeOffset = Vector3(0.0f, 0.0f, 0.0f);
211       }
212       else
213       {
214         relativeOffset = Vector3(1.0f, 1.0f, 0.0f);
215       }
216     }
217     else if( (parentOvershoot > Math::MACHINE_EPSILON_0 && parentScrollDirection.x > Math::MACHINE_EPSILON_0)
218           || (parentOvershoot < Math::MACHINE_EPSILON_0 && parentScrollDirection.x < Math::MACHINE_EPSILON_0) )
219     {
220       relativeOffset = Vector3(0.0f, 1.0f, 0.0f);
221     }
222     else
223     {
224       relativeOffset = Vector3(1.0f, 0.0f, 0.0f);
225     }
226   }
227
228   current = relativeOffset * parentSize;
229 }
230
231 void OvershootOverlayVisibilityConstraint( bool& current, const PropertyInputContainer& inputs )
232 {
233   current = inputs[0]->GetBoolean();
234 }
235
236 } // unnamed namespace
237
238 namespace Dali
239 {
240
241 namespace Toolkit
242 {
243
244 namespace Internal
245 {
246
247 namespace // unnamed namespace
248 {
249
250 bool FindById( const ItemContainer& items, ItemId id )
251 {
252   for( ConstItemIter iter = items.begin(); items.end() != iter; ++iter )
253   {
254     if( iter->first == id )
255     {
256       return true;
257     }
258   }
259
260   return false;
261 }
262
263 } // unnamed namespace
264
265 Dali::Toolkit::ItemView ItemView::New(ItemFactory& factory)
266 {
267   // Create the implementation
268   ItemViewPtr itemView(new ItemView(factory));
269
270   // Pass ownership to CustomActor via derived handle
271   Dali::Toolkit::ItemView handle(*itemView);
272
273   // Second-phase init of the implementation
274   // This can only be done after the CustomActor connection has been made...
275   itemView->Initialize();
276
277   return handle;
278 }
279
280 ItemView::ItemView(ItemFactory& factory)
281 : Scrollable( ControlBehaviour( DISABLE_SIZE_NEGOTIATION | REQUIRES_WHEEL_EVENTS | REQUIRES_KEYBOARD_NAVIGATION_SUPPORT ) ),
282   mItemFactory(factory),
283   mActiveLayout(NULL),
284   mAnimatingOvershootOn(false),
285   mAnimateOvershootOff(false),
286   mAnchoringEnabled(false),
287   mAnchoringDuration(DEFAULT_ANCHORING_DURATION),
288   mRefreshIntervalLayoutPositions(0.0f),
289   mRefreshOrderHint(true/*Refresh item 0 first*/),
290   mMinimumSwipeSpeed(DEFAULT_MINIMUM_SWIPE_SPEED),
291   mMinimumSwipeDistance(DEFAULT_MINIMUM_SWIPE_DISTANCE),
292   mWheelScrollDistanceStep(0.0f),
293   mScrollDistance(0.0f),
294   mScrollSpeed(0.0f),
295   mTotalPanDisplacement(Vector2::ZERO),
296   mScrollOvershoot(0.0f),
297   mIsFlicking(false),
298   mGestureState(Gesture::Clear),
299   mAddingItems(false),
300   mRefreshEnabled(true),
301   mItemsParentOrigin( ParentOrigin::CENTER),
302   mItemsAnchorPoint( AnchorPoint::CENTER)
303 {
304 }
305
306 void ItemView::OnInitialize()
307 {
308   Actor self = Self();
309
310   SetOvershootEnabled(true);
311
312   Vector2 stageSize = Stage::GetCurrent().GetSize();
313   mWheelScrollDistanceStep = stageSize.y * DEFAULT_WHEEL_SCROLL_DISTANCE_STEP_PROPORTION;
314
315   EnableGestureDetection(Gesture::Type(Gesture::Pan));
316
317   mWheelEventFinishedTimer = Timer::New( WHEEL_EVENT_FINISHED_TIME_OUT );
318   mWheelEventFinishedTimer.TickSignal().Connect( this, &ItemView::OnWheelEventFinished );
319
320   SetRefreshInterval(DEFAULT_REFRESH_INTERVAL_LAYOUT_POSITIONS);
321 }
322
323 ItemView::~ItemView()
324 {
325 }
326
327 unsigned int ItemView::GetLayoutCount() const
328 {
329   return mLayouts.size();
330 }
331
332 void ItemView::AddLayout(ItemLayout& layout)
333 {
334   mLayouts.push_back(ItemLayoutPtr(&layout));
335 }
336
337 void ItemView::RemoveLayout(unsigned int layoutIndex)
338 {
339   DALI_ASSERT_ALWAYS(layoutIndex < mLayouts.size());
340
341   if (mActiveLayout == mLayouts[layoutIndex].Get())
342   {
343     mActiveLayout = NULL;
344   }
345
346   mLayouts.erase(mLayouts.begin() + layoutIndex);
347 }
348
349 ItemLayoutPtr ItemView::GetLayout(unsigned int layoutIndex) const
350 {
351   return mLayouts[layoutIndex];
352 }
353
354 ItemLayoutPtr ItemView::GetActiveLayout() const
355 {
356   return ItemLayoutPtr(mActiveLayout);
357 }
358
359 float ItemView::GetCurrentLayoutPosition(unsigned int itemId) const
360 {
361   return Self().GetProperty<float>( Toolkit::ItemView::Property::LAYOUT_POSITION ) + static_cast<float>( itemId );
362 }
363
364 void ItemView::ActivateLayout(unsigned int layoutIndex, const Vector3& targetSize, float durationSeconds)
365 {
366   DALI_ASSERT_ALWAYS(layoutIndex < mLayouts.size());
367
368   mRefreshEnabled = false;
369
370   Actor self = Self();
371
372   // The ItemView size should match the active layout size
373   self.SetSize(targetSize);
374   mActiveLayoutTargetSize = targetSize;
375
376   // Switch to the new layout
377   mActiveLayout = mLayouts[layoutIndex].Get();
378
379   // Move the items to the new layout positions...
380
381   for (ConstItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
382   {
383     unsigned int itemId = iter->first;
384     Actor actor = iter->second;
385
386     // Remove constraints from previous layout
387     actor.RemoveConstraints();
388
389     Vector3 size;
390     mActiveLayout->GetItemSize( itemId, targetSize, size );
391     actor.SetSize( size.GetVectorXY() );
392
393     mActiveLayout->ApplyConstraints(actor, itemId, targetSize, Self() );
394   }
395
396   // Refresh the new layout
397   ItemRange range = GetItemRange(*mActiveLayout, targetSize, GetCurrentLayoutPosition(0), false/* don't reserve extra*/);
398   AddActorsWithinRange( range, targetSize );
399
400   // Scroll to an appropriate layout position
401
402   bool scrollAnimationNeeded(false);
403   float firstItemScrollPosition(0.0f);
404
405   float current = GetCurrentLayoutPosition(0);
406   float minimum = ClampFirstItemPosition(current, targetSize, *mActiveLayout);
407
408   if (current < minimum)
409   {
410     scrollAnimationNeeded = true;
411     firstItemScrollPosition = minimum;
412   }
413   else if (mAnchoringEnabled)
414   {
415     scrollAnimationNeeded = true;
416     firstItemScrollPosition = mActiveLayout->GetClosestAnchorPosition(current);
417   }
418
419   if (scrollAnimationNeeded)
420   {
421     RemoveAnimation(mScrollAnimation);
422     mScrollAnimation = Animation::New(durationSeconds);
423     mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), firstItemScrollPosition, AlphaFunction::EASE_OUT );
424     mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnLayoutActivationScrollFinished);
425     mScrollAnimation.Play();
426   }
427   else
428   {
429     // Emit the layout activated signal
430     mLayoutActivatedSignal.Emit();
431   }
432
433   AnimateScrollOvershoot(0.0f);
434   mScrollOvershoot = 0.0f;
435
436   Radian scrollDirection(mActiveLayout->GetScrollDirection());
437   self.SetProperty(Toolkit::ItemView::Property::SCROLL_DIRECTION, Vector2(sinf(scrollDirection), cosf(scrollDirection)));
438   self.SetProperty(Toolkit::ItemView::Property::LAYOUT_ORIENTATION, static_cast<int>(mActiveLayout->GetOrientation()));
439   self.SetProperty(Toolkit::ItemView::Property::SCROLL_SPEED, mScrollSpeed);
440
441   CalculateDomainSize(targetSize);
442 }
443
444 void ItemView::DeactivateCurrentLayout()
445 {
446   if (mActiveLayout)
447   {
448     for (ConstItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
449     {
450       Actor actor = iter->second;
451       actor.RemoveConstraints();
452     }
453
454     mActiveLayout = NULL;
455   }
456 }
457
458 void ItemView::OnRefreshNotification(PropertyNotification& source)
459 {
460   if(mRefreshEnabled || mScrollAnimation)
461   {
462     // Only refresh the cache during normal scrolling
463     DoRefresh(GetCurrentLayoutPosition(0), true);
464   }
465 }
466
467 void ItemView::Refresh()
468 {
469   for (ItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter )
470   {
471     ReleaseActor( iter->first, iter->second );
472   }
473   mItemPool.clear();
474
475   DoRefresh(GetCurrentLayoutPosition(0), true);
476 }
477
478 void ItemView::DoRefresh(float currentLayoutPosition, bool cacheExtra)
479 {
480   if (mActiveLayout)
481   {
482     ItemRange range = GetItemRange(*mActiveLayout, mActiveLayoutTargetSize, currentLayoutPosition, cacheExtra/*reserve extra*/);
483     RemoveActorsOutsideRange( range );
484     AddActorsWithinRange( range, Self().GetCurrentSize() );
485
486     mScrollUpdatedSignal.Emit( Vector2(0.0f, currentLayoutPosition) );
487   }
488 }
489
490 void ItemView::SetMinimumSwipeSpeed(float speed)
491 {
492   mMinimumSwipeSpeed = speed;
493 }
494
495 float ItemView::GetMinimumSwipeSpeed() const
496 {
497   return mMinimumSwipeSpeed;
498 }
499
500 void ItemView::SetMinimumSwipeDistance(float distance)
501 {
502   mMinimumSwipeDistance = distance;
503 }
504
505 float ItemView::GetMinimumSwipeDistance() const
506 {
507   return mMinimumSwipeDistance;
508 }
509
510 void ItemView::SetWheelScrollDistanceStep(float step)
511 {
512   mWheelScrollDistanceStep = step;
513 }
514
515 float ItemView::GetWheelScrollDistanceStep() const
516 {
517   return mWheelScrollDistanceStep;
518 }
519
520 void ItemView::SetAnchoring(bool enabled)
521 {
522   mAnchoringEnabled = enabled;
523 }
524
525 bool ItemView::GetAnchoring() const
526 {
527   return mAnchoringEnabled;
528 }
529
530 void ItemView::SetAnchoringDuration(float durationSeconds)
531 {
532   mAnchoringDuration = durationSeconds;
533 }
534
535 float ItemView::GetAnchoringDuration() const
536 {
537   return mAnchoringDuration;
538 }
539
540 void ItemView::SetRefreshInterval(float intervalLayoutPositions)
541 {
542   if( !Equals(mRefreshIntervalLayoutPositions, intervalLayoutPositions) )
543   {
544     mRefreshIntervalLayoutPositions = intervalLayoutPositions;
545
546     Actor self = Self();
547     if(mRefreshNotification)
548     {
549       self.RemovePropertyNotification(mRefreshNotification);
550     }
551     mRefreshNotification = self.AddPropertyNotification( Toolkit::ItemView::Property::LAYOUT_POSITION, StepCondition(mRefreshIntervalLayoutPositions, 0.0f) );
552     mRefreshNotification.NotifySignal().Connect( this, &ItemView::OnRefreshNotification );
553   }
554 }
555
556 float ItemView::GetRefreshInterval() const
557 {
558   return mRefreshIntervalLayoutPositions;
559 }
560
561 void ItemView::SetRefreshEnabled(bool enabled)
562 {
563   mRefreshEnabled = enabled;
564 }
565
566 Actor ItemView::GetItem(unsigned int itemId) const
567 {
568   Actor actor;
569
570   ConstItemPoolIter iter = mItemPool.find( itemId );
571   if( iter != mItemPool.end() )
572   {
573     actor = iter->second;
574   }
575
576   return actor;
577 }
578
579 unsigned int ItemView::GetItemId( Actor actor ) const
580 {
581   unsigned int itemId( 0 );
582
583   for ( ConstItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter )
584   {
585     if( iter->second == actor )
586     {
587       itemId = iter->first;
588       break;
589     }
590   }
591
592   return itemId;
593 }
594
595 void ItemView::InsertItem( Item newItem, float durationSeconds )
596 {
597   mAddingItems = true;
598   Vector3 layoutSize = Self().GetCurrentSize();
599
600   Actor displacedActor;
601   ItemPoolIter afterDisplacedIter = mItemPool.end();
602
603   ItemPoolIter foundIter = mItemPool.find( newItem.first );
604   if( mItemPool.end() != foundIter )
605   {
606     SetupActor( newItem, layoutSize );
607     Self().Add( newItem.second );
608
609     displacedActor = foundIter->second;
610     foundIter->second = newItem.second;
611
612     afterDisplacedIter = ++foundIter;
613   }
614   else
615   {
616     // Inserting before the existing item range?
617     ItemPoolIter iter = mItemPool.begin();
618     if( iter != mItemPool.end() &&
619         iter->first > newItem.first )
620     {
621       displacedActor = iter->second;
622       mItemPool.erase( iter++ ); // iter is still valid after the erase
623
624       afterDisplacedIter = iter;
625     }
626   }
627
628   if( displacedActor )
629   {
630     // Move the existing actors to make room
631     for( ItemPoolIter iter = afterDisplacedIter; mItemPool.end() != iter; ++iter )
632     {
633       Actor temp = iter->second;
634       iter->second = displacedActor;
635       displacedActor = temp;
636
637       iter->second.RemoveConstraints();
638       mActiveLayout->ApplyConstraints( iter->second, iter->first, layoutSize, Self() );
639     }
640
641     // Create last item
642     ItemPool::reverse_iterator lastIter = mItemPool.rbegin();
643     if ( lastIter != mItemPool.rend() )
644     {
645       ItemId lastId = lastIter->first;
646       Item lastItem( lastId + 1, displacedActor );
647       mItemPool.insert( lastItem );
648
649       lastItem.second.RemoveConstraints();
650       mActiveLayout->ApplyConstraints( lastItem.second, lastItem.first, layoutSize, Self() );
651     }
652   }
653
654   CalculateDomainSize( layoutSize );
655
656   mAddingItems = false;
657 }
658
659 void ItemView::InsertItems( const ItemContainer& newItems, float durationSeconds )
660 {
661   mAddingItems = true;
662   Vector3 layoutSize = Self().GetCurrentSize();
663
664   // Insert from lowest id to highest
665   std::set<Item> sortedItems;
666   for( ConstItemIter iter = newItems.begin(); newItems.end() != iter; ++iter )
667   {
668     sortedItems.insert( *iter );
669   }
670
671   for( std::set<Item>::iterator iter = sortedItems.begin(); sortedItems.end() != iter; ++iter )
672   {
673     Self().Add( iter->second );
674
675     ItemPoolIter foundIter = mItemPool.find( iter->first );
676     if( mItemPool.end() != foundIter )
677     {
678       Actor moveMe = foundIter->second;
679       foundIter->second = iter->second;
680
681       // Move the existing actors to make room
682       for( ItemPoolIter iter = ++foundIter; mItemPool.end() != iter; ++iter )
683       {
684         Actor temp = iter->second;
685         iter->second = moveMe;
686         moveMe = temp;
687       }
688
689       // Create last item
690       ItemId lastId = mItemPool.rbegin()->first;
691       Item lastItem( lastId + 1, moveMe );
692       mItemPool.insert( lastItem );
693     }
694     else
695     {
696       mItemPool.insert( *iter );
697     }
698   }
699
700   // Relayout everything
701   for (ItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
702   {
703     // If newly inserted
704     if( FindById( newItems, iter->first ) )
705     {
706       SetupActor( *iter, layoutSize );
707     }
708     else
709     {
710       iter->second.RemoveConstraints();
711       mActiveLayout->ApplyConstraints( iter->second, iter->first, layoutSize, Self() );
712     }
713   }
714
715   CalculateDomainSize( layoutSize );
716
717   mAddingItems = false;
718 }
719
720 void ItemView::RemoveItem( unsigned int itemId, float durationSeconds )
721 {
722   bool actorsReordered = RemoveActor( itemId );
723   if( actorsReordered )
724   {
725     ReapplyAllConstraints();
726
727     OnItemsRemoved();
728   }
729 }
730
731 void ItemView::RemoveItems( const ItemIdContainer& itemIds, float durationSeconds )
732 {
733   bool actorsReordered( false );
734
735   // Remove from highest id to lowest
736   set<ItemId> sortedItems;
737   for( ConstItemIdIter iter = itemIds.begin(); itemIds.end() != iter; ++iter )
738   {
739     sortedItems.insert( *iter );
740   }
741
742   for( set<ItemId>::reverse_iterator iter = sortedItems.rbegin(); sortedItems.rend() != iter; ++iter )
743   {
744     if( RemoveActor( *iter ) )
745     {
746       actorsReordered = true;
747     }
748   }
749
750   if( actorsReordered )
751   {
752     ReapplyAllConstraints();
753
754     OnItemsRemoved();
755   }
756 }
757
758 bool ItemView::RemoveActor(unsigned int itemId)
759 {
760   bool reordered( false );
761
762   ItemPoolIter removeIter = mItemPool.find( itemId );
763   if( removeIter != mItemPool.end() )
764   {
765     ReleaseActor(itemId, removeIter->second);
766   }
767   else
768   {
769     // Removing before the existing item range?
770     ItemPoolIter iter = mItemPool.begin();
771     if( iter != mItemPool.end() &&
772         iter->first > itemId )
773     {
774       // In order to decrement the first visible item ID
775       mItemPool.insert( Item(iter->first - 1, Actor()) );
776
777       removeIter = mItemPool.begin();
778     }
779   }
780
781   if( removeIter != mItemPool.end() )
782   {
783     reordered = true;
784
785     // Adjust the remaining item IDs, for example if item 2 is removed:
786     //   Initial actors:     After insert:
787     //     ID 1 - ActorA       ID 1 - ActorA
788     //     ID 2 - ActorB       ID 2 - ActorC (previously ID 3)
789     //     ID 3 - ActorC       ID 3 - ActorB (previously ID 4)
790     //     ID 4 - ActorD
791     for (ItemPoolIter iter = removeIter; iter != mItemPool.end(); ++iter)
792     {
793       if( iter->first < mItemPool.rbegin()->first )
794       {
795         iter->second = mItemPool[ iter->first + 1 ];
796       }
797       else
798       {
799         mItemPool.erase( iter );
800         break;
801       }
802     }
803   }
804
805   return reordered;
806 }
807
808 void ItemView::ReplaceItem( Item replacementItem, float durationSeconds )
809 {
810   mAddingItems = true;
811   Vector3 layoutSize = Self().GetCurrentSize();
812
813   SetupActor( replacementItem, layoutSize );
814   Self().Add( replacementItem.second );
815
816   const ItemPoolIter iter = mItemPool.find( replacementItem.first );
817   if( mItemPool.end() != iter )
818   {
819     ReleaseActor(iter->first, iter->second);
820     iter->second = replacementItem.second;
821   }
822   else
823   {
824     mItemPool.insert( replacementItem );
825   }
826
827   CalculateDomainSize( layoutSize );
828
829   mAddingItems = false;
830 }
831
832 void ItemView::ReplaceItems( const ItemContainer& replacementItems, float durationSeconds )
833 {
834   for( ConstItemIter iter = replacementItems.begin(); replacementItems.end() != iter; ++iter )
835   {
836     ReplaceItem( *iter, durationSeconds );
837   }
838 }
839
840 void ItemView::RemoveActorsOutsideRange( ItemRange range )
841 {
842   // Remove unwanted actors from the ItemView & ItemPool
843   for (ItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); )
844   {
845     unsigned int current = iter->first;
846
847     if( ! range.Within( current ) )
848     {
849       ReleaseActor(iter->first, iter->second);
850
851       mItemPool.erase( iter++ ); // erase invalidates the return value of post-increment; iter remains valid
852     }
853     else
854     {
855       ++iter;
856     }
857   }
858 }
859
860 void ItemView::AddActorsWithinRange( ItemRange range, const Vector3& layoutSize )
861 {
862   range.end = std::min(mItemFactory.GetNumberOfItems(), range.end);
863
864   // The order of addition depends on the scroll direction.
865   if (mRefreshOrderHint)
866   {
867     for (unsigned int itemId = range.begin; itemId < range.end; ++itemId)
868     {
869       AddNewActor( itemId, layoutSize );
870     }
871   }
872   else
873   {
874     for (unsigned int itemId = range.end; itemId > range.begin; --itemId)
875     {
876       AddNewActor( itemId-1, layoutSize );
877     }
878   }
879
880   // Total number of items may change dynamically.
881   // Always recalculate the domain size to reflect that.
882   CalculateDomainSize(Self().GetCurrentSize());
883 }
884
885 void ItemView::AddNewActor( unsigned int itemId, const Vector3& layoutSize )
886 {
887   mAddingItems = true;
888
889   if( mItemPool.end() == mItemPool.find( itemId ) )
890   {
891     Actor actor = mItemFactory.NewItem( itemId );
892
893     if( actor )
894     {
895       Item newItem( itemId, actor );
896
897       mItemPool.insert( newItem );
898
899       SetupActor( newItem, layoutSize );
900       Self().Add( actor );
901     }
902   }
903
904   mAddingItems = false;
905 }
906
907 void ItemView::SetupActor( Item item, const Vector3& layoutSize )
908 {
909   item.second.SetParentOrigin( mItemsParentOrigin );
910   item.second.SetAnchorPoint( mItemsAnchorPoint );
911
912   if( mActiveLayout )
913   {
914     Vector3 size;
915     mActiveLayout->GetItemSize( item.first, mActiveLayoutTargetSize, size );
916     item.second.SetSize( size.GetVectorXY() );
917
918     mActiveLayout->ApplyConstraints( item.second, item.first, layoutSize, Self() );
919   }
920 }
921
922 void ItemView::ReleaseActor( ItemId item, Actor actor )
923 {
924   Self().Remove( actor );
925   mItemFactory.ItemReleased(item, actor);
926 }
927
928 ItemRange ItemView::GetItemRange(ItemLayout& layout, const Vector3& layoutSize, float layoutPosition, bool reserveExtra)
929 {
930   unsigned int itemCount = mItemFactory.GetNumberOfItems();
931
932   ItemRange available(0u, itemCount);
933
934   ItemRange range = layout.GetItemsWithinArea( layoutPosition, layoutSize );
935
936   if (reserveExtra)
937   {
938     // Add the reserve items for scrolling
939     unsigned int extra = layout.GetReserveItemCount(layoutSize);
940     range.begin = (range.begin >= extra) ? (range.begin - extra) : 0u;
941     range.end += extra;
942   }
943
944   return range.Intersection(available);
945 }
946
947 void ItemView::OnChildAdd(Actor& child)
948 {
949   if(!mAddingItems)
950   {
951     // We don't want to do this downcast check for any item added by ItemView itself.
952     Dali::Toolkit::ScrollBar scrollBar = Dali::Toolkit::ScrollBar::DownCast(child);
953     if(scrollBar)
954     {
955       scrollBar.SetScrollPropertySource(Self(),
956                                         Toolkit::ItemView::Property::LAYOUT_POSITION,
957                                         Toolkit::Scrollable::Property::SCROLL_POSITION_MIN_Y,
958                                         Toolkit::Scrollable::Property::SCROLL_POSITION_MAX_Y,
959                                         Toolkit::ItemView::Property::SCROLL_CONTENT_SIZE);
960       scrollBar.ScrollPositionIntervalReachedSignal().Connect( this, &ItemView::OnScrollPositionChanged );
961     }
962   }
963 }
964
965 bool ItemView::OnTouchEvent(const TouchEvent& event)
966 {
967   // Ignore events with multiple-touch points
968   if (event.GetPointCount() != 1)
969   {
970     return false;
971   }
972
973   if (event.GetPoint(0).state == TouchPoint::Down)
974   {
975     // Cancel ongoing scrolling etc.
976     mGestureState = Gesture::Clear;
977
978     mScrollDistance = 0.0f;
979     mScrollSpeed = 0.0f;
980     Self().SetProperty(Toolkit::ItemView::Property::SCROLL_SPEED, mScrollSpeed);
981
982     mScrollOvershoot = 0.0f;
983     AnimateScrollOvershoot(0.0f);
984
985     if(mScrollAnimation)
986     {
987       mScrollCompletedSignal.Emit(GetCurrentScrollPosition());
988     }
989
990     RemoveAnimation(mScrollAnimation);
991   }
992
993   return true; // consume since we're potentially scrolling
994 }
995
996 bool ItemView::OnWheelEvent(const WheelEvent& event)
997 {
998   // Respond the wheel event to scroll
999   if (mActiveLayout)
1000   {
1001     Actor self = Self();
1002     const Vector3 layoutSize = Self().GetCurrentSize();
1003     float layoutPositionDelta = GetCurrentLayoutPosition(0) - (event.z * mWheelScrollDistanceStep * mActiveLayout->GetScrollSpeedFactor());
1004     float firstItemScrollPosition = ClampFirstItemPosition(layoutPositionDelta, layoutSize, *mActiveLayout);
1005
1006     self.SetProperty(Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1007
1008     mScrollStartedSignal.Emit(GetCurrentScrollPosition());
1009     mRefreshEnabled = true;
1010   }
1011
1012   if (mWheelEventFinishedTimer.IsRunning())
1013   {
1014     mWheelEventFinishedTimer.Stop();
1015   }
1016
1017   mWheelEventFinishedTimer.Start();
1018
1019   return true;
1020 }
1021
1022 bool ItemView::OnWheelEventFinished()
1023 {
1024   if (mActiveLayout)
1025   {
1026     RemoveAnimation(mScrollAnimation);
1027
1028     // No more wheel events coming. Do the anchoring if enabled.
1029     mScrollAnimation = DoAnchoring();
1030     if (mScrollAnimation)
1031     {
1032       mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
1033       mScrollAnimation.Play();
1034     }
1035     else
1036     {
1037       mScrollOvershoot = 0.0f;
1038       AnimateScrollOvershoot(0.0f);
1039
1040       mScrollCompletedSignal.Emit(GetCurrentScrollPosition());
1041     }
1042   }
1043
1044   return false;
1045 }
1046
1047 void ItemView::ReapplyAllConstraints()
1048 {
1049   Vector3 layoutSize = Self().GetCurrentSize();
1050
1051   for (ConstItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
1052   {
1053     unsigned int id = iter->first;
1054     Actor actor = iter->second;
1055
1056     actor.RemoveConstraints();
1057     mActiveLayout->ApplyConstraints(actor, id, layoutSize, Self());
1058   }
1059 }
1060
1061 void ItemView::OnItemsRemoved()
1062 {
1063   CalculateDomainSize(Self().GetCurrentSize());
1064
1065   // Adjust scroll-position after an item is removed
1066   if( mActiveLayout )
1067   {
1068     float firstItemScrollPosition = ClampFirstItemPosition(GetCurrentLayoutPosition(0), Self().GetCurrentSize(), *mActiveLayout);
1069     Self().SetProperty( Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1070   }
1071 }
1072
1073 float ItemView::ClampFirstItemPosition(float targetPosition, const Vector3& targetSize, ItemLayout& layout)
1074 {
1075   Actor self = Self();
1076   float minLayoutPosition = layout.GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), targetSize);
1077   float clamppedPosition = std::min(0.0f, std::max(minLayoutPosition, targetPosition));
1078   mScrollOvershoot = targetPosition - clamppedPosition;
1079   self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX, Vector2(0.0f, -minLayoutPosition));
1080
1081   return clamppedPosition;
1082 }
1083
1084 void ItemView::OnPan( const PanGesture& gesture )
1085 {
1086   Actor self = Self();
1087   const Vector3 layoutSize = Self().GetCurrentSize();
1088
1089   RemoveAnimation(mScrollAnimation);
1090
1091   // Short-circuit if there is no active layout
1092   if (!mActiveLayout)
1093   {
1094     mGestureState = Gesture::Clear;
1095     return;
1096   }
1097
1098   mGestureState = gesture.state;
1099
1100   switch (mGestureState)
1101   {
1102     case Gesture::Finished:
1103     {
1104       // Swipe Detection
1105       if (fabsf(mScrollDistance) > mMinimumSwipeDistance &&
1106           mScrollSpeed > mMinimumSwipeSpeed)
1107       {
1108         float direction = (mScrollDistance < 0.0f) ? -1.0f : 1.0f;
1109
1110         mRefreshOrderHint = true;
1111
1112         float currentLayoutPosition = GetCurrentLayoutPosition(0);
1113         float firstItemScrollPosition = ClampFirstItemPosition(currentLayoutPosition + mScrollSpeed * direction,
1114                                                                layoutSize,
1115                                                                *mActiveLayout);
1116
1117         if (mAnchoringEnabled)
1118         {
1119           firstItemScrollPosition = mActiveLayout->GetClosestAnchorPosition(firstItemScrollPosition);
1120         }
1121
1122         RemoveAnimation(mScrollAnimation);
1123
1124         float flickAnimationDuration = Clamp( mActiveLayout->GetItemFlickAnimationDuration() * std::max(1.0f, fabsf(firstItemScrollPosition - GetCurrentLayoutPosition(0)))
1125                                        , DEFAULT_MINIMUM_SWIPE_DURATION, DEFAULT_MAXIMUM_SWIPE_DURATION);
1126
1127         mScrollAnimation = Animation::New(flickAnimationDuration);
1128         mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION ), firstItemScrollPosition, AlphaFunction::EASE_OUT );
1129         mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::SCROLL_SPEED), 0.0f, AlphaFunction::EASE_OUT );
1130
1131         mIsFlicking = true;
1132         // Check whether it has already scrolled to the end
1133         if(fabs(currentLayoutPosition - firstItemScrollPosition) > Math::MACHINE_EPSILON_0)
1134         {
1135           AnimateScrollOvershoot(0.0f);
1136         }
1137       }
1138
1139       // Anchoring may be triggered when there was no swipe
1140       if (!mScrollAnimation)
1141       {
1142         mScrollAnimation = DoAnchoring();
1143       }
1144
1145       // Reset the overshoot if no scroll animation.
1146       if (!mScrollAnimation)
1147       {
1148         mScrollCompletedSignal.Emit(GetCurrentScrollPosition());
1149
1150         AnimateScrollOvershoot(0.0f, false);
1151       }
1152     }
1153     break;
1154
1155     case Gesture::Started: // Fall through
1156     {
1157       mTotalPanDisplacement = Vector2::ZERO;
1158       mScrollStartedSignal.Emit(GetCurrentScrollPosition());
1159       mRefreshEnabled = true;
1160     }
1161
1162     case Gesture::Continuing:
1163     {
1164       mScrollDistance = CalculateScrollDistance(gesture.displacement, *mActiveLayout);
1165       mScrollSpeed = Clamp((gesture.GetSpeed() * gesture.GetSpeed() * mActiveLayout->GetFlickSpeedFactor() * MILLISECONDS_PER_SECONDS), 0.0f, mActiveLayout->GetMaximumSwipeSpeed());
1166
1167       // Refresh order depends on the direction of the scroll; negative is towards the last item.
1168       mRefreshOrderHint = mScrollDistance < 0.0f;
1169
1170       float layoutPositionDelta = GetCurrentLayoutPosition(0) + (mScrollDistance * mActiveLayout->GetScrollSpeedFactor());
1171
1172       float firstItemScrollPosition = ClampFirstItemPosition(layoutPositionDelta, layoutSize, *mActiveLayout);
1173
1174       float currentOvershoot = self.GetProperty<float>(Toolkit::ItemView::Property::OVERSHOOT);
1175
1176       self.SetProperty(Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1177
1178       if( (firstItemScrollPosition >= 0.0f && currentOvershoot < 1.0f) || (firstItemScrollPosition >= mActiveLayout->GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), layoutSize) && currentOvershoot > -1.0f) )
1179       {
1180         mTotalPanDisplacement += gesture.displacement;
1181       }
1182
1183       mScrollOvershoot = CalculateScrollOvershoot();
1184       self.SetProperty( Toolkit::ItemView::Property::OVERSHOOT, mScrollOvershoot );
1185     }
1186     break;
1187
1188     case Gesture::Cancelled:
1189     {
1190       mScrollAnimation = DoAnchoring();
1191     }
1192     break;
1193
1194     default:
1195       break;
1196   }
1197
1198   if (mScrollAnimation)
1199   {
1200     mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
1201     mScrollAnimation.Play();
1202   }
1203 }
1204
1205 bool ItemView::OnAccessibilityPan(PanGesture gesture)
1206 {
1207   OnPan(gesture);
1208   return true;
1209 }
1210
1211 Actor ItemView::GetNextKeyboardFocusableActor(Actor actor, Toolkit::Control::KeyboardFocus::Direction direction, bool loopEnabled)
1212 {
1213   Actor nextFocusActor;
1214   if(mActiveLayout)
1215   {
1216     int nextItemID = 0;
1217     if(!actor || actor == this->Self())
1218     {
1219       nextFocusActor = GetItem(nextItemID);
1220     }
1221     else if(actor && actor.GetParent() == this->Self())
1222     {
1223       int itemID = GetItemId(actor);
1224       nextItemID = mActiveLayout->GetNextFocusItemID(itemID, mItemFactory.GetNumberOfItems(), direction, loopEnabled);
1225       nextFocusActor = GetItem(nextItemID);
1226       if(nextFocusActor == actor)
1227       {
1228         // need to pass NULL actor back to focus manager
1229         nextFocusActor.Reset();
1230         return nextFocusActor;
1231       }
1232     }
1233     float layoutPosition = mActiveLayout->GetClosestAnchorPosition( GetCurrentLayoutPosition(0) );
1234     Vector3 layoutSize = Self().GetCurrentSize();
1235     if(!nextFocusActor)
1236     {
1237       // likely the current item is not buffered, so not in our item pool, probably best to get first viewable item
1238       ItemRange viewableItems = mActiveLayout->GetItemsWithinArea(layoutPosition, layoutSize);
1239       nextItemID = viewableItems.begin;
1240       nextFocusActor = GetItem(nextItemID);
1241     }
1242   }
1243   return nextFocusActor;
1244 }
1245
1246 void ItemView::OnKeyboardFocusChangeCommitted(Actor commitedFocusableActor)
1247 {
1248   // only in this function if our chosen focus actor was actually used
1249   if(commitedFocusableActor)
1250   {
1251     int nextItemID = GetItemId(commitedFocusableActor);
1252     float layoutPosition = GetCurrentLayoutPosition(0);
1253     Vector3 layoutSize = Self().GetCurrentSize();
1254
1255     float scrollTo = mActiveLayout->GetClosestOnScreenLayoutPosition(nextItemID, layoutPosition, layoutSize);
1256     ScrollTo(Vector2(0.0f, scrollTo), DEFAULT_KEYBOARD_FOCUS_SCROLL_DURATION);
1257   }
1258 }
1259
1260 Animation ItemView::DoAnchoring()
1261 {
1262   Animation anchoringAnimation;
1263   Actor self = Self();
1264
1265   if (mActiveLayout && mAnchoringEnabled)
1266   {
1267     float anchorPosition = mActiveLayout->GetClosestAnchorPosition( GetCurrentLayoutPosition(0) );
1268
1269     anchoringAnimation = Animation::New(mAnchoringDuration);
1270     anchoringAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), anchorPosition, AlphaFunction::EASE_OUT );
1271     anchoringAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::SCROLL_SPEED), 0.0f, AlphaFunction::EASE_OUT );
1272     if(!mIsFlicking)
1273     {
1274       AnimateScrollOvershoot(0.0f);
1275     }
1276   }
1277
1278   return anchoringAnimation;
1279 }
1280
1281 void ItemView::OnScrollFinished(Animation& source)
1282 {
1283   Actor self = Self();
1284
1285   RemoveAnimation(mScrollAnimation); // mScrollAnimation is used to query whether we're scrolling
1286
1287   mScrollCompletedSignal.Emit(GetCurrentScrollPosition());
1288
1289   if(mIsFlicking && fabsf(mScrollOvershoot) > Math::MACHINE_EPSILON_1)
1290   {
1291     AnimateScrollOvershoot( mScrollOvershoot > 0.0f ? 1.0f : -1.0f, true);
1292   }
1293   else
1294   {
1295     // Reset the overshoot
1296     AnimateScrollOvershoot( 0.0f );
1297   }
1298   mIsFlicking = false;
1299
1300   mScrollOvershoot = 0.0f;
1301 }
1302
1303 void ItemView::OnLayoutActivationScrollFinished(Animation& source)
1304 {
1305   RemoveAnimation(mScrollAnimation);
1306   mRefreshEnabled = true;
1307   DoRefresh(GetCurrentLayoutPosition(0), true);
1308
1309   // Emit the layout activated signal
1310   mLayoutActivatedSignal.Emit();
1311 }
1312
1313 void ItemView::OnOvershootOnFinished(Animation& animation)
1314 {
1315   mAnimatingOvershootOn = false;
1316   mScrollOvershootAnimation.FinishedSignal().Disconnect(this, &ItemView::OnOvershootOnFinished);
1317   RemoveAnimation(mScrollOvershootAnimation);
1318   if(mAnimateOvershootOff)
1319   {
1320     AnimateScrollOvershoot(0.0f);
1321   }
1322 }
1323
1324 void ItemView::ScrollToItem(unsigned int itemId, float durationSeconds)
1325 {
1326   Actor self = Self();
1327   const Vector3 layoutSize = Self().GetCurrentSize();
1328   float firstItemScrollPosition = ClampFirstItemPosition(mActiveLayout->GetItemScrollToPosition(itemId), layoutSize, *mActiveLayout);
1329
1330   if(durationSeconds > 0.0f)
1331   {
1332     RemoveAnimation(mScrollAnimation);
1333     mScrollAnimation = Animation::New(durationSeconds);
1334     mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), firstItemScrollPosition, AlphaFunction::EASE_OUT );
1335     mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
1336     mScrollAnimation.Play();
1337   }
1338   else
1339   {
1340     self.SetProperty( Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1341     AnimateScrollOvershoot(0.0f);
1342   }
1343
1344   mScrollStartedSignal.Emit(GetCurrentScrollPosition());
1345   mRefreshEnabled = true;
1346 }
1347
1348 void ItemView::RemoveAnimation(Animation& animation)
1349 {
1350   if(animation)
1351   {
1352     // Cease animating, and reset handle.
1353     animation.Clear();
1354     animation.Reset();
1355   }
1356 }
1357
1358 void ItemView::CalculateDomainSize(const Vector3& layoutSize)
1359 {
1360   Actor self = Self();
1361
1362   Vector3 firstItemPosition(Vector3::ZERO);
1363   Vector3 lastItemPosition(Vector3::ZERO);
1364
1365   if(mActiveLayout)
1366   {
1367     firstItemPosition = mActiveLayout->GetItemPosition( 0,0,layoutSize );
1368
1369     float minLayoutPosition = mActiveLayout->GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), layoutSize);
1370     lastItemPosition = mActiveLayout->GetItemPosition( fabs(minLayoutPosition),fabs(minLayoutPosition),layoutSize );
1371
1372     float domainSize;
1373
1374     if(IsHorizontal(mActiveLayout->GetOrientation()))
1375     {
1376       domainSize = fabs(firstItemPosition.x - lastItemPosition.x);
1377     }
1378     else
1379     {
1380       domainSize = fabs(firstItemPosition.y - lastItemPosition.y);
1381     }
1382
1383     self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MIN, Vector2::ZERO);
1384     self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX, Vector2(0.0f, -minLayoutPosition));
1385
1386     self.SetProperty(Toolkit::ItemView::Property::SCROLL_CONTENT_SIZE, domainSize);
1387
1388     bool isLayoutScrollable = IsLayoutScrollable(layoutSize);
1389     self.SetProperty(Toolkit::Scrollable::Property::CAN_SCROLL_VERTICAL, isLayoutScrollable);
1390     self.SetProperty(Toolkit::Scrollable::Property::CAN_SCROLL_HORIZONTAL, false);
1391   }
1392 }
1393
1394 Vector2 ItemView::GetDomainSize() const
1395 {
1396   Actor self = Self();
1397
1398   float minScrollPosition = self.GetProperty<float>(Toolkit::Scrollable::Property::SCROLL_POSITION_MIN_Y);
1399   float maxScrollPosition = self.GetProperty<float>(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX_Y);
1400
1401   return Vector2(0.0f, fabs(GetScrollPosition(minScrollPosition, self.GetCurrentSize()) - GetScrollPosition(-maxScrollPosition, self.GetCurrentSize())));
1402 }
1403
1404 bool ItemView::IsLayoutScrollable(const Vector3& layoutSize)
1405 {
1406   Actor self = Self();
1407
1408   float currentLayoutPosition = ClampFirstItemPosition( GetCurrentLayoutPosition(0), layoutSize, *mActiveLayout );
1409   float forwardClampedPosition = ClampFirstItemPosition(currentLayoutPosition + 1.0, layoutSize, *mActiveLayout);
1410   float backwardClampedPosition = ClampFirstItemPosition(currentLayoutPosition - 1.0, layoutSize, *mActiveLayout);
1411
1412   return (fabs(forwardClampedPosition - backwardClampedPosition) > Math::MACHINE_EPSILON_0);
1413 }
1414
1415 float ItemView::GetScrollPosition(float layoutPosition, const Vector3& layoutSize) const
1416 {
1417   Vector3 firstItemPosition( mActiveLayout->GetItemPosition(0, layoutPosition, layoutSize ) );
1418   return IsHorizontal(mActiveLayout->GetOrientation()) ? firstItemPosition.x: firstItemPosition.y;
1419 }
1420
1421 Vector2 ItemView::GetCurrentScrollPosition() const
1422 {
1423   return Vector2(0.0f, GetScrollPosition(GetCurrentLayoutPosition(0), Self().GetCurrentSize()));
1424 }
1425
1426 void ItemView::AddOverlay(Actor actor)
1427 {
1428   Self().Add(actor);
1429 }
1430
1431 void ItemView::RemoveOverlay(Actor actor)
1432 {
1433   Self().Remove(actor);
1434 }
1435
1436 void ItemView::ScrollTo(const Vector2& position, float duration)
1437 {
1438   Actor self = Self();
1439   const Vector3 layoutSize = Self().GetCurrentSize();
1440
1441   float firstItemScrollPosition = ClampFirstItemPosition(position.y, layoutSize, *mActiveLayout);
1442
1443   if(duration > 0.0f)
1444   {
1445     RemoveAnimation(mScrollAnimation);
1446     mScrollAnimation = Animation::New(duration);
1447     mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), firstItemScrollPosition, AlphaFunction::EASE_OUT );
1448     mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
1449     mScrollAnimation.Play();
1450   }
1451   else
1452   {
1453     self.SetProperty( Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1454     AnimateScrollOvershoot(0.0f);
1455   }
1456
1457   mScrollStartedSignal.Emit(GetCurrentScrollPosition());
1458   mRefreshEnabled = true;
1459 }
1460
1461 void ItemView::SetOvershootEffectColor( const Vector4& color )
1462 {
1463   mOvershootEffectColor = color;
1464   if( mOvershootOverlay )
1465   {
1466     mOvershootOverlay.SetColor( color );
1467   }
1468 }
1469
1470 void ItemView::EnableScrollOvershoot( bool enable )
1471 {
1472   Actor self = Self();
1473   if( enable )
1474   {
1475     Property::Index effectOvershootPropertyIndex = Property::INVALID_INDEX;
1476     mOvershootOverlay = CreateBouncingEffectActor( effectOvershootPropertyIndex );
1477     mOvershootOverlay.SetColor(mOvershootEffectColor);
1478     mOvershootOverlay.SetParentOrigin(ParentOrigin::TOP_LEFT);
1479     mOvershootOverlay.SetAnchorPoint(AnchorPoint::TOP_LEFT);
1480     self.Add(mOvershootOverlay);
1481
1482     Constraint constraint = Constraint::New<Vector3>( mOvershootOverlay, Actor::Property::SIZE, OvershootOverlaySizeConstraint );
1483     constraint.AddSource( ParentSource( Toolkit::ItemView::Property::SCROLL_DIRECTION ) );
1484     constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_ORIENTATION ) );
1485     constraint.AddSource( ParentSource( Actor::Property::SIZE ) );
1486     constraint.Apply();
1487
1488     mOvershootOverlay.SetSize(OVERSHOOT_BOUNCE_ACTOR_DEFAULT_SIZE.width, OVERSHOOT_BOUNCE_ACTOR_DEFAULT_SIZE.height);
1489
1490     constraint = Constraint::New<Quaternion>( mOvershootOverlay, Actor::Property::ORIENTATION, OvershootOverlayRotationConstraint );
1491     constraint.AddSource( ParentSource( Toolkit::ItemView::Property::SCROLL_DIRECTION ) );
1492     constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_ORIENTATION ) );
1493     constraint.AddSource( ParentSource( Toolkit::ItemView::Property::OVERSHOOT ) );
1494     constraint.Apply();
1495
1496     constraint = Constraint::New<Vector3>( mOvershootOverlay, Actor::Property::POSITION, OvershootOverlayPositionConstraint );
1497     constraint.AddSource( ParentSource( Actor::Property::SIZE ) );
1498     constraint.AddSource( ParentSource( Toolkit::ItemView::Property::SCROLL_DIRECTION ) );
1499     constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_ORIENTATION ) );
1500     constraint.AddSource( ParentSource( Toolkit::ItemView::Property::OVERSHOOT ) );
1501     constraint.Apply();
1502
1503     constraint = Constraint::New<bool>( mOvershootOverlay, Actor::Property::VISIBLE, OvershootOverlayVisibilityConstraint );
1504     constraint.AddSource( ParentSource( Toolkit::Scrollable::Property::CAN_SCROLL_VERTICAL ) );
1505     constraint.Apply();
1506
1507     constraint = Constraint::New<float>( mOvershootOverlay, effectOvershootPropertyIndex, EqualToConstraint() );
1508     constraint.AddSource( ParentSource( Toolkit::ItemView::Property::OVERSHOOT ) );
1509     constraint.Apply();
1510   }
1511   else
1512   {
1513     if( mOvershootOverlay )
1514     {
1515       self.Remove(mOvershootOverlay);
1516       mOvershootOverlay.Reset();
1517     }
1518   }
1519 }
1520
1521 float ItemView::CalculateScrollOvershoot()
1522 {
1523   float overshoot = 0.0f;
1524
1525   if(mActiveLayout)
1526   {
1527     // The overshoot must be calculated from the accumulated pan gesture displacement
1528     // since the pan gesture starts.
1529     Actor self = Self();
1530     float scrollDistance = CalculateScrollDistance(mTotalPanDisplacement, *mActiveLayout) * mActiveLayout->GetScrollSpeedFactor();
1531     float positionDelta = GetCurrentLayoutPosition(0) + scrollDistance;
1532     float minLayoutPosition = mActiveLayout->GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), Self().GetCurrentSize());
1533     self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX, Vector2(0.0f, -minLayoutPosition));
1534     float clamppedPosition = std::min(0.0f, std::max(minLayoutPosition, positionDelta));
1535     overshoot = positionDelta - clamppedPosition;
1536   }
1537
1538   return overshoot > 0.0f ? std::min(overshoot, 1.0f) : std::max(overshoot, -1.0f);
1539 }
1540
1541 void ItemView::AnimateScrollOvershoot(float overshootAmount, bool animateBack)
1542 {
1543   bool animatingOn = fabsf(overshootAmount) > Math::MACHINE_EPSILON_1;
1544
1545   // make sure we animate back if needed
1546   mAnimateOvershootOff = animateBack || (!animatingOn && mAnimatingOvershootOn);
1547
1548   if( mAnimatingOvershootOn )
1549   {
1550     // animating on, do not allow animate off
1551     return;
1552   }
1553
1554   Actor self = Self();
1555
1556   if(mOvershootAnimationSpeed > Math::MACHINE_EPSILON_0)
1557   {
1558     float currentOvershoot = self.GetProperty<float>(Toolkit::ItemView::Property::OVERSHOOT);
1559     float duration = 0.0f;
1560
1561     if (mOvershootOverlay)
1562     {
1563       duration = mOvershootOverlay.GetCurrentSize().height * (animatingOn ? (1.0f - fabsf(currentOvershoot)) : fabsf(currentOvershoot)) / mOvershootAnimationSpeed;
1564     }
1565
1566     RemoveAnimation(mScrollOvershootAnimation);
1567     mScrollOvershootAnimation = Animation::New(duration);
1568     mScrollOvershootAnimation.FinishedSignal().Connect(this, &ItemView::OnOvershootOnFinished);
1569     mScrollOvershootAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::OVERSHOOT), overshootAmount, TimePeriod(0.0f, duration) );
1570     mScrollOvershootAnimation.Play();
1571
1572     mAnimatingOvershootOn = animatingOn;
1573   }
1574   else
1575   {
1576     self.SetProperty( Toolkit::ItemView::Property::OVERSHOOT, overshootAmount );
1577   }
1578 }
1579
1580 void ItemView::SetItemsParentOrigin( const Vector3& parentOrigin )
1581 {
1582   if( parentOrigin != mItemsParentOrigin )
1583   {
1584     mItemsParentOrigin = parentOrigin;
1585     for (ItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
1586     {
1587       iter->second.SetParentOrigin(parentOrigin);
1588     }
1589   }
1590 }
1591
1592 Vector3 ItemView::GetItemsParentOrigin() const
1593 {
1594   return mItemsParentOrigin;
1595 }
1596
1597 void ItemView::SetItemsAnchorPoint( const Vector3& anchorPoint )
1598 {
1599   if( anchorPoint != mItemsAnchorPoint )
1600   {
1601     mItemsAnchorPoint = anchorPoint;
1602     for (ItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
1603     {
1604       iter->second.SetAnchorPoint(anchorPoint);
1605     }
1606   }
1607 }
1608
1609 Vector3 ItemView::GetItemsAnchorPoint() const
1610 {
1611   return mItemsAnchorPoint;
1612 }
1613
1614 void ItemView::GetItemsRange(ItemRange& range)
1615 {
1616   if( !mItemPool.empty() )
1617   {
1618     range.begin = mItemPool.begin()->first;
1619     range.end = mItemPool.rbegin()->first + 1;
1620   }
1621   else
1622   {
1623     range.begin = 0;
1624     range.end = 0;
1625   }
1626 }
1627
1628 void ItemView::OnScrollPositionChanged( float position )
1629 {
1630   // Cancel scroll animation to prevent any fighting of setting the scroll position property.
1631   RemoveAnimation(mScrollAnimation);
1632
1633   // Refresh the cache immediately when the scroll position is changed.
1634   DoRefresh(position, false); // No need to cache extra items.
1635 }
1636
1637 bool ItemView::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
1638 {
1639   Dali::BaseHandle handle( object );
1640
1641   bool connected( true );
1642   Toolkit::ItemView itemView = Toolkit::ItemView::DownCast( handle );
1643
1644   if( 0 == strcmp( signalName.c_str(), LAYOUT_ACTIVATED_SIGNAL ) )
1645   {
1646     itemView.LayoutActivatedSignal().Connect( tracker, functor );
1647   }
1648   else
1649   {
1650     // signalName does not match any signal
1651     connected = false;
1652   }
1653
1654   return connected;
1655 }
1656
1657 } // namespace Internal
1658
1659 } // namespace Toolkit
1660
1661 } // namespace Dali