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