Merge "Added PropertyValue Array as a class" into tizen
[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(false),
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     mActiveLayout->GetItemSize( itemId, targetSize, size );
389     actor.SetSize( size.GetVectorXY() );
390
391     mActiveLayout->ApplyConstraints(actor, itemId, targetSize, Self() );
392   }
393
394   // Refresh the new layout
395   ItemRange range = GetItemRange(*mActiveLayout, targetSize, GetCurrentLayoutPosition(0), false/* don't reserve extra*/);
396   AddActorsWithinRange( range, targetSize );
397
398   // Scroll to an appropriate layout position
399
400   bool scrollAnimationNeeded(false);
401   float firstItemScrollPosition(0.0f);
402
403   float current = GetCurrentLayoutPosition(0);
404   float minimum = ClampFirstItemPosition(current, targetSize, *mActiveLayout);
405
406   if (current < minimum)
407   {
408     scrollAnimationNeeded = true;
409     firstItemScrollPosition = minimum;
410   }
411   else if (mAnchoringEnabled)
412   {
413     scrollAnimationNeeded = true;
414     firstItemScrollPosition = mActiveLayout->GetClosestAnchorPosition(current);
415   }
416
417   if (scrollAnimationNeeded)
418   {
419     RemoveAnimation(mScrollAnimation);
420     mScrollAnimation = Animation::New(durationSeconds);
421     mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), firstItemScrollPosition, AlphaFunction::EASE_OUT );
422     mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnLayoutActivationScrollFinished);
423     mScrollAnimation.Play();
424   }
425
426   AnimateScrollOvershoot(0.0f);
427   mScrollOvershoot = 0.0f;
428
429   Radian scrollDirection(mActiveLayout->GetScrollDirection());
430   self.SetProperty(Toolkit::ItemView::Property::SCROLL_DIRECTION, Vector2(sinf(scrollDirection), cosf(scrollDirection)));
431   self.SetProperty(Toolkit::ItemView::Property::LAYOUT_ORIENTATION, static_cast<int>(mActiveLayout->GetOrientation()));
432   self.SetProperty(Toolkit::ItemView::Property::SCROLL_SPEED, mScrollSpeed);
433
434   CalculateDomainSize(targetSize);
435 }
436
437 void ItemView::DeactivateCurrentLayout()
438 {
439   if (mActiveLayout)
440   {
441     for (ConstItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
442     {
443       Actor actor = iter->second;
444       actor.RemoveConstraints();
445     }
446
447     mActiveLayout = NULL;
448   }
449 }
450
451 void ItemView::OnRefreshNotification(PropertyNotification& source)
452 {
453   if(mRefreshEnabled || mScrollAnimation)
454   {
455     // Only refresh the cache during normal scrolling
456     DoRefresh(GetCurrentLayoutPosition(0), true);
457   }
458 }
459
460 void ItemView::Refresh()
461 {
462   for (ItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter )
463   {
464     ReleaseActor( iter->first, iter->second );
465   }
466   mItemPool.clear();
467
468   DoRefresh(GetCurrentLayoutPosition(0), true);
469 }
470
471 void ItemView::DoRefresh(float currentLayoutPosition, bool cacheExtra)
472 {
473   if (mActiveLayout)
474   {
475     ItemRange range = GetItemRange(*mActiveLayout, mActiveLayoutTargetSize, currentLayoutPosition, cacheExtra/*reserve extra*/);
476     RemoveActorsOutsideRange( range );
477     AddActorsWithinRange( range, Self().GetCurrentSize() );
478
479     mScrollUpdatedSignal.Emit( Vector2(0.0f, currentLayoutPosition) );
480   }
481 }
482
483 void ItemView::SetMinimumSwipeSpeed(float speed)
484 {
485   mMinimumSwipeSpeed = speed;
486 }
487
488 float ItemView::GetMinimumSwipeSpeed() const
489 {
490   return mMinimumSwipeSpeed;
491 }
492
493 void ItemView::SetMinimumSwipeDistance(float distance)
494 {
495   mMinimumSwipeDistance = distance;
496 }
497
498 float ItemView::GetMinimumSwipeDistance() const
499 {
500   return mMinimumSwipeDistance;
501 }
502
503 void ItemView::SetMouseWheelScrollDistanceStep(float step)
504 {
505   mMouseWheelScrollDistanceStep = step;
506 }
507
508 float ItemView::GetMouseWheelScrollDistanceStep() const
509 {
510   return mMouseWheelScrollDistanceStep;
511 }
512
513 void ItemView::SetAnchoring(bool enabled)
514 {
515   mAnchoringEnabled = enabled;
516 }
517
518 bool ItemView::GetAnchoring() const
519 {
520   return mAnchoringEnabled;
521 }
522
523 void ItemView::SetAnchoringDuration(float durationSeconds)
524 {
525   mAnchoringDuration = durationSeconds;
526 }
527
528 float ItemView::GetAnchoringDuration() const
529 {
530   return mAnchoringDuration;
531 }
532
533 void ItemView::SetRefreshInterval(float intervalLayoutPositions)
534 {
535   if( !Equals(mRefreshIntervalLayoutPositions, intervalLayoutPositions) )
536   {
537     mRefreshIntervalLayoutPositions = intervalLayoutPositions;
538
539     Actor self = Self();
540     if(mRefreshNotification)
541     {
542       self.RemovePropertyNotification(mRefreshNotification);
543     }
544     mRefreshNotification = self.AddPropertyNotification( Toolkit::ItemView::Property::LAYOUT_POSITION, StepCondition(mRefreshIntervalLayoutPositions, 0.0f) );
545     mRefreshNotification.NotifySignal().Connect( this, &ItemView::OnRefreshNotification );
546   }
547 }
548
549 float ItemView::GetRefreshInterval() const
550 {
551   return mRefreshIntervalLayoutPositions;
552 }
553
554 void ItemView::SetRefreshEnabled(bool enabled)
555 {
556   mRefreshEnabled = enabled;
557 }
558
559 Actor ItemView::GetItem(unsigned int itemId) const
560 {
561   Actor actor;
562
563   ConstItemPoolIter iter = mItemPool.find( itemId );
564   if( iter != mItemPool.end() )
565   {
566     actor = iter->second;
567   }
568
569   return actor;
570 }
571
572 unsigned int ItemView::GetItemId( Actor actor ) const
573 {
574   unsigned int itemId( 0 );
575
576   for ( ConstItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter )
577   {
578     if( iter->second == actor )
579     {
580       itemId = iter->first;
581       break;
582     }
583   }
584
585   return itemId;
586 }
587
588 void ItemView::InsertItem( Item newItem, float durationSeconds )
589 {
590   mAddingItems = true;
591   Vector3 layoutSize = Self().GetCurrentSize();
592
593   Actor displacedActor;
594   ItemPoolIter afterDisplacedIter = mItemPool.end();
595
596   ItemPoolIter foundIter = mItemPool.find( newItem.first );
597   if( mItemPool.end() != foundIter )
598   {
599     SetupActor( newItem, layoutSize );
600     Self().Add( newItem.second );
601
602     displacedActor = foundIter->second;
603     foundIter->second = newItem.second;
604
605     afterDisplacedIter = ++foundIter;
606   }
607   else
608   {
609     // Inserting before the existing item range?
610     ItemPoolIter iter = mItemPool.begin();
611     if( iter != mItemPool.end() &&
612         iter->first > newItem.first )
613     {
614       displacedActor = iter->second;
615       mItemPool.erase( iter++ ); // iter is still valid after the erase
616
617       afterDisplacedIter = iter;
618     }
619   }
620
621   if( displacedActor )
622   {
623     // Move the existing actors to make room
624     for( ItemPoolIter iter = afterDisplacedIter; mItemPool.end() != iter; ++iter )
625     {
626       Actor temp = iter->second;
627       iter->second = displacedActor;
628       displacedActor = temp;
629
630       iter->second.RemoveConstraints();
631       mActiveLayout->ApplyConstraints( iter->second, iter->first, layoutSize, Self() );
632     }
633
634     // Create last item
635     ItemPool::reverse_iterator lastIter = mItemPool.rbegin();
636     if ( lastIter != mItemPool.rend() )
637     {
638       ItemId lastId = lastIter->first;
639       Item lastItem( lastId + 1, displacedActor );
640       mItemPool.insert( lastItem );
641
642       lastItem.second.RemoveConstraints();
643       mActiveLayout->ApplyConstraints( lastItem.second, lastItem.first, layoutSize, Self() );
644     }
645   }
646
647   CalculateDomainSize( layoutSize );
648
649   mAddingItems = false;
650 }
651
652 void ItemView::InsertItems( const ItemContainer& newItems, float durationSeconds )
653 {
654   mAddingItems = true;
655   Vector3 layoutSize = Self().GetCurrentSize();
656
657   // Insert from lowest id to highest
658   std::set<Item> sortedItems;
659   for( ConstItemIter iter = newItems.begin(); newItems.end() != iter; ++iter )
660   {
661     sortedItems.insert( *iter );
662   }
663
664   for( std::set<Item>::iterator iter = sortedItems.begin(); sortedItems.end() != iter; ++iter )
665   {
666     Self().Add( iter->second );
667
668     ItemPoolIter foundIter = mItemPool.find( iter->first );
669     if( mItemPool.end() != foundIter )
670     {
671       Actor moveMe = foundIter->second;
672       foundIter->second = iter->second;
673
674       // Move the existing actors to make room
675       for( ItemPoolIter iter = ++foundIter; mItemPool.end() != iter; ++iter )
676       {
677         Actor temp = iter->second;
678         iter->second = moveMe;
679         moveMe = temp;
680       }
681
682       // Create last item
683       ItemId lastId = mItemPool.rbegin()->first;
684       Item lastItem( lastId + 1, moveMe );
685       mItemPool.insert( lastItem );
686     }
687     else
688     {
689       mItemPool.insert( *iter );
690     }
691   }
692
693   // Relayout everything
694   for (ItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
695   {
696     // If newly inserted
697     if( FindById( newItems, iter->first ) )
698     {
699       SetupActor( *iter, layoutSize );
700     }
701     else
702     {
703       iter->second.RemoveConstraints();
704       mActiveLayout->ApplyConstraints( iter->second, iter->first, layoutSize, Self() );
705     }
706   }
707
708   CalculateDomainSize( layoutSize );
709
710   mAddingItems = false;
711 }
712
713 void ItemView::RemoveItem( unsigned int itemId, float durationSeconds )
714 {
715   bool actorsReordered = RemoveActor( itemId );
716   if( actorsReordered )
717   {
718     ReapplyAllConstraints();
719
720     OnItemsRemoved();
721   }
722 }
723
724 void ItemView::RemoveItems( const ItemIdContainer& itemIds, float durationSeconds )
725 {
726   bool actorsReordered( false );
727
728   // Remove from highest id to lowest
729   set<ItemId> sortedItems;
730   for( ConstItemIdIter iter = itemIds.begin(); itemIds.end() != iter; ++iter )
731   {
732     sortedItems.insert( *iter );
733   }
734
735   for( set<ItemId>::reverse_iterator iter = sortedItems.rbegin(); sortedItems.rend() != iter; ++iter )
736   {
737     if( RemoveActor( *iter ) )
738     {
739       actorsReordered = true;
740     }
741   }
742
743   if( actorsReordered )
744   {
745     ReapplyAllConstraints();
746
747     OnItemsRemoved();
748   }
749 }
750
751 bool ItemView::RemoveActor(unsigned int itemId)
752 {
753   bool reordered( false );
754
755   ItemPoolIter removeIter = mItemPool.find( itemId );
756   if( removeIter != mItemPool.end() )
757   {
758     ReleaseActor(itemId, removeIter->second);
759   }
760   else
761   {
762     // Removing before the existing item range?
763     ItemPoolIter iter = mItemPool.begin();
764     if( iter != mItemPool.end() &&
765         iter->first > itemId )
766     {
767       // In order to decrement the first visible item ID
768       mItemPool.insert( Item(iter->first - 1, Actor()) );
769
770       removeIter = mItemPool.begin();
771     }
772   }
773
774   if( removeIter != mItemPool.end() )
775   {
776     reordered = true;
777
778     // Adjust the remaining item IDs, for example if item 2 is removed:
779     //   Initial actors:     After insert:
780     //     ID 1 - ActorA       ID 1 - ActorA
781     //     ID 2 - ActorB       ID 2 - ActorC (previously ID 3)
782     //     ID 3 - ActorC       ID 3 - ActorB (previously ID 4)
783     //     ID 4 - ActorD
784     for (ItemPoolIter iter = removeIter; iter != mItemPool.end(); ++iter)
785     {
786       if( iter->first < mItemPool.rbegin()->first )
787       {
788         iter->second = mItemPool[ iter->first + 1 ];
789       }
790       else
791       {
792         mItemPool.erase( iter );
793         break;
794       }
795     }
796   }
797
798   return reordered;
799 }
800
801 void ItemView::ReplaceItem( Item replacementItem, float durationSeconds )
802 {
803   mAddingItems = true;
804   Vector3 layoutSize = Self().GetCurrentSize();
805
806   SetupActor( replacementItem, layoutSize );
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( layoutSize );
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, const Vector3& layoutSize )
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, layoutSize );
863     }
864   }
865   else
866   {
867     for (unsigned int itemId = range.end; itemId > range.begin; --itemId)
868     {
869       AddNewActor( itemId-1, layoutSize );
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, const Vector3& layoutSize )
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, layoutSize );
893       Self().Add( actor );
894     }
895   }
896
897   mAddingItems = false;
898 }
899
900 void ItemView::SetupActor( Item item, const Vector3& layoutSize )
901 {
902   item.second.SetParentOrigin( mItemsParentOrigin );
903   item.second.SetAnchorPoint( mItemsAnchorPoint );
904
905   if( mActiveLayout )
906   {
907     Vector3 size;
908     mActiveLayout->GetItemSize( item.first, mActiveLayoutTargetSize, size );
909     item.second.SetSize( size.GetVectorXY() );
910
911     mActiveLayout->ApplyConstraints( item.second, item.first, layoutSize, Self() );
912   }
913 }
914
915 void ItemView::ReleaseActor( ItemId item, Actor actor )
916 {
917   Self().Remove( actor );
918   mItemFactory.ItemReleased(item, actor);
919 }
920
921 ItemRange ItemView::GetItemRange(ItemLayout& layout, const Vector3& layoutSize, float layoutPosition, bool reserveExtra)
922 {
923   unsigned int itemCount = mItemFactory.GetNumberOfItems();
924
925   ItemRange available(0u, itemCount);
926
927   ItemRange range = layout.GetItemsWithinArea( layoutPosition, layoutSize );
928
929   if (reserveExtra)
930   {
931     // Add the reserve items for scrolling
932     unsigned int extra = layout.GetReserveItemCount(layoutSize);
933     range.begin = (range.begin >= extra) ? (range.begin - extra) : 0u;
934     range.end += extra;
935   }
936
937   return range.Intersection(available);
938 }
939
940 void ItemView::OnChildAdd(Actor& child)
941 {
942   if(!mAddingItems)
943   {
944     // We don't want to do this downcast check for any item added by ItemView itself.
945     Dali::Toolkit::ScrollBar scrollBar = Dali::Toolkit::ScrollBar::DownCast(child);
946     if(scrollBar)
947     {
948       scrollBar.SetScrollPropertySource(Self(),
949                                         Toolkit::ItemView::Property::LAYOUT_POSITION,
950                                         Toolkit::Scrollable::Property::SCROLL_POSITION_MIN_Y,
951                                         Toolkit::Scrollable::Property::SCROLL_POSITION_MAX_Y,
952                                         Toolkit::ItemView::Property::SCROLL_CONTENT_SIZE);
953       scrollBar.ScrollPositionIntervalReachedSignal().Connect( this, &ItemView::OnScrollPositionChanged );
954     }
955   }
956 }
957
958 bool ItemView::OnTouchEvent(const TouchEvent& event)
959 {
960   // Ignore events with multiple-touch points
961   if (event.GetPointCount() != 1)
962   {
963     return false;
964   }
965
966   if (event.GetPoint(0).state == TouchPoint::Down)
967   {
968     // Cancel ongoing scrolling etc.
969     mGestureState = Gesture::Clear;
970
971     mScrollDistance = 0.0f;
972     mScrollSpeed = 0.0f;
973     Self().SetProperty(Toolkit::ItemView::Property::SCROLL_SPEED, mScrollSpeed);
974
975     mScrollOvershoot = 0.0f;
976     AnimateScrollOvershoot(0.0f);
977
978     if(mScrollAnimation)
979     {
980       mScrollCompletedSignal.Emit(GetCurrentScrollPosition());
981     }
982
983     RemoveAnimation(mScrollAnimation);
984   }
985
986   return true; // consume since we're potentially scrolling
987 }
988
989 bool ItemView::OnMouseWheelEvent(const MouseWheelEvent& event)
990 {
991   // Respond the mouse wheel event to scroll
992   if (mActiveLayout)
993   {
994     Actor self = Self();
995     const Vector3 layoutSize = Self().GetCurrentSize();
996     float layoutPositionDelta = GetCurrentLayoutPosition(0) - (event.z * mMouseWheelScrollDistanceStep * mActiveLayout->GetScrollSpeedFactor());
997     float firstItemScrollPosition = ClampFirstItemPosition(layoutPositionDelta, layoutSize, *mActiveLayout);
998
999     self.SetProperty(Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1000
1001     mScrollStartedSignal.Emit(GetCurrentScrollPosition());
1002     mRefreshEnabled = true;
1003   }
1004
1005   if (mMouseWheelEventFinishedTimer.IsRunning())
1006   {
1007     mMouseWheelEventFinishedTimer.Stop();
1008   }
1009
1010   mMouseWheelEventFinishedTimer.Start();
1011
1012   return true;
1013 }
1014
1015 bool ItemView::OnMouseWheelEventFinished()
1016 {
1017   if (mActiveLayout)
1018   {
1019     RemoveAnimation(mScrollAnimation);
1020
1021     // No more mouse wheel events coming. Do the anchoring if enabled.
1022     mScrollAnimation = DoAnchoring();
1023     if (mScrollAnimation)
1024     {
1025       mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
1026       mScrollAnimation.Play();
1027     }
1028     else
1029     {
1030       mScrollOvershoot = 0.0f;
1031       AnimateScrollOvershoot(0.0f);
1032
1033       mScrollCompletedSignal.Emit(GetCurrentScrollPosition());
1034     }
1035   }
1036
1037   return false;
1038 }
1039
1040 void ItemView::ReapplyAllConstraints()
1041 {
1042   Vector3 layoutSize = Self().GetCurrentSize();
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, layoutSize, 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