c8bb12fc205ea4ab16fa327717a1f1b46320ed15
[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-data.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 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_ACTION_REGISTRATION(              Toolkit, ItemView, "stopScrolling",       ACTION_STOP_SCROLLING   )
264
265 DALI_ACTION_REGISTRATION(              Toolkit, ItemView, "enableRefresh",       ACTION_ENABLE_REFRESH   )
266 DALI_ACTION_REGISTRATION(              Toolkit, ItemView, "disableRefresh",      ACTION_DISABLE_REFRESH  )
267
268 DALI_TYPE_REGISTRATION_END()
269
270 bool FindById( const ItemContainer& items, ItemId id )
271 {
272   for( ConstItemIter iter = items.begin(); items.end() != iter; ++iter )
273   {
274     if( iter->first == id )
275     {
276       return true;
277     }
278   }
279
280   return false;
281 }
282
283 } // unnamed namespace
284
285 Dali::Toolkit::ItemView ItemView::New(ItemFactory& factory)
286 {
287   // Create the implementation
288   ItemViewPtr itemView(new ItemView(factory));
289
290   // Pass ownership to CustomActor via derived handle
291   Dali::Toolkit::ItemView handle(*itemView);
292
293   // Second-phase init of the implementation
294   // This can only be done after the CustomActor connection has been made...
295   itemView->Initialize();
296
297   return handle;
298 }
299
300 ItemView::ItemView(ItemFactory& factory)
301 : Scrollable( ControlBehaviour( DISABLE_SIZE_NEGOTIATION | REQUIRES_WHEEL_EVENTS | REQUIRES_KEYBOARD_NAVIGATION_SUPPORT ) ),
302   mItemFactory(factory),
303   mItemsParentOrigin(ParentOrigin::CENTER),
304   mItemsAnchorPoint(AnchorPoint::CENTER),
305   mTotalPanDisplacement(Vector2::ZERO),
306   mActiveLayout(NULL),
307   mAnchoringDuration(DEFAULT_ANCHORING_DURATION),
308   mRefreshIntervalLayoutPositions(0.0f),
309   mMinimumSwipeSpeed(DEFAULT_MINIMUM_SWIPE_SPEED),
310   mMinimumSwipeDistance(DEFAULT_MINIMUM_SWIPE_DISTANCE),
311   mWheelScrollDistanceStep(0.0f),
312   mScrollDistance(0.0f),
313   mScrollSpeed(0.0f),
314   mScrollOvershoot(0.0f),
315   mGestureState(Gesture::Clear),
316   mAnimatingOvershootOn(false),
317   mAnimateOvershootOff(false),
318   mAnchoringEnabled(false),
319   mRefreshOrderHint(true/*Refresh item 0 first*/),
320   mIsFlicking(false),
321   mAddingItems(false),
322   mRefreshEnabled(true),
323   mRefreshNotificationEnabled(true),
324   mInAnimation(false)
325 {
326 }
327
328 void ItemView::OnInitialize()
329 {
330   Actor self = Self();
331
332   Vector2 stageSize = Stage::GetCurrent().GetSize();
333   mWheelScrollDistanceStep = stageSize.y * DEFAULT_WHEEL_SCROLL_DISTANCE_STEP_PROPORTION;
334
335   self.TouchSignal().Connect( this, &ItemView::OnTouch );
336   EnableGestureDetection(Gesture::Type(Gesture::Pan));
337
338   mWheelEventFinishedTimer = Timer::New( WHEEL_EVENT_FINISHED_TIME_OUT );
339   mWheelEventFinishedTimer.TickSignal().Connect( this, &ItemView::OnWheelEventFinished );
340
341   SetRefreshInterval(DEFAULT_REFRESH_INTERVAL_LAYOUT_POSITIONS);
342 }
343
344 ItemView::~ItemView()
345 {
346 }
347
348 unsigned int ItemView::GetLayoutCount() const
349 {
350   return mLayouts.size();
351 }
352
353 void ItemView::AddLayout(ItemLayout& layout)
354 {
355   mLayouts.push_back(ItemLayoutPtr(&layout));
356 }
357
358 void ItemView::RemoveLayout(unsigned int layoutIndex)
359 {
360   DALI_ASSERT_ALWAYS(layoutIndex < mLayouts.size());
361
362   if (mActiveLayout == mLayouts[layoutIndex].Get())
363   {
364     mActiveLayout = NULL;
365   }
366
367   mLayouts.erase(mLayouts.begin() + layoutIndex);
368 }
369
370 ItemLayoutPtr ItemView::GetLayout(unsigned int layoutIndex) const
371 {
372   return mLayouts[layoutIndex];
373 }
374
375 ItemLayoutPtr ItemView::GetActiveLayout() const
376 {
377   return ItemLayoutPtr(mActiveLayout);
378 }
379
380 float ItemView::GetCurrentLayoutPosition(unsigned int itemId) const
381 {
382   return Self().GetProperty<float>( Toolkit::ItemView::Property::LAYOUT_POSITION ) + static_cast<float>( itemId );
383 }
384
385 void ItemView::ActivateLayout(unsigned int layoutIndex, const Vector3& targetSize, float durationSeconds)
386 {
387   DALI_ASSERT_ALWAYS(layoutIndex < mLayouts.size());
388
389   mRefreshEnabled = false;
390
391   Actor self = Self();
392
393   // The ItemView size should match the active layout size
394   self.SetSize(targetSize);
395   mActiveLayoutTargetSize = targetSize;
396
397   // Switch to the new layout
398   mActiveLayout = mLayouts[layoutIndex].Get();
399
400   // Move the items to the new layout positions...
401
402   for (ConstItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
403   {
404     unsigned int itemId = iter->first;
405     Actor actor = iter->second;
406
407     // Remove constraints from previous layout
408     actor.RemoveConstraints();
409
410     Vector3 size;
411     mActiveLayout->GetItemSize( itemId, targetSize, size );
412     actor.SetSize( size.GetVectorXY() );
413
414     mActiveLayout->ApplyConstraints(actor, itemId, targetSize, Self() );
415   }
416
417   // Refresh the new layout
418   ItemRange range = GetItemRange(*mActiveLayout, targetSize, GetCurrentLayoutPosition(0), false/* don't reserve extra*/);
419   AddActorsWithinRange( range, targetSize );
420
421   // Scroll to an appropriate layout position
422
423   bool scrollAnimationNeeded(false);
424   float firstItemScrollPosition(0.0f);
425
426   float current = GetCurrentLayoutPosition(0);
427   float minimum = ClampFirstItemPosition(current, targetSize, *mActiveLayout);
428
429   if (current < minimum)
430   {
431     scrollAnimationNeeded = true;
432     firstItemScrollPosition = minimum;
433   }
434   else if (mAnchoringEnabled)
435   {
436     scrollAnimationNeeded = true;
437     firstItemScrollPosition = mActiveLayout->GetClosestAnchorPosition(current);
438   }
439
440   if (scrollAnimationNeeded)
441   {
442     RemoveAnimation(mScrollAnimation);
443     mScrollAnimation = Animation::New(durationSeconds);
444     mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), firstItemScrollPosition, AlphaFunction::EASE_OUT );
445     mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnLayoutActivationScrollFinished);
446     mScrollAnimation.Play();
447   }
448   else
449   {
450     // Emit the layout activated signal
451     mLayoutActivatedSignal.Emit();
452   }
453
454   AnimateScrollOvershoot(0.0f);
455   mScrollOvershoot = 0.0f;
456
457   Radian scrollDirection(mActiveLayout->GetScrollDirection());
458   self.SetProperty(Toolkit::ItemView::Property::SCROLL_DIRECTION, Vector2(sinf(scrollDirection), cosf(scrollDirection)));
459   self.SetProperty(Toolkit::ItemView::Property::LAYOUT_ORIENTATION, static_cast<int>(mActiveLayout->GetOrientation()));
460   self.SetProperty(Toolkit::ItemView::Property::SCROLL_SPEED, mScrollSpeed);
461
462   CalculateDomainSize(targetSize);
463 }
464
465 void ItemView::DeactivateCurrentLayout()
466 {
467   if (mActiveLayout)
468   {
469     for (ConstItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
470     {
471       Actor actor = iter->second;
472       actor.RemoveConstraints();
473     }
474
475     mActiveLayout = NULL;
476   }
477 }
478
479 void ItemView::OnRefreshNotification(PropertyNotification& source)
480 {
481   if( mRefreshNotificationEnabled )
482   {
483     // Cancel scroll animation to prevent any fighting of setting the scroll position property by scroll bar during fast scroll.
484     if(!mRefreshEnabled && mScrollAnimation)
485     {
486       RemoveAnimation(mScrollAnimation);
487     }
488
489     // Only cache extra items when it is not a fast scroll
490     DoRefresh(GetCurrentLayoutPosition(0), mRefreshEnabled || mScrollAnimation);
491   }
492 }
493
494 void ItemView::Refresh()
495 {
496   for (ItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter )
497   {
498     ReleaseActor( iter->first, iter->second );
499   }
500   mItemPool.clear();
501
502   DoRefresh(GetCurrentLayoutPosition(0), true);
503 }
504
505 void ItemView::DoRefresh(float currentLayoutPosition, bool cacheExtra)
506 {
507   if (mActiveLayout)
508   {
509     ItemRange range = GetItemRange(*mActiveLayout, mActiveLayoutTargetSize, currentLayoutPosition, cacheExtra/*reserve extra*/);
510     RemoveActorsOutsideRange( range );
511     AddActorsWithinRange( range, Self().GetCurrentSize() );
512
513     mScrollUpdatedSignal.Emit( Vector2(0.0f, currentLayoutPosition) );
514   }
515 }
516
517 void ItemView::SetMinimumSwipeSpeed(float speed)
518 {
519   mMinimumSwipeSpeed = speed;
520 }
521
522 float ItemView::GetMinimumSwipeSpeed() const
523 {
524   return mMinimumSwipeSpeed;
525 }
526
527 void ItemView::SetMinimumSwipeDistance(float distance)
528 {
529   mMinimumSwipeDistance = distance;
530 }
531
532 float ItemView::GetMinimumSwipeDistance() const
533 {
534   return mMinimumSwipeDistance;
535 }
536
537 void ItemView::SetWheelScrollDistanceStep(float step)
538 {
539   mWheelScrollDistanceStep = step;
540 }
541
542 float ItemView::GetWheelScrollDistanceStep() const
543 {
544   return mWheelScrollDistanceStep;
545 }
546
547 void ItemView::SetAnchoring(bool enabled)
548 {
549   mAnchoringEnabled = enabled;
550 }
551
552 bool ItemView::GetAnchoring() const
553 {
554   return mAnchoringEnabled;
555 }
556
557 void ItemView::SetAnchoringDuration(float durationSeconds)
558 {
559   mAnchoringDuration = durationSeconds;
560 }
561
562 float ItemView::GetAnchoringDuration() const
563 {
564   return mAnchoringDuration;
565 }
566
567 void ItemView::SetRefreshInterval(float intervalLayoutPositions)
568 {
569   if( !Equals(mRefreshIntervalLayoutPositions, intervalLayoutPositions) )
570   {
571     mRefreshIntervalLayoutPositions = intervalLayoutPositions;
572
573     Actor self = Self();
574     if(mRefreshNotification)
575     {
576       self.RemovePropertyNotification(mRefreshNotification);
577     }
578     mRefreshNotification = self.AddPropertyNotification( Toolkit::ItemView::Property::LAYOUT_POSITION, StepCondition(mRefreshIntervalLayoutPositions, 0.0f) );
579     mRefreshNotification.NotifySignal().Connect( this, &ItemView::OnRefreshNotification );
580   }
581 }
582
583 float ItemView::GetRefreshInterval() const
584 {
585   return mRefreshIntervalLayoutPositions;
586 }
587
588 void ItemView::SetRefreshEnabled(bool enabled)
589 {
590   mRefreshEnabled = enabled;
591 }
592
593 Actor ItemView::GetItem(unsigned int itemId) const
594 {
595   Actor actor;
596
597   ConstItemPoolIter iter = mItemPool.find( itemId );
598   if( iter != mItemPool.end() )
599   {
600     actor = iter->second;
601   }
602
603   return actor;
604 }
605
606 unsigned int ItemView::GetItemId( Actor actor ) const
607 {
608   unsigned int itemId( 0 );
609
610   for ( ConstItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter )
611   {
612     if( iter->second == actor )
613     {
614       itemId = iter->first;
615       break;
616     }
617   }
618
619   return itemId;
620 }
621
622 void ItemView::InsertItem( Item newItem, float durationSeconds )
623 {
624   mAddingItems = true;
625   Vector3 layoutSize = Self().GetCurrentSize();
626
627   Actor displacedActor;
628   ItemPoolIter afterDisplacedIter = mItemPool.end();
629
630   ItemPoolIter foundIter = mItemPool.find( newItem.first );
631   if( mItemPool.end() != foundIter )
632   {
633     SetupActor( newItem, layoutSize );
634     Self().Add( newItem.second );
635
636     displacedActor = foundIter->second;
637     foundIter->second = newItem.second;
638
639     afterDisplacedIter = ++foundIter;
640   }
641   else
642   {
643     // Inserting before the existing item range?
644     ItemPoolIter iter = mItemPool.begin();
645     if( iter != mItemPool.end() &&
646         iter->first > newItem.first )
647     {
648       displacedActor = iter->second;
649       mItemPool.erase( iter++ ); // iter is still valid after the erase
650
651       afterDisplacedIter = iter;
652     }
653   }
654
655   if( displacedActor )
656   {
657     // Move the existing actors to make room
658     for( ItemPoolIter iter = afterDisplacedIter; mItemPool.end() != iter; ++iter )
659     {
660       Actor temp = iter->second;
661       iter->second = displacedActor;
662       displacedActor = temp;
663
664       iter->second.RemoveConstraints();
665       mActiveLayout->ApplyConstraints( iter->second, iter->first, layoutSize, Self() );
666     }
667
668     // Create last item
669     ItemPool::reverse_iterator lastIter = mItemPool.rbegin();
670     if ( lastIter != mItemPool.rend() )
671     {
672       ItemId lastId = lastIter->first;
673       Item lastItem( lastId + 1, displacedActor );
674       mItemPool.insert( lastItem );
675
676       lastItem.second.RemoveConstraints();
677       mActiveLayout->ApplyConstraints( lastItem.second, lastItem.first, layoutSize, Self() );
678     }
679   }
680
681   CalculateDomainSize( layoutSize );
682
683   mAddingItems = false;
684 }
685
686 void ItemView::InsertItems( const ItemContainer& newItems, float durationSeconds )
687 {
688   mAddingItems = true;
689   Vector3 layoutSize = Self().GetCurrentSize();
690
691   // Insert from lowest id to highest
692   std::set<Item> sortedItems;
693   for( ConstItemIter iter = newItems.begin(); newItems.end() != iter; ++iter )
694   {
695     sortedItems.insert( *iter );
696   }
697
698   for( std::set<Item>::iterator iter = sortedItems.begin(); sortedItems.end() != iter; ++iter )
699   {
700     Self().Add( iter->second );
701
702     ItemPoolIter foundIter = mItemPool.find( iter->first );
703     if( mItemPool.end() != foundIter )
704     {
705       Actor moveMe = foundIter->second;
706       foundIter->second = iter->second;
707
708       // Move the existing actors to make room
709       for( ItemPoolIter iter = ++foundIter; mItemPool.end() != iter; ++iter )
710       {
711         Actor temp = iter->second;
712         iter->second = moveMe;
713         moveMe = temp;
714       }
715
716       // Create last item
717       ItemId lastId = mItemPool.rbegin()->first;
718       Item lastItem( lastId + 1, moveMe );
719       mItemPool.insert( lastItem );
720     }
721     else
722     {
723       mItemPool.insert( *iter );
724     }
725   }
726
727   // Relayout everything
728   for (ItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
729   {
730     // If newly inserted
731     if( FindById( newItems, iter->first ) )
732     {
733       SetupActor( *iter, layoutSize );
734     }
735     else
736     {
737       iter->second.RemoveConstraints();
738       mActiveLayout->ApplyConstraints( iter->second, iter->first, layoutSize, Self() );
739     }
740   }
741
742   CalculateDomainSize( layoutSize );
743
744   mAddingItems = false;
745 }
746
747 void ItemView::RemoveItem( unsigned int itemId, float durationSeconds )
748 {
749   bool actorsReordered = RemoveActor( itemId );
750   if( actorsReordered )
751   {
752     ReapplyAllConstraints();
753
754     OnItemsRemoved();
755   }
756 }
757
758 void ItemView::RemoveItems( const ItemIdContainer& itemIds, float durationSeconds )
759 {
760   bool actorsReordered( false );
761
762   // Remove from highest id to lowest
763   set<ItemId> sortedItems;
764   for( ConstItemIdIter iter = itemIds.begin(); itemIds.end() != iter; ++iter )
765   {
766     sortedItems.insert( *iter );
767   }
768
769   for( set<ItemId>::reverse_iterator iter = sortedItems.rbegin(); sortedItems.rend() != iter; ++iter )
770   {
771     if( RemoveActor( *iter ) )
772     {
773       actorsReordered = true;
774     }
775   }
776
777   if( actorsReordered )
778   {
779     ReapplyAllConstraints();
780
781     OnItemsRemoved();
782   }
783 }
784
785 bool ItemView::RemoveActor(unsigned int itemId)
786 {
787   bool reordered( false );
788
789   ItemPoolIter removeIter = mItemPool.find( itemId );
790   if( removeIter != mItemPool.end() )
791   {
792     ReleaseActor(itemId, removeIter->second);
793   }
794   else
795   {
796     // Removing before the existing item range?
797     ItemPoolIter iter = mItemPool.begin();
798     if( iter != mItemPool.end() &&
799         iter->first > itemId )
800     {
801       // In order to decrement the first visible item ID
802       mItemPool.insert( Item(iter->first - 1, Actor()) );
803
804       removeIter = mItemPool.begin();
805     }
806   }
807
808   if( removeIter != mItemPool.end() )
809   {
810     reordered = true;
811
812     // Adjust the remaining item IDs, for example if item 2 is removed:
813     //   Initial actors:     After insert:
814     //     ID 1 - ActorA       ID 1 - ActorA
815     //     ID 2 - ActorB       ID 2 - ActorC (previously ID 3)
816     //     ID 3 - ActorC       ID 3 - ActorB (previously ID 4)
817     //     ID 4 - ActorD
818     for (ItemPoolIter iter = removeIter; iter != mItemPool.end(); ++iter)
819     {
820       if( iter->first < mItemPool.rbegin()->first )
821       {
822         iter->second = mItemPool[ iter->first + 1 ];
823       }
824       else
825       {
826         mItemPool.erase( iter );
827         break;
828       }
829     }
830   }
831
832   return reordered;
833 }
834
835 void ItemView::ReplaceItem( Item replacementItem, float durationSeconds )
836 {
837   mAddingItems = true;
838   Vector3 layoutSize = Self().GetCurrentSize();
839
840   SetupActor( replacementItem, layoutSize );
841   Self().Add( replacementItem.second );
842
843   const ItemPoolIter iter = mItemPool.find( replacementItem.first );
844   if( mItemPool.end() != iter )
845   {
846     ReleaseActor(iter->first, iter->second);
847     iter->second = replacementItem.second;
848   }
849   else
850   {
851     mItemPool.insert( replacementItem );
852   }
853
854   CalculateDomainSize( layoutSize );
855
856   mAddingItems = false;
857 }
858
859 void ItemView::ReplaceItems( const ItemContainer& replacementItems, float durationSeconds )
860 {
861   for( ConstItemIter iter = replacementItems.begin(); replacementItems.end() != iter; ++iter )
862   {
863     ReplaceItem( *iter, durationSeconds );
864   }
865 }
866
867 void ItemView::RemoveActorsOutsideRange( ItemRange range )
868 {
869   // Remove unwanted actors from the ItemView & ItemPool
870   for (ItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); )
871   {
872     unsigned int current = iter->first;
873
874     if( ! range.Within( current ) )
875     {
876       ReleaseActor(iter->first, iter->second);
877
878       mItemPool.erase( iter++ ); // erase invalidates the return value of post-increment; iter remains valid
879     }
880     else
881     {
882       ++iter;
883     }
884   }
885 }
886
887 void ItemView::AddActorsWithinRange( ItemRange range, const Vector3& layoutSize )
888 {
889   range.end = std::min(mItemFactory.GetNumberOfItems(), range.end);
890
891   // The order of addition depends on the scroll direction.
892   if (mRefreshOrderHint)
893   {
894     for (unsigned int itemId = range.begin; itemId < range.end; ++itemId)
895     {
896       AddNewActor( itemId, layoutSize );
897     }
898   }
899   else
900   {
901     for (unsigned int itemId = range.end; itemId > range.begin; --itemId)
902     {
903       AddNewActor( itemId-1, layoutSize );
904     }
905   }
906
907   // Total number of items may change dynamically.
908   // Always recalculate the domain size to reflect that.
909   CalculateDomainSize(Self().GetCurrentSize());
910 }
911
912 void ItemView::AddNewActor( unsigned int itemId, const Vector3& layoutSize )
913 {
914   mAddingItems = true;
915
916   if( mItemPool.end() == mItemPool.find( itemId ) )
917   {
918     Actor actor = mItemFactory.NewItem( itemId );
919
920     if( actor )
921     {
922       Item newItem( itemId, actor );
923
924       mItemPool.insert( newItem );
925
926       SetupActor( newItem, layoutSize );
927       Self().Add( actor );
928     }
929   }
930
931   mAddingItems = false;
932 }
933
934 void ItemView::SetupActor( Item item, const Vector3& layoutSize )
935 {
936   item.second.SetParentOrigin( mItemsParentOrigin );
937   item.second.SetAnchorPoint( mItemsAnchorPoint );
938
939   if( mActiveLayout )
940   {
941     Vector3 size;
942     mActiveLayout->GetItemSize( item.first, mActiveLayoutTargetSize, size );
943     item.second.SetSize( size.GetVectorXY() );
944
945     mActiveLayout->ApplyConstraints( item.second, item.first, layoutSize, Self() );
946   }
947 }
948
949 void ItemView::ReleaseActor( ItemId item, Actor actor )
950 {
951   Self().Remove( actor );
952   mItemFactory.ItemReleased(item, actor);
953 }
954
955 ItemRange ItemView::GetItemRange(ItemLayout& layout, const Vector3& layoutSize, float layoutPosition, bool reserveExtra)
956 {
957   unsigned int itemCount = mItemFactory.GetNumberOfItems();
958
959   ItemRange available(0u, itemCount);
960
961   ItemRange range = layout.GetItemsWithinArea( layoutPosition, layoutSize );
962
963   if (reserveExtra)
964   {
965     // Add the reserve items for scrolling
966     unsigned int extra = layout.GetReserveItemCount(layoutSize);
967     range.begin = (range.begin >= extra) ? (range.begin - extra) : 0u;
968     range.end += extra;
969   }
970
971   return range.Intersection(available);
972 }
973
974 void ItemView::OnChildAdd(Actor& child)
975 {
976   if(!mAddingItems)
977   {
978     // We don't want to do this downcast check for any item added by ItemView itself.
979     Dali::Toolkit::ScrollBar scrollBar = Dali::Toolkit::ScrollBar::DownCast(child);
980     if(scrollBar)
981     {
982       scrollBar.SetScrollPropertySource(Self(),
983                                         Toolkit::ItemView::Property::LAYOUT_POSITION,
984                                         Toolkit::Scrollable::Property::SCROLL_POSITION_MIN_Y,
985                                         Toolkit::Scrollable::Property::SCROLL_POSITION_MAX_Y,
986                                         Toolkit::ItemView::Property::SCROLL_CONTENT_SIZE);
987     }
988   }
989 }
990
991 bool ItemView::OnWheelEvent(const WheelEvent& event)
992 {
993   // Respond the wheel event to scroll
994   if (mActiveLayout)
995   {
996     Actor self = Self();
997     const Vector3 layoutSize = Self().GetCurrentSize();
998     float layoutPositionDelta = GetCurrentLayoutPosition(0) - (event.z * mWheelScrollDistanceStep * mActiveLayout->GetScrollSpeedFactor());
999     float firstItemScrollPosition = ClampFirstItemPosition(layoutPositionDelta, layoutSize, *mActiveLayout);
1000
1001     self.SetProperty(Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1002
1003     mScrollStartedSignal.Emit(GetCurrentScrollPosition());
1004     mRefreshEnabled = true;
1005   }
1006
1007   if (mWheelEventFinishedTimer.IsRunning())
1008   {
1009     mWheelEventFinishedTimer.Stop();
1010   }
1011
1012   mWheelEventFinishedTimer.Start();
1013
1014   return true;
1015 }
1016
1017 bool ItemView::OnWheelEventFinished()
1018 {
1019   if (mActiveLayout)
1020   {
1021     RemoveAnimation(mScrollAnimation);
1022
1023     // No more wheel events coming. Do the anchoring if enabled.
1024     mScrollAnimation = DoAnchoring();
1025     if (mScrollAnimation)
1026     {
1027       mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
1028       mScrollAnimation.Play();
1029     }
1030     else
1031     {
1032       mScrollOvershoot = 0.0f;
1033       AnimateScrollOvershoot(0.0f);
1034
1035       mScrollCompletedSignal.Emit(GetCurrentScrollPosition());
1036     }
1037   }
1038
1039   return false;
1040 }
1041
1042 void ItemView::ReapplyAllConstraints()
1043 {
1044   Vector3 layoutSize = Self().GetCurrentSize();
1045
1046   for (ConstItemPoolIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter)
1047   {
1048     unsigned int id = iter->first;
1049     Actor actor = iter->second;
1050
1051     actor.RemoveConstraints();
1052     mActiveLayout->ApplyConstraints(actor, id, layoutSize, Self());
1053   }
1054 }
1055
1056 void ItemView::OnItemsRemoved()
1057 {
1058   CalculateDomainSize(Self().GetCurrentSize());
1059
1060   // Adjust scroll-position after an item is removed
1061   if( mActiveLayout )
1062   {
1063     float firstItemScrollPosition = ClampFirstItemPosition(GetCurrentLayoutPosition(0), Self().GetCurrentSize(), *mActiveLayout);
1064     Self().SetProperty( Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1065   }
1066 }
1067
1068 float ItemView::ClampFirstItemPosition( float targetPosition, const Vector3& targetSize, ItemLayout& layout, bool updateOvershoot )
1069 {
1070   Actor self = Self();
1071   float minLayoutPosition = layout.GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), targetSize);
1072   float clamppedPosition = std::min(0.0f, std::max(minLayoutPosition, targetPosition));
1073   self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX, Vector2(0.0f, -minLayoutPosition));
1074
1075   if( updateOvershoot )
1076   {
1077     mScrollOvershoot = targetPosition - clamppedPosition;
1078   }
1079
1080   return clamppedPosition;
1081 }
1082
1083 bool ItemView::OnTouch( Actor actor, const TouchData& touch )
1084 {
1085   // Ignore events with multiple-touch points
1086   if (touch.GetPointCount() != 1)
1087   {
1088     return false;
1089   }
1090
1091   if ( touch.GetState( 0 ) == PointState::DOWN )
1092   {
1093     // Cancel ongoing scrolling etc.
1094     mGestureState = Gesture::Clear;
1095
1096     mScrollDistance = 0.0f;
1097     mScrollSpeed = 0.0f;
1098     Self().SetProperty(Toolkit::ItemView::Property::SCROLL_SPEED, mScrollSpeed);
1099
1100     mScrollOvershoot = 0.0f;
1101     AnimateScrollOvershoot(0.0f);
1102
1103     if(mScrollAnimation)
1104     {
1105       mScrollCompletedSignal.Emit(GetCurrentScrollPosition());
1106     }
1107
1108     RemoveAnimation(mScrollAnimation);
1109   }
1110
1111   return true; // consume since we're potentially scrolling
1112 }
1113
1114 void ItemView::OnPan( const PanGesture& gesture )
1115 {
1116   Actor self = Self();
1117   const Vector3 layoutSize = Self().GetCurrentSize();
1118
1119   RemoveAnimation(mScrollAnimation);
1120
1121   // Short-circuit if there is no active layout
1122   if (!mActiveLayout)
1123   {
1124     mGestureState = Gesture::Clear;
1125     return;
1126   }
1127
1128   mGestureState = gesture.state;
1129
1130   switch (mGestureState)
1131   {
1132     case Gesture::Finished:
1133     {
1134       // Swipe Detection
1135       if (fabsf(mScrollDistance) > mMinimumSwipeDistance &&
1136           mScrollSpeed > mMinimumSwipeSpeed)
1137       {
1138         float direction = (mScrollDistance < 0.0f) ? -1.0f : 1.0f;
1139
1140         mRefreshOrderHint = true;
1141
1142         float currentLayoutPosition = GetCurrentLayoutPosition(0);
1143         float firstItemScrollPosition = ClampFirstItemPosition(currentLayoutPosition + mScrollSpeed * direction,
1144                                                                layoutSize,
1145                                                                *mActiveLayout);
1146
1147         if (mAnchoringEnabled)
1148         {
1149           firstItemScrollPosition = mActiveLayout->GetClosestAnchorPosition(firstItemScrollPosition);
1150         }
1151
1152         RemoveAnimation(mScrollAnimation);
1153
1154         float flickAnimationDuration = Clamp( mActiveLayout->GetItemFlickAnimationDuration() * std::max(1.0f, fabsf(firstItemScrollPosition - GetCurrentLayoutPosition(0)))
1155                                        , DEFAULT_MINIMUM_SWIPE_DURATION, DEFAULT_MAXIMUM_SWIPE_DURATION);
1156
1157         mScrollAnimation = Animation::New(flickAnimationDuration);
1158         mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION ), firstItemScrollPosition, AlphaFunction::EASE_OUT );
1159         mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::SCROLL_SPEED), 0.0f, AlphaFunction::EASE_OUT );
1160
1161         mIsFlicking = true;
1162         // Check whether it has already scrolled to the end
1163         if(fabs(currentLayoutPosition - firstItemScrollPosition) > Math::MACHINE_EPSILON_0)
1164         {
1165           AnimateScrollOvershoot(0.0f);
1166         }
1167       }
1168
1169       // Anchoring may be triggered when there was no swipe
1170       if (!mScrollAnimation)
1171       {
1172         mScrollAnimation = DoAnchoring();
1173       }
1174
1175       // Reset the overshoot if no scroll animation.
1176       if (!mScrollAnimation)
1177       {
1178         mScrollCompletedSignal.Emit(GetCurrentScrollPosition());
1179
1180         AnimateScrollOvershoot(0.0f, false);
1181       }
1182     }
1183     break;
1184
1185     case Gesture::Started: // Fall through
1186     {
1187       mTotalPanDisplacement = Vector2::ZERO;
1188       mScrollStartedSignal.Emit(GetCurrentScrollPosition());
1189       mRefreshEnabled = true;
1190     }
1191
1192     case Gesture::Continuing:
1193     {
1194       mScrollDistance = CalculateScrollDistance(gesture.displacement, *mActiveLayout);
1195       mScrollSpeed = Clamp((gesture.GetSpeed() * gesture.GetSpeed() * mActiveLayout->GetFlickSpeedFactor() * MILLISECONDS_PER_SECONDS), 0.0f, mActiveLayout->GetMaximumSwipeSpeed());
1196
1197       // Refresh order depends on the direction of the scroll; negative is towards the last item.
1198       mRefreshOrderHint = mScrollDistance < 0.0f;
1199
1200       float layoutPositionDelta = GetCurrentLayoutPosition(0) + (mScrollDistance * mActiveLayout->GetScrollSpeedFactor());
1201
1202       float firstItemScrollPosition = ClampFirstItemPosition(layoutPositionDelta, layoutSize, *mActiveLayout);
1203
1204       float currentOvershoot = self.GetProperty<float>(Toolkit::ItemView::Property::OVERSHOOT);
1205
1206       self.SetProperty(Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1207
1208       if( ( firstItemScrollPosition >= 0.0f &&
1209             currentOvershoot < 1.0f ) ||
1210           ( firstItemScrollPosition <= mActiveLayout->GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), layoutSize) &&
1211             currentOvershoot > -1.0f ) )
1212       {
1213         mTotalPanDisplacement += gesture.displacement;
1214       }
1215
1216       mScrollOvershoot = CalculateScrollOvershoot();
1217
1218       // If the view is moved in a direction against the overshoot indicator, then the indicator should be animated off.
1219       // First make sure we are not in an animation, otherwise a previously started
1220       // off-animation will be overwritten as the user continues scrolling.
1221       if( !mInAnimation )
1222       {
1223         // Check if the movement is against the current overshoot amount (if we are currently displaying the indicator).
1224         if( ( ( mScrollOvershoot > Math::MACHINE_EPSILON_0 ) && ( mScrollDistance < -Math::MACHINE_EPSILON_0 ) ) ||
1225           ( ( mScrollOvershoot < Math::MACHINE_EPSILON_0 ) && ( mScrollDistance > Math::MACHINE_EPSILON_0 ) ) )
1226         {
1227           // The user has moved against the indicator direction.
1228           // First, we reset the total displacement. This means the overshoot amount will become zero the next frame,
1229           // and if the user starts dragging in the overshoot direction again, the indicator will appear once more.
1230           mTotalPanDisplacement = Vector2::ZERO;
1231           // Animate the overshoot indicator off.
1232           AnimateScrollOvershoot( 0.0f, false );
1233         }
1234         else
1235         {
1236           // Only set the property directly if we are not animating the overshoot away,
1237           // as otherwise this will overwrite the animation generated value.
1238           self.SetProperty( Toolkit::ItemView::Property::OVERSHOOT, mScrollOvershoot );
1239         }
1240       }
1241     }
1242     break;
1243
1244     case Gesture::Cancelled:
1245     {
1246       mScrollAnimation = DoAnchoring();
1247     }
1248     break;
1249
1250     default:
1251       break;
1252   }
1253
1254   if (mScrollAnimation)
1255   {
1256     mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
1257     mScrollAnimation.Play();
1258   }
1259 }
1260
1261 bool ItemView::OnAccessibilityPan(PanGesture gesture)
1262 {
1263   OnPan(gesture);
1264   return true;
1265 }
1266
1267 Actor ItemView::GetNextKeyboardFocusableActor(Actor actor, Toolkit::Control::KeyboardFocus::Direction direction, bool loopEnabled)
1268 {
1269   Actor nextFocusActor;
1270   if(mActiveLayout)
1271   {
1272     int nextItemID = 0;
1273     if(!actor || actor == this->Self())
1274     {
1275       nextFocusActor = GetItem(nextItemID);
1276     }
1277     else if(actor && actor.GetParent() == this->Self())
1278     {
1279       int itemID = GetItemId(actor);
1280       nextItemID = mActiveLayout->GetNextFocusItemID(itemID, mItemFactory.GetNumberOfItems(), direction, loopEnabled);
1281       nextFocusActor = GetItem(nextItemID);
1282       if(nextFocusActor == actor)
1283       {
1284         // need to pass NULL actor back to focus manager
1285         nextFocusActor.Reset();
1286         return nextFocusActor;
1287       }
1288     }
1289     float layoutPosition = mActiveLayout->GetClosestAnchorPosition( GetCurrentLayoutPosition(0) );
1290     Vector3 layoutSize = Self().GetCurrentSize();
1291     if(!nextFocusActor)
1292     {
1293       // likely the current item is not buffered, so not in our item pool, probably best to get first viewable item
1294       ItemRange viewableItems = mActiveLayout->GetItemsWithinArea(layoutPosition, layoutSize);
1295       nextItemID = viewableItems.begin;
1296       nextFocusActor = GetItem(nextItemID);
1297     }
1298   }
1299   return nextFocusActor;
1300 }
1301
1302 void ItemView::OnKeyboardFocusChangeCommitted(Actor commitedFocusableActor)
1303 {
1304   // only in this function if our chosen focus actor was actually used
1305   if(commitedFocusableActor)
1306   {
1307     int nextItemID = GetItemId(commitedFocusableActor);
1308     float layoutPosition = GetCurrentLayoutPosition(0);
1309     Vector3 layoutSize = Self().GetCurrentSize();
1310
1311     float scrollTo = mActiveLayout->GetClosestOnScreenLayoutPosition(nextItemID, layoutPosition, layoutSize);
1312     ScrollTo(Vector2(0.0f, scrollTo), DEFAULT_KEYBOARD_FOCUS_SCROLL_DURATION);
1313   }
1314 }
1315
1316 Animation ItemView::DoAnchoring()
1317 {
1318   Animation anchoringAnimation;
1319   Actor self = Self();
1320
1321   if (mActiveLayout && mAnchoringEnabled)
1322   {
1323     float anchorPosition = mActiveLayout->GetClosestAnchorPosition( GetCurrentLayoutPosition(0) );
1324
1325     anchoringAnimation = Animation::New(mAnchoringDuration);
1326     anchoringAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), anchorPosition, AlphaFunction::EASE_OUT );
1327     anchoringAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::SCROLL_SPEED), 0.0f, AlphaFunction::EASE_OUT );
1328     if(!mIsFlicking)
1329     {
1330       AnimateScrollOvershoot(0.0f);
1331     }
1332   }
1333
1334   return anchoringAnimation;
1335 }
1336
1337 void ItemView::OnScrollFinished(Animation& source)
1338 {
1339   Actor self = Self();
1340
1341   RemoveAnimation(mScrollAnimation); // mScrollAnimation is used to query whether we're scrolling
1342
1343   mScrollCompletedSignal.Emit(GetCurrentScrollPosition());
1344
1345   if(mIsFlicking && fabsf(mScrollOvershoot) > Math::MACHINE_EPSILON_1)
1346   {
1347     AnimateScrollOvershoot( mScrollOvershoot > 0.0f ? 1.0f : -1.0f, true);
1348   }
1349   else
1350   {
1351     // Reset the overshoot
1352     AnimateScrollOvershoot( 0.0f );
1353   }
1354   mIsFlicking = false;
1355
1356   mScrollOvershoot = 0.0f;
1357 }
1358
1359 void ItemView::OnLayoutActivationScrollFinished(Animation& source)
1360 {
1361   RemoveAnimation(mScrollAnimation);
1362   mRefreshEnabled = true;
1363   DoRefresh(GetCurrentLayoutPosition(0), true);
1364
1365   // Emit the layout activated signal
1366   mLayoutActivatedSignal.Emit();
1367 }
1368
1369 void ItemView::OnOvershootOnFinished(Animation& animation)
1370 {
1371   mAnimatingOvershootOn = false;
1372   mScrollOvershootAnimation.FinishedSignal().Disconnect(this, &ItemView::OnOvershootOnFinished);
1373   RemoveAnimation(mScrollOvershootAnimation);
1374   if(mAnimateOvershootOff)
1375   {
1376     AnimateScrollOvershoot(0.0f);
1377   }
1378   mInAnimation = false;
1379 }
1380
1381 void ItemView::ScrollToItem(unsigned int itemId, float durationSeconds)
1382 {
1383   Actor self = Self();
1384   const Vector3 layoutSize = Self().GetCurrentSize();
1385   float firstItemScrollPosition = ClampFirstItemPosition(mActiveLayout->GetItemScrollToPosition(itemId), layoutSize, *mActiveLayout);
1386
1387   if(durationSeconds > 0.0f)
1388   {
1389     RemoveAnimation(mScrollAnimation);
1390     mScrollAnimation = Animation::New(durationSeconds);
1391     mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), firstItemScrollPosition, mScrollToAlphaFunction );
1392     mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished);
1393     mScrollAnimation.Play();
1394   }
1395   else
1396   {
1397     self.SetProperty( Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition );
1398     AnimateScrollOvershoot(0.0f);
1399   }
1400
1401   mScrollStartedSignal.Emit(GetCurrentScrollPosition());
1402   mRefreshEnabled = true;
1403 }
1404
1405 void ItemView::RemoveAnimation(Animation& animation)
1406 {
1407   if(animation)
1408   {
1409     // Cease animating, and reset handle.
1410     animation.Clear();
1411     animation.Reset();
1412   }
1413 }
1414
1415 void ItemView::CalculateDomainSize(const Vector3& layoutSize)
1416 {
1417   Actor self = Self();
1418
1419   Vector3 firstItemPosition(Vector3::ZERO);
1420   Vector3 lastItemPosition(Vector3::ZERO);
1421
1422   if(mActiveLayout)
1423   {
1424     firstItemPosition = mActiveLayout->GetItemPosition( 0,0,layoutSize );
1425
1426     float minLayoutPosition = mActiveLayout->GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), layoutSize);
1427     lastItemPosition = mActiveLayout->GetItemPosition( fabs(minLayoutPosition),fabs(minLayoutPosition),layoutSize );
1428
1429     float domainSize;
1430
1431     if(IsHorizontal(mActiveLayout->GetOrientation()))
1432     {
1433       domainSize = fabs(firstItemPosition.x - lastItemPosition.x);
1434     }
1435     else
1436     {
1437       domainSize = fabs(firstItemPosition.y - lastItemPosition.y);
1438     }
1439
1440     self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MIN, Vector2::ZERO);
1441     self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX, Vector2(0.0f, -minLayoutPosition));
1442
1443     self.SetProperty(Toolkit::ItemView::Property::SCROLL_CONTENT_SIZE, domainSize);
1444
1445     bool isLayoutScrollable = IsLayoutScrollable(layoutSize);
1446     self.SetProperty(Toolkit::Scrollable::Property::CAN_SCROLL_VERTICAL, isLayoutScrollable);
1447     self.SetProperty(Toolkit::Scrollable::Property::CAN_SCROLL_HORIZONTAL, false);
1448   }
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, mScrollToAlphaFunction );
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 bool ItemView::DoAction( BaseObject* object, const std::string& actionName, const Property::Map& attributes )
1782 {
1783   Dali::BaseHandle handle( object );
1784
1785   Toolkit::ItemView itemView = Toolkit::ItemView::DownCast( handle );
1786
1787   DALI_ASSERT_ALWAYS( itemView );
1788
1789   if( 0 == strcmp( actionName.c_str(), ACTION_STOP_SCROLLING ) )
1790   {
1791     GetImpl( itemView ).DoStopScrolling();
1792   }
1793   else if ( 0 == strcmp( actionName.c_str(), ACTION_ENABLE_REFRESH ) )
1794   {
1795     GetImpl( itemView ).SetRefreshNotificationEnabled( true );
1796   }
1797   else if ( 0 == strcmp( actionName.c_str(), ACTION_DISABLE_REFRESH ) )
1798   {
1799     GetImpl( itemView ).SetRefreshNotificationEnabled( false );
1800   }
1801
1802   return true;
1803 }
1804
1805 void ItemView::DoStopScrolling()
1806 {
1807   if( mScrollAnimation )
1808   {
1809     mScrollAnimation.Stop();
1810     mScrollAnimation.Reset();
1811   }
1812 }
1813
1814 void ItemView::SetRefreshNotificationEnabled( bool enabled )
1815 {
1816   mRefreshNotificationEnabled = enabled;
1817 }
1818
1819 } // namespace Internal
1820
1821 } // namespace Toolkit
1822
1823 } // namespace Dali