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