Use OVERLAY_2D for scroll overshoot etc.
[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   // Cancel scroll animation to prevent any fighting of setting the scroll position property by scroll bar during fast scroll.
461   if(!mRefreshEnabled && mScrollAnimation)
462   {
463     RemoveAnimation(mScrollAnimation);
464   }
465
466   // Only cache extra items when it is not a fast scroll
467   DoRefresh(GetCurrentLayoutPosition(0), mRefreshEnabled || mScrollAnimation);
468 }
469
470 void ItemView::Refresh()
471 {
472   for (ItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter )
473   {
474     ReleaseActor( iter->first, iter->second );
475   }
476   mItemPool.clear();
477
478   DoRefresh(GetCurrentLayoutPosition(0), true);
479 }
480
481 void ItemView::DoRefresh(float currentLayoutPosition, bool cacheExtra)
482 {
483   if (mActiveLayout)
484   {
485     ItemRange range = GetItemRange(*mActiveLayout, mActiveLayoutTargetSize, currentLayoutPosition, cacheExtra/*reserve extra*/);
486     RemoveActorsOutsideRange( range );
487     AddActorsWithinRange( range, Self().GetCurrentSize() );
488
489     mScrollUpdatedSignal.Emit( Vector2(0.0f, currentLayoutPosition) );
490   }
491 }
492
493 void ItemView::SetMinimumSwipeSpeed(float speed)
494 {
495   mMinimumSwipeSpeed = speed;
496 }
497
498 float ItemView::GetMinimumSwipeSpeed() const
499 {
500   return mMinimumSwipeSpeed;
501 }
502
503 void ItemView::SetMinimumSwipeDistance(float distance)
504 {
505   mMinimumSwipeDistance = distance;
506 }
507
508 float ItemView::GetMinimumSwipeDistance() const
509 {
510   return mMinimumSwipeDistance;
511 }
512
513 void ItemView::SetWheelScrollDistanceStep(float step)
514 {
515   mWheelScrollDistanceStep = step;
516 }
517
518 float ItemView::GetWheelScrollDistanceStep() const
519 {
520   return mWheelScrollDistanceStep;
521 }
522
523 void ItemView::SetAnchoring(bool enabled)
524 {
525   mAnchoringEnabled = enabled;
526 }
527
528 bool ItemView::GetAnchoring() const
529 {
530   return mAnchoringEnabled;
531 }
532
533 void ItemView::SetAnchoringDuration(float durationSeconds)
534 {
535   mAnchoringDuration = durationSeconds;
536 }
537
538 float ItemView::GetAnchoringDuration() const
539 {
540   return mAnchoringDuration;
541 }
542
543 void ItemView::SetRefreshInterval(float intervalLayoutPositions)
544 {
545   if( !Equals(mRefreshIntervalLayoutPositions, intervalLayoutPositions) )
546   {
547     mRefreshIntervalLayoutPositions = intervalLayoutPositions;
548
549     Actor self = Self();
550     if(mRefreshNotification)
551     {
552       self.RemovePropertyNotification(mRefreshNotification);
553     }
554     mRefreshNotification = self.AddPropertyNotification( Toolkit::ItemView::Property::LAYOUT_POSITION, StepCondition(mRefreshIntervalLayoutPositions, 0.0f) );
555     mRefreshNotification.NotifySignal().Connect( this, &ItemView::OnRefreshNotification );
556   }
557 }
558
559 float ItemView::GetRefreshInterval() const
560 {
561   return mRefreshIntervalLayoutPositions;
562 }
563
564 void ItemView::SetRefreshEnabled(bool enabled)
565 {
566   mRefreshEnabled = enabled;
567 }
568
569 Actor ItemView::GetItem(unsigned int itemId) const
570 {
571   Actor actor;
572
573   ConstItemPoolIter iter = mItemPool.find( itemId );
574   if( iter != mItemPool.end() )
575   {
576     actor = iter->second;
577   }
578
579   return actor;
580 }
581
582 unsigned int ItemView::GetItemId( Actor actor ) const
583 {
584   unsigned int itemId( 0 );
585
586   for ( ConstItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter )
587   {
588     if( iter->second == actor )
589     {
590       itemId = iter->first;
591       break;
592     }
593   }
594
595   return itemId;
596 }
597
598 void ItemView::InsertItem( Item newItem, float durationSeconds )
599 {
600   mAddingItems = true;
601   Vector3 layoutSize = Self().GetCurrentSize();
602
603   Actor displacedActor;
604   ItemPoolIter afterDisplacedIter = mItemPool.end();
605
606   ItemPoolIter foundIter = mItemPool.find( newItem.first );
607   if( mItemPool.end() != foundIter )
608   {
609     SetupActor( newItem, layoutSize );
610     Self().Add( newItem.second );
611
612     displacedActor = foundIter->second;
613     foundIter->second = newItem.second;
614
615     afterDisplacedIter = ++foundIter;
616   }
617   else
618   {
619     // Inserting before the existing item range?
620     ItemPoolIter iter = mItemPool.begin();
621     if( iter != mItemPool.end() &&
622         iter->first > newItem.first )
623     {
624       displacedActor = iter->second;
625       mItemPool.erase( iter++ ); // iter is still valid after the erase
626
627       afterDisplacedIter = iter;
628     }
629   }
630
631   if( displacedActor )
632   {
633     // Move the existing actors to make room
634     for( ItemPoolIter iter = afterDisplacedIter; mItemPool.end() != iter; ++iter )
635     {
636       Actor temp = iter->second;
637       iter->second = displacedActor;
638       displacedActor = temp;
639
640       iter->second.RemoveConstraints();
641       mActiveLayout->ApplyConstraints( iter->second, iter->first, layoutSize, Self() );
642     }
643
644     // Create last item
645     ItemPool::reverse_iterator lastIter = mItemPool.rbegin();
646     if ( lastIter != mItemPool.rend() )
647     {
648       ItemId lastId = lastIter->first;
649       Item lastItem( lastId + 1, displacedActor );
650       mItemPool.insert( lastItem );
651
652       lastItem.second.RemoveConstraints();
653       mActiveLayout->ApplyConstraints( lastItem.second, lastItem.first, layoutSize, Self() );
654     }
655   }
656
657   CalculateDomainSize( layoutSize );
658
659   mAddingItems = false;
660 }
661
662 void ItemView::InsertItems( const ItemContainer& newItems, float durationSeconds )
663 {
664   mAddingItems = true;
665   Vector3 layoutSize = Self().GetCurrentSize();
666
667   // Insert from lowest id to highest
668   std::set<Item> sortedItems;
669   for( ConstItemIter iter = newItems.begin(); newItems.end() != iter; ++iter )
670   {
671     sortedItems.insert( *iter );
672   }
673
674   for( std::set<Item>::iterator iter = sortedItems.begin(); sortedItems.end() != iter; ++iter )
675   {
676     Self().Add( iter->second );
677
678     ItemPoolIter foundIter = mItemPool.find( iter->first );
679     if( mItemPool.end() != foundIter )
680     {
681       Actor moveMe = foundIter->second;
682       foundIter->second = iter->second;
683
684       // Move the existing actors to make room
685       for( ItemPoolIter iter = ++foundIter; mItemPool.end() != iter; ++iter )
686       {
687         Actor temp = iter->second;
688         iter->second = moveMe;
689         moveMe = temp;
690       }
691
692       // Create last item
693       ItemId lastId = mItemPool.rbegin()->first;
694       Item lastItem( lastId + 1, moveMe );
695       mItemPool.insert( lastItem );
696     }
697     else
698     {
699       mItemPool.insert( *iter );
700     }
701   }
702
703   // Relayout everything
704   for (ItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
705   {
706     // If newly inserted
707     if( FindById( newItems, iter->first ) )
708     {
709       SetupActor( *iter, layoutSize );
710     }
711     else
712     {
713       iter->second.RemoveConstraints();
714       mActiveLayout->ApplyConstraints( iter->second, iter->first, layoutSize, Self() );
715     }
716   }
717
718   CalculateDomainSize( layoutSize );
719
720   mAddingItems = false;
721 }
722
723 void ItemView::RemoveItem( unsigned int itemId, float durationSeconds )
724 {
725   bool actorsReordered = RemoveActor( itemId );
726   if( actorsReordered )
727   {
728     ReapplyAllConstraints();
729
730     OnItemsRemoved();
731   }
732 }
733
734 void ItemView::RemoveItems( const ItemIdContainer& itemIds, float durationSeconds )
735 {
736   bool actorsReordered( false );
737
738   // Remove from highest id to lowest
739   set<ItemId> sortedItems;
740   for( ConstItemIdIter iter = itemIds.begin(); itemIds.end() != iter; ++iter )
741   {
742     sortedItems.insert( *iter );
743   }
744
745   for( set<ItemId>::reverse_iterator iter = sortedItems.rbegin(); sortedItems.rend() != iter; ++iter )
746   {
747     if( RemoveActor( *iter ) )
748     {
749       actorsReordered = true;
750     }
751   }
752
753   if( actorsReordered )
754   {
755     ReapplyAllConstraints();
756
757     OnItemsRemoved();
758   }
759 }
760
761 bool ItemView::RemoveActor(unsigned int itemId)
762 {
763   bool reordered( false );
764
765   ItemPoolIter removeIter = mItemPool.find( itemId );
766   if( removeIter != mItemPool.end() )
767   {
768     ReleaseActor(itemId, removeIter->second);
769   }
770   else
771   {
772     // Removing before the existing item range?
773     ItemPoolIter iter = mItemPool.begin();
774     if( iter != mItemPool.end() &&
775         iter->first > itemId )
776     {
777       // In order to decrement the first visible item ID
778       mItemPool.insert( Item(iter->first - 1, Actor()) );
779
780       removeIter = mItemPool.begin();
781     }
782   }
783
784   if( removeIter != mItemPool.end() )
785   {
786     reordered = true;
787
788     // Adjust the remaining item IDs, for example if item 2 is removed:
789     //   Initial actors:     After insert:
790     //     ID 1 - ActorA       ID 1 - ActorA
791     //     ID 2 - ActorB       ID 2 - ActorC (previously ID 3)
792     //     ID 3 - ActorC       ID 3 - ActorB (previously ID 4)
793     //     ID 4 - ActorD
794     for (ItemPoolIter iter = removeIter; iter != mItemPool.end(); ++iter)
795     {
796       if( iter->first < mItemPool.rbegin()->first )
797       {
798         iter->second = mItemPool[ iter->first + 1 ];
799       }
800       else
801       {
802         mItemPool.erase( iter );
803         break;
804       }
805     }
806   }
807
808   return reordered;
809 }
810
811 void ItemView::ReplaceItem( Item replacementItem, float durationSeconds )
812 {
813   mAddingItems = true;
814   Vector3 layoutSize = Self().GetCurrentSize();
815
816   SetupActor( replacementItem, layoutSize );
817   Self().Add( replacementItem.second );
818
819   const ItemPoolIter iter = mItemPool.find( replacementItem.first );
820   if( mItemPool.end() != iter )
821   {
822     ReleaseActor(iter->first, iter->second);
823     iter->second = replacementItem.second;
824   }
825   else
826   {
827     mItemPool.insert( replacementItem );
828   }
829
830   CalculateDomainSize( layoutSize );
831
832   mAddingItems = false;
833 }
834
835 void ItemView::ReplaceItems( const ItemContainer& replacementItems, float durationSeconds )
836 {
837   for( ConstItemIter iter = replacementItems.begin(); replacementItems.end() != iter; ++iter )
838   {
839     ReplaceItem( *iter, durationSeconds );
840   }
841 }
842
843 void ItemView::RemoveActorsOutsideRange( ItemRange range )
844 {
845   // Remove unwanted actors from the ItemView & ItemPool
846   for (ItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); )
847   {
848     unsigned int current = iter->first;
849
850     if( ! range.Within( current ) )
851     {
852       ReleaseActor(iter->first, iter->second);
853
854       mItemPool.erase( iter++ ); // erase invalidates the return value of post-increment; iter remains valid
855     }
856     else
857     {
858       ++iter;
859     }
860   }
861 }
862
863 void ItemView::AddActorsWithinRange( ItemRange range, const Vector3& layoutSize )
864 {
865   range.end = std::min(mItemFactory.GetNumberOfItems(), range.end);
866
867   // The order of addition depends on the scroll direction.
868   if (mRefreshOrderHint)
869   {
870     for (unsigned int itemId = range.begin; itemId < range.end; ++itemId)
871     {
872       AddNewActor( itemId, layoutSize );
873     }
874   }
875   else
876   {
877     for (unsigned int itemId = range.end; itemId > range.begin; --itemId)
878     {
879       AddNewActor( itemId-1, layoutSize );
880     }
881   }
882
883   // Total number of items may change dynamically.
884   // Always recalculate the domain size to reflect that.
885   CalculateDomainSize(Self().GetCurrentSize());
886 }
887
888 void ItemView::AddNewActor( unsigned int itemId, const Vector3& layoutSize )
889 {
890   mAddingItems = true;
891
892   if( mItemPool.end() == mItemPool.find( itemId ) )
893   {
894     Actor actor = mItemFactory.NewItem( itemId );
895
896     if( actor )
897     {
898       Item newItem( itemId, actor );
899
900       mItemPool.insert( newItem );
901
902       SetupActor( newItem, layoutSize );
903       Self().Add( actor );
904     }
905   }
906
907   mAddingItems = false;
908 }
909
910 void ItemView::SetupActor( Item item, const Vector3& layoutSize )
911 {
912   item.second.SetParentOrigin( mItemsParentOrigin );
913   item.second.SetAnchorPoint( mItemsAnchorPoint );
914
915   if( mActiveLayout )
916   {
917     Vector3 size;
918     mActiveLayout->GetItemSize( item.first, mActiveLayoutTargetSize, size );
919     item.second.SetSize( size.GetVectorXY() );
920
921     mActiveLayout->ApplyConstraints( item.second, item.first, layoutSize, Self() );
922   }
923 }
924
925 void ItemView::ReleaseActor( ItemId item, Actor actor )
926 {
927   Self().Remove( actor );
928   mItemFactory.ItemReleased(item, actor);
929 }
930
931 ItemRange ItemView::GetItemRange(ItemLayout& layout, const Vector3& layoutSize, float layoutPosition, bool reserveExtra)
932 {
933   unsigned int itemCount = mItemFactory.GetNumberOfItems();
934
935   ItemRange available(0u, itemCount);
936
937   ItemRange range = layout.GetItemsWithinArea( layoutPosition, layoutSize );
938
939   if (reserveExtra)
940   {
941     // Add the reserve items for scrolling
942     unsigned int extra = layout.GetReserveItemCount(layoutSize);
943     range.begin = (range.begin >= extra) ? (range.begin - extra) : 0u;
944     range.end += extra;
945   }
946
947   return range.Intersection(available);
948 }
949
950 void ItemView::OnChildAdd(Actor& child)
951 {
952   if(!mAddingItems)
953   {
954     // We don't want to do this downcast check for any item added by ItemView itself.
955     Dali::Toolkit::ScrollBar scrollBar = Dali::Toolkit::ScrollBar::DownCast(child);
956     if(scrollBar)
957     {
958       scrollBar.SetScrollPropertySource(Self(),
959                                         Toolkit::ItemView::Property::LAYOUT_POSITION,
960                                         Toolkit::Scrollable::Property::SCROLL_POSITION_MIN_Y,
961                                         Toolkit::Scrollable::Property::SCROLL_POSITION_MAX_Y,
962                                         Toolkit::ItemView::Property::SCROLL_CONTENT_SIZE);
963     }
964   }
965 }
966
967 bool ItemView::OnTouchEvent(const TouchEvent& event)
968 {
969   // Ignore events with multiple-touch points
970   if (event.GetPointCount() != 1)
971   {
972     return false;
973   }
974
975   if (event.GetPoint(0).state == TouchPoint::Down)
976   {
977     // Cancel ongoing scrolling etc.
978     mGestureState = Gesture::Clear;
979
980     mScrollDistance = 0.0f;
981     mScrollSpeed = 0.0f;
982     Self().SetProperty(Toolkit::ItemView::Property::SCROLL_SPEED, mScrollSpeed);
983
984     mScrollOvershoot = 0.0f;
985     AnimateScrollOvershoot(0.0f);
986
987     if(mScrollAnimation)
988     {
989       mScrollCompletedSignal.Emit(GetCurrentScrollPosition());
990     }
991
992     RemoveAnimation(mScrollAnimation);
993   }
994
995   return true; // consume since we're potentially scrolling
996 }
997
998 bool ItemView::OnWheelEvent(const WheelEvent& event)
999 {
1000   // Respond the wheel event to scroll
1001   if (mActiveLayout)
1002   {
1003     Actor self = Self();
1004     const Vector3 layoutSize = Self().GetCurrentSize();
1005     float layoutPositionDelta = GetCurrentLayoutPosition(0) - (event.z * mWheelScrollDistanceStep * mActiveLayout->GetScrollSpeedFactor());
1006     float firstItemScrollPosition = ClampFirstItemPosition(layoutPositionDelta, layoutSize, *mActiveLayout);
1007
1008     self.SetProperty(Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1009
1010     mScrollStartedSignal.Emit(GetCurrentScrollPosition());
1011     mRefreshEnabled = true;
1012   }
1013
1014   if (mWheelEventFinishedTimer.IsRunning())
1015   {
1016     mWheelEventFinishedTimer.Stop();
1017   }
1018
1019   mWheelEventFinishedTimer.Start();
1020
1021   return true;
1022 }
1023
1024 bool ItemView::OnWheelEventFinished()
1025 {
1026   if (mActiveLayout)
1027   {
1028     RemoveAnimation(mScrollAnimation);
1029
1030     // No more wheel events coming. Do the anchoring if enabled.
1031     mScrollAnimation = DoAnchoring();
1032     if (mScrollAnimation)
1033     {
1034       mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
1035       mScrollAnimation.Play();
1036     }
1037     else
1038     {
1039       mScrollOvershoot = 0.0f;
1040       AnimateScrollOvershoot(0.0f);
1041
1042       mScrollCompletedSignal.Emit(GetCurrentScrollPosition());
1043     }
1044   }
1045
1046   return false;
1047 }
1048
1049 void ItemView::ReapplyAllConstraints()
1050 {
1051   Vector3 layoutSize = Self().GetCurrentSize();
1052
1053   for (ConstItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
1054   {
1055     unsigned int id = iter->first;
1056     Actor actor = iter->second;
1057
1058     actor.RemoveConstraints();
1059     mActiveLayout->ApplyConstraints(actor, id, layoutSize, Self());
1060   }
1061 }
1062
1063 void ItemView::OnItemsRemoved()
1064 {
1065   CalculateDomainSize(Self().GetCurrentSize());
1066
1067   // Adjust scroll-position after an item is removed
1068   if( mActiveLayout )
1069   {
1070     float firstItemScrollPosition = ClampFirstItemPosition(GetCurrentLayoutPosition(0), Self().GetCurrentSize(), *mActiveLayout);
1071     Self().SetProperty( Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1072   }
1073 }
1074
1075 float ItemView::ClampFirstItemPosition(float targetPosition, const Vector3& targetSize, ItemLayout& layout)
1076 {
1077   Actor self = Self();
1078   float minLayoutPosition = layout.GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), targetSize);
1079   float clamppedPosition = std::min(0.0f, std::max(minLayoutPosition, targetPosition));
1080   mScrollOvershoot = targetPosition - clamppedPosition;
1081   self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX, Vector2(0.0f, -minLayoutPosition));
1082
1083   return clamppedPosition;
1084 }
1085
1086 void ItemView::OnPan( const PanGesture& gesture )
1087 {
1088   Actor self = Self();
1089   const Vector3 layoutSize = Self().GetCurrentSize();
1090
1091   RemoveAnimation(mScrollAnimation);
1092
1093   // Short-circuit if there is no active layout
1094   if (!mActiveLayout)
1095   {
1096     mGestureState = Gesture::Clear;
1097     return;
1098   }
1099
1100   mGestureState = gesture.state;
1101
1102   switch (mGestureState)
1103   {
1104     case Gesture::Finished:
1105     {
1106       // Swipe Detection
1107       if (fabsf(mScrollDistance) > mMinimumSwipeDistance &&
1108           mScrollSpeed > mMinimumSwipeSpeed)
1109       {
1110         float direction = (mScrollDistance < 0.0f) ? -1.0f : 1.0f;
1111
1112         mRefreshOrderHint = true;
1113
1114         float currentLayoutPosition = GetCurrentLayoutPosition(0);
1115         float firstItemScrollPosition = ClampFirstItemPosition(currentLayoutPosition + mScrollSpeed * direction,
1116                                                                layoutSize,
1117                                                                *mActiveLayout);
1118
1119         if (mAnchoringEnabled)
1120         {
1121           firstItemScrollPosition = mActiveLayout->GetClosestAnchorPosition(firstItemScrollPosition);
1122         }
1123
1124         RemoveAnimation(mScrollAnimation);
1125
1126         float flickAnimationDuration = Clamp( mActiveLayout->GetItemFlickAnimationDuration() * std::max(1.0f, fabsf(firstItemScrollPosition - GetCurrentLayoutPosition(0)))
1127                                        , DEFAULT_MINIMUM_SWIPE_DURATION, DEFAULT_MAXIMUM_SWIPE_DURATION);
1128
1129         mScrollAnimation = Animation::New(flickAnimationDuration);
1130         mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION ), firstItemScrollPosition, AlphaFunction::EASE_OUT );
1131         mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::SCROLL_SPEED), 0.0f, AlphaFunction::EASE_OUT );
1132
1133         mIsFlicking = true;
1134         // Check whether it has already scrolled to the end
1135         if(fabs(currentLayoutPosition - firstItemScrollPosition) > Math::MACHINE_EPSILON_0)
1136         {
1137           AnimateScrollOvershoot(0.0f);
1138         }
1139       }
1140
1141       // Anchoring may be triggered when there was no swipe
1142       if (!mScrollAnimation)
1143       {
1144         mScrollAnimation = DoAnchoring();
1145       }
1146
1147       // Reset the overshoot if no scroll animation.
1148       if (!mScrollAnimation)
1149       {
1150         mScrollCompletedSignal.Emit(GetCurrentScrollPosition());
1151
1152         AnimateScrollOvershoot(0.0f, false);
1153       }
1154     }
1155     break;
1156
1157     case Gesture::Started: // Fall through
1158     {
1159       mTotalPanDisplacement = Vector2::ZERO;
1160       mScrollStartedSignal.Emit(GetCurrentScrollPosition());
1161       mRefreshEnabled = true;
1162     }
1163
1164     case Gesture::Continuing:
1165     {
1166       mScrollDistance = CalculateScrollDistance(gesture.displacement, *mActiveLayout);
1167       mScrollSpeed = Clamp((gesture.GetSpeed() * gesture.GetSpeed() * mActiveLayout->GetFlickSpeedFactor() * MILLISECONDS_PER_SECONDS), 0.0f, mActiveLayout->GetMaximumSwipeSpeed());
1168
1169       // Refresh order depends on the direction of the scroll; negative is towards the last item.
1170       mRefreshOrderHint = mScrollDistance < 0.0f;
1171
1172       float layoutPositionDelta = GetCurrentLayoutPosition(0) + (mScrollDistance * mActiveLayout->GetScrollSpeedFactor());
1173
1174       float firstItemScrollPosition = ClampFirstItemPosition(layoutPositionDelta, layoutSize, *mActiveLayout);
1175
1176       float currentOvershoot = self.GetProperty<float>(Toolkit::ItemView::Property::OVERSHOOT);
1177
1178       self.SetProperty(Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1179
1180       if( (firstItemScrollPosition >= 0.0f && currentOvershoot < 1.0f) || (firstItemScrollPosition >= mActiveLayout->GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), layoutSize) && currentOvershoot > -1.0f) )
1181       {
1182         mTotalPanDisplacement += gesture.displacement;
1183       }
1184
1185       mScrollOvershoot = CalculateScrollOvershoot();
1186       self.SetProperty( Toolkit::ItemView::Property::OVERSHOOT, mScrollOvershoot );
1187     }
1188     break;
1189
1190     case Gesture::Cancelled:
1191     {
1192       mScrollAnimation = DoAnchoring();
1193     }
1194     break;
1195
1196     default:
1197       break;
1198   }
1199
1200   if (mScrollAnimation)
1201   {
1202     mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
1203     mScrollAnimation.Play();
1204   }
1205 }
1206
1207 bool ItemView::OnAccessibilityPan(PanGesture gesture)
1208 {
1209   OnPan(gesture);
1210   return true;
1211 }
1212
1213 Actor ItemView::GetNextKeyboardFocusableActor(Actor actor, Toolkit::Control::KeyboardFocus::Direction direction, bool loopEnabled)
1214 {
1215   Actor nextFocusActor;
1216   if(mActiveLayout)
1217   {
1218     int nextItemID = 0;
1219     if(!actor || actor == this->Self())
1220     {
1221       nextFocusActor = GetItem(nextItemID);
1222     }
1223     else if(actor && actor.GetParent() == this->Self())
1224     {
1225       int itemID = GetItemId(actor);
1226       nextItemID = mActiveLayout->GetNextFocusItemID(itemID, mItemFactory.GetNumberOfItems(), direction, loopEnabled);
1227       nextFocusActor = GetItem(nextItemID);
1228       if(nextFocusActor == actor)
1229       {
1230         // need to pass NULL actor back to focus manager
1231         nextFocusActor.Reset();
1232         return nextFocusActor;
1233       }
1234     }
1235     float layoutPosition = mActiveLayout->GetClosestAnchorPosition( GetCurrentLayoutPosition(0) );
1236     Vector3 layoutSize = Self().GetCurrentSize();
1237     if(!nextFocusActor)
1238     {
1239       // likely the current item is not buffered, so not in our item pool, probably best to get first viewable item
1240       ItemRange viewableItems = mActiveLayout->GetItemsWithinArea(layoutPosition, layoutSize);
1241       nextItemID = viewableItems.begin;
1242       nextFocusActor = GetItem(nextItemID);
1243     }
1244   }
1245   return nextFocusActor;
1246 }
1247
1248 void ItemView::OnKeyboardFocusChangeCommitted(Actor commitedFocusableActor)
1249 {
1250   // only in this function if our chosen focus actor was actually used
1251   if(commitedFocusableActor)
1252   {
1253     int nextItemID = GetItemId(commitedFocusableActor);
1254     float layoutPosition = GetCurrentLayoutPosition(0);
1255     Vector3 layoutSize = Self().GetCurrentSize();
1256
1257     float scrollTo = mActiveLayout->GetClosestOnScreenLayoutPosition(nextItemID, layoutPosition, layoutSize);
1258     ScrollTo(Vector2(0.0f, scrollTo), DEFAULT_KEYBOARD_FOCUS_SCROLL_DURATION);
1259   }
1260 }
1261
1262 Animation ItemView::DoAnchoring()
1263 {
1264   Animation anchoringAnimation;
1265   Actor self = Self();
1266
1267   if (mActiveLayout && mAnchoringEnabled)
1268   {
1269     float anchorPosition = mActiveLayout->GetClosestAnchorPosition( GetCurrentLayoutPosition(0) );
1270
1271     anchoringAnimation = Animation::New(mAnchoringDuration);
1272     anchoringAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), anchorPosition, AlphaFunction::EASE_OUT );
1273     anchoringAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::SCROLL_SPEED), 0.0f, AlphaFunction::EASE_OUT );
1274     if(!mIsFlicking)
1275     {
1276       AnimateScrollOvershoot(0.0f);
1277     }
1278   }
1279
1280   return anchoringAnimation;
1281 }
1282
1283 void ItemView::OnScrollFinished(Animation& source)
1284 {
1285   Actor self = Self();
1286
1287   RemoveAnimation(mScrollAnimation); // mScrollAnimation is used to query whether we're scrolling
1288
1289   mScrollCompletedSignal.Emit(GetCurrentScrollPosition());
1290
1291   if(mIsFlicking && fabsf(mScrollOvershoot) > Math::MACHINE_EPSILON_1)
1292   {
1293     AnimateScrollOvershoot( mScrollOvershoot > 0.0f ? 1.0f : -1.0f, true);
1294   }
1295   else
1296   {
1297     // Reset the overshoot
1298     AnimateScrollOvershoot( 0.0f );
1299   }
1300   mIsFlicking = false;
1301
1302   mScrollOvershoot = 0.0f;
1303 }
1304
1305 void ItemView::OnLayoutActivationScrollFinished(Animation& source)
1306 {
1307   RemoveAnimation(mScrollAnimation);
1308   mRefreshEnabled = true;
1309   DoRefresh(GetCurrentLayoutPosition(0), true);
1310
1311   // Emit the layout activated signal
1312   mLayoutActivatedSignal.Emit();
1313 }
1314
1315 void ItemView::OnOvershootOnFinished(Animation& animation)
1316 {
1317   mAnimatingOvershootOn = false;
1318   mScrollOvershootAnimation.FinishedSignal().Disconnect(this, &ItemView::OnOvershootOnFinished);
1319   RemoveAnimation(mScrollOvershootAnimation);
1320   if(mAnimateOvershootOff)
1321   {
1322     AnimateScrollOvershoot(0.0f);
1323   }
1324 }
1325
1326 void ItemView::ScrollToItem(unsigned int itemId, float durationSeconds)
1327 {
1328   Actor self = Self();
1329   const Vector3 layoutSize = Self().GetCurrentSize();
1330   float firstItemScrollPosition = ClampFirstItemPosition(mActiveLayout->GetItemScrollToPosition(itemId), layoutSize, *mActiveLayout);
1331
1332   if(durationSeconds > 0.0f)
1333   {
1334     RemoveAnimation(mScrollAnimation);
1335     mScrollAnimation = Animation::New(durationSeconds);
1336     mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), firstItemScrollPosition, AlphaFunction::EASE_OUT );
1337     mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
1338     mScrollAnimation.Play();
1339   }
1340   else
1341   {
1342     self.SetProperty( Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1343     AnimateScrollOvershoot(0.0f);
1344   }
1345
1346   mScrollStartedSignal.Emit(GetCurrentScrollPosition());
1347   mRefreshEnabled = true;
1348 }
1349
1350 void ItemView::RemoveAnimation(Animation& animation)
1351 {
1352   if(animation)
1353   {
1354     // Cease animating, and reset handle.
1355     animation.Clear();
1356     animation.Reset();
1357   }
1358 }
1359
1360 void ItemView::CalculateDomainSize(const Vector3& layoutSize)
1361 {
1362   Actor self = Self();
1363
1364   Vector3 firstItemPosition(Vector3::ZERO);
1365   Vector3 lastItemPosition(Vector3::ZERO);
1366
1367   if(mActiveLayout)
1368   {
1369     firstItemPosition = mActiveLayout->GetItemPosition( 0,0,layoutSize );
1370
1371     float minLayoutPosition = mActiveLayout->GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), layoutSize);
1372     lastItemPosition = mActiveLayout->GetItemPosition( fabs(minLayoutPosition),fabs(minLayoutPosition),layoutSize );
1373
1374     float domainSize;
1375
1376     if(IsHorizontal(mActiveLayout->GetOrientation()))
1377     {
1378       domainSize = fabs(firstItemPosition.x - lastItemPosition.x);
1379     }
1380     else
1381     {
1382       domainSize = fabs(firstItemPosition.y - lastItemPosition.y);
1383     }
1384
1385     self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MIN, Vector2::ZERO);
1386     self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX, Vector2(0.0f, -minLayoutPosition));
1387
1388     self.SetProperty(Toolkit::ItemView::Property::SCROLL_CONTENT_SIZE, domainSize);
1389
1390     bool isLayoutScrollable = IsLayoutScrollable(layoutSize);
1391     self.SetProperty(Toolkit::Scrollable::Property::CAN_SCROLL_VERTICAL, isLayoutScrollable);
1392     self.SetProperty(Toolkit::Scrollable::Property::CAN_SCROLL_HORIZONTAL, false);
1393   }
1394 }
1395
1396 Vector2 ItemView::GetDomainSize() const
1397 {
1398   Actor self = Self();
1399
1400   float minScrollPosition = self.GetProperty<float>(Toolkit::Scrollable::Property::SCROLL_POSITION_MIN_Y);
1401   float maxScrollPosition = self.GetProperty<float>(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX_Y);
1402
1403   return Vector2(0.0f, fabs(GetScrollPosition(minScrollPosition, self.GetCurrentSize()) - GetScrollPosition(-maxScrollPosition, self.GetCurrentSize())));
1404 }
1405
1406 bool ItemView::IsLayoutScrollable(const Vector3& layoutSize)
1407 {
1408   Actor self = Self();
1409
1410   float currentLayoutPosition = ClampFirstItemPosition( GetCurrentLayoutPosition(0), layoutSize, *mActiveLayout );
1411   float forwardClampedPosition = ClampFirstItemPosition(currentLayoutPosition + 1.0, layoutSize, *mActiveLayout);
1412   float backwardClampedPosition = ClampFirstItemPosition(currentLayoutPosition - 1.0, layoutSize, *mActiveLayout);
1413
1414   return (fabs(forwardClampedPosition - backwardClampedPosition) > Math::MACHINE_EPSILON_0);
1415 }
1416
1417 float ItemView::GetScrollPosition(float layoutPosition, const Vector3& layoutSize) const
1418 {
1419   Vector3 firstItemPosition( mActiveLayout->GetItemPosition(0, layoutPosition, layoutSize ) );
1420   return IsHorizontal(mActiveLayout->GetOrientation()) ? firstItemPosition.x: firstItemPosition.y;
1421 }
1422
1423 Vector2 ItemView::GetCurrentScrollPosition() const
1424 {
1425   return Vector2(0.0f, GetScrollPosition(GetCurrentLayoutPosition(0), Self().GetCurrentSize()));
1426 }
1427
1428 void ItemView::AddOverlay(Actor actor)
1429 {
1430   actor.SetDrawMode( DrawMode::OVERLAY_2D );
1431   Self().Add(actor);
1432 }
1433
1434 void ItemView::RemoveOverlay(Actor actor)
1435 {
1436   Self().Remove(actor);
1437 }
1438
1439 void ItemView::ScrollTo(const Vector2& position, float duration)
1440 {
1441   Actor self = Self();
1442   const Vector3 layoutSize = Self().GetCurrentSize();
1443
1444   float firstItemScrollPosition = ClampFirstItemPosition(position.y, layoutSize, *mActiveLayout);
1445
1446   if(duration > 0.0f)
1447   {
1448     RemoveAnimation(mScrollAnimation);
1449     mScrollAnimation = Animation::New(duration);
1450     mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), firstItemScrollPosition, AlphaFunction::EASE_OUT );
1451     mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
1452     mScrollAnimation.Play();
1453   }
1454   else
1455   {
1456     self.SetProperty( Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1457     AnimateScrollOvershoot(0.0f);
1458   }
1459
1460   mScrollStartedSignal.Emit(GetCurrentScrollPosition());
1461   mRefreshEnabled = true;
1462 }
1463
1464 void ItemView::SetOvershootEffectColor( const Vector4& color )
1465 {
1466   mOvershootEffectColor = color;
1467   if( mOvershootOverlay )
1468   {
1469     mOvershootOverlay.SetColor( color );
1470   }
1471 }
1472
1473 void ItemView::EnableScrollOvershoot( bool enable )
1474 {
1475   Actor self = Self();
1476   if( enable )
1477   {
1478     Property::Index effectOvershootPropertyIndex = Property::INVALID_INDEX;
1479     mOvershootOverlay = CreateBouncingEffectActor( effectOvershootPropertyIndex );
1480     mOvershootOverlay.SetColor(mOvershootEffectColor);
1481     mOvershootOverlay.SetParentOrigin(ParentOrigin::TOP_LEFT);
1482     mOvershootOverlay.SetAnchorPoint(AnchorPoint::TOP_LEFT);
1483     mOvershootOverlay.SetDrawMode( DrawMode::OVERLAY_2D );
1484     self.Add(mOvershootOverlay);
1485
1486     Constraint constraint = Constraint::New<Vector3>( mOvershootOverlay, Actor::Property::SIZE, OvershootOverlaySizeConstraint );
1487     constraint.AddSource( ParentSource( Toolkit::ItemView::Property::SCROLL_DIRECTION ) );
1488     constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_ORIENTATION ) );
1489     constraint.AddSource( ParentSource( Actor::Property::SIZE ) );
1490     constraint.Apply();
1491
1492     mOvershootOverlay.SetSize(OVERSHOOT_BOUNCE_ACTOR_DEFAULT_SIZE.width, OVERSHOOT_BOUNCE_ACTOR_DEFAULT_SIZE.height);
1493
1494     constraint = Constraint::New<Quaternion>( mOvershootOverlay, Actor::Property::ORIENTATION, OvershootOverlayRotationConstraint );
1495     constraint.AddSource( ParentSource( Toolkit::ItemView::Property::SCROLL_DIRECTION ) );
1496     constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_ORIENTATION ) );
1497     constraint.AddSource( ParentSource( Toolkit::ItemView::Property::OVERSHOOT ) );
1498     constraint.Apply();
1499
1500     constraint = Constraint::New<Vector3>( mOvershootOverlay, Actor::Property::POSITION, OvershootOverlayPositionConstraint );
1501     constraint.AddSource( ParentSource( Actor::Property::SIZE ) );
1502     constraint.AddSource( ParentSource( Toolkit::ItemView::Property::SCROLL_DIRECTION ) );
1503     constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_ORIENTATION ) );
1504     constraint.AddSource( ParentSource( Toolkit::ItemView::Property::OVERSHOOT ) );
1505     constraint.Apply();
1506
1507     constraint = Constraint::New<bool>( mOvershootOverlay, Actor::Property::VISIBLE, OvershootOverlayVisibilityConstraint );
1508     constraint.AddSource( ParentSource( Toolkit::Scrollable::Property::CAN_SCROLL_VERTICAL ) );
1509     constraint.Apply();
1510
1511     constraint = Constraint::New<float>( mOvershootOverlay, effectOvershootPropertyIndex, EqualToConstraint() );
1512     constraint.AddSource( ParentSource( Toolkit::ItemView::Property::OVERSHOOT ) );
1513     constraint.Apply();
1514   }
1515   else
1516   {
1517     if( mOvershootOverlay )
1518     {
1519       self.Remove(mOvershootOverlay);
1520       mOvershootOverlay.Reset();
1521     }
1522   }
1523 }
1524
1525 float ItemView::CalculateScrollOvershoot()
1526 {
1527   float overshoot = 0.0f;
1528
1529   if(mActiveLayout)
1530   {
1531     // The overshoot must be calculated from the accumulated pan gesture displacement
1532     // since the pan gesture starts.
1533     Actor self = Self();
1534     float scrollDistance = CalculateScrollDistance(mTotalPanDisplacement, *mActiveLayout) * mActiveLayout->GetScrollSpeedFactor();
1535     float positionDelta = GetCurrentLayoutPosition(0) + scrollDistance;
1536     float minLayoutPosition = mActiveLayout->GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), Self().GetCurrentSize());
1537     self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX, Vector2(0.0f, -minLayoutPosition));
1538     float clamppedPosition = std::min(0.0f, std::max(minLayoutPosition, positionDelta));
1539     overshoot = positionDelta - clamppedPosition;
1540   }
1541
1542   return overshoot > 0.0f ? std::min(overshoot, 1.0f) : std::max(overshoot, -1.0f);
1543 }
1544
1545 void ItemView::AnimateScrollOvershoot(float overshootAmount, bool animateBack)
1546 {
1547   bool animatingOn = fabsf(overshootAmount) > Math::MACHINE_EPSILON_1;
1548
1549   // make sure we animate back if needed
1550   mAnimateOvershootOff = animateBack || (!animatingOn && mAnimatingOvershootOn);
1551
1552   if( mAnimatingOvershootOn )
1553   {
1554     // animating on, do not allow animate off
1555     return;
1556   }
1557
1558   Actor self = Self();
1559
1560   if(mOvershootAnimationSpeed > Math::MACHINE_EPSILON_0)
1561   {
1562     float currentOvershoot = self.GetProperty<float>(Toolkit::ItemView::Property::OVERSHOOT);
1563     float duration = 0.0f;
1564
1565     if (mOvershootOverlay)
1566     {
1567       duration = mOvershootOverlay.GetCurrentSize().height * (animatingOn ? (1.0f - fabsf(currentOvershoot)) : fabsf(currentOvershoot)) / mOvershootAnimationSpeed;
1568     }
1569
1570     RemoveAnimation(mScrollOvershootAnimation);
1571     mScrollOvershootAnimation = Animation::New(duration);
1572     mScrollOvershootAnimation.FinishedSignal().Connect(this, &ItemView::OnOvershootOnFinished);
1573     mScrollOvershootAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::OVERSHOOT), overshootAmount, TimePeriod(0.0f, duration) );
1574     mScrollOvershootAnimation.Play();
1575
1576     mAnimatingOvershootOn = animatingOn;
1577   }
1578   else
1579   {
1580     self.SetProperty( Toolkit::ItemView::Property::OVERSHOOT, overshootAmount );
1581   }
1582 }
1583
1584 void ItemView::SetItemsParentOrigin( const Vector3& parentOrigin )
1585 {
1586   if( parentOrigin != mItemsParentOrigin )
1587   {
1588     mItemsParentOrigin = parentOrigin;
1589     for (ItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
1590     {
1591       iter->second.SetParentOrigin(parentOrigin);
1592     }
1593   }
1594 }
1595
1596 Vector3 ItemView::GetItemsParentOrigin() const
1597 {
1598   return mItemsParentOrigin;
1599 }
1600
1601 void ItemView::SetItemsAnchorPoint( const Vector3& anchorPoint )
1602 {
1603   if( anchorPoint != mItemsAnchorPoint )
1604   {
1605     mItemsAnchorPoint = anchorPoint;
1606     for (ItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
1607     {
1608       iter->second.SetAnchorPoint(anchorPoint);
1609     }
1610   }
1611 }
1612
1613 Vector3 ItemView::GetItemsAnchorPoint() const
1614 {
1615   return mItemsAnchorPoint;
1616 }
1617
1618 void ItemView::GetItemsRange(ItemRange& range)
1619 {
1620   if( !mItemPool.empty() )
1621   {
1622     range.begin = mItemPool.begin()->first;
1623     range.end = mItemPool.rbegin()->first + 1;
1624   }
1625   else
1626   {
1627     range.begin = 0;
1628     range.end = 0;
1629   }
1630 }
1631
1632 bool ItemView::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
1633 {
1634   Dali::BaseHandle handle( object );
1635
1636   bool connected( true );
1637   Toolkit::ItemView itemView = Toolkit::ItemView::DownCast( handle );
1638
1639   if( 0 == strcmp( signalName.c_str(), LAYOUT_ACTIVATED_SIGNAL ) )
1640   {
1641     itemView.LayoutActivatedSignal().Connect( tracker, functor );
1642   }
1643   else
1644   {
1645     // signalName does not match any signal
1646     connected = false;
1647   }
1648
1649   return connected;
1650 }
1651
1652 } // namespace Internal
1653
1654 } // namespace Toolkit
1655
1656 } // namespace Dali