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