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