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