Add support for ItemView layout customisation through properties.
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / controls / scrollable / item-view / item-view-impl.h
1 #ifndef __DALI_TOOLKIT_INTERNAL_ITEM_VIEW_H__
2 #define __DALI_TOOLKIT_INTERNAL_ITEM_VIEW_H__
3
4 /*
5  * Copyright (c) 2014 Samsung Electronics Co., Ltd.
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  * http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  */
20
21 // EXTERNAL INCLUDES
22 #include <dali/public-api/adaptor-framework/timer.h>
23 #include <dali/public-api/animation/animation.h>
24 #include <dali/public-api/object/property-notification.h>
25 #include <dali/devel-api/common/map-wrapper.h>
26 #include <dali/public-api/object/property-map.h>
27 #include <dali/public-api/object/property-array.h>
28
29 // INTERNAL INCLUDES
30 #include <dali-toolkit/public-api/controls/control-impl.h>
31 #include <dali-toolkit/public-api/controls/scrollable/item-view/item-view.h>
32 #include <dali-toolkit/public-api/controls/scrollable/item-view/item-layout.h>
33 #include <dali-toolkit/public-api/controls/image-view/image-view.h>
34 #include <dali-toolkit/internal/controls/scrollable/scrollable-impl.h>
35 #include <dali-toolkit/public-api/focus-manager/keyboard-focus-manager.h>
36
37 namespace Dali
38 {
39
40 namespace Toolkit
41 {
42
43 namespace Internal
44 {
45
46 class ItemView;
47
48 typedef IntrusivePtr<ItemView> ItemViewPtr;
49
50 /**
51  * ItemView is a scrollable layout container.
52  * Multiple ItemLayouts may be provided, to determine the logical position of each item a layout.
53  * Actor-ID pairs are provided from a shared ItemFactory, to display the currently visible items.
54  */
55 class ItemView : public Scrollable
56 {
57 public:
58
59   // Signals
60   typedef Toolkit::ItemView::LayoutActivatedSignalType LayoutActivatedSignalType;
61
62 public:
63
64   /**
65    * Create a new ItemView.
66    * @param[in] factory The factory which provides ItemView with items.
67    * @return A public handle to the newly allocated ItemView.
68    */
69   static Dali::Toolkit::ItemView New(ItemFactory& factory);
70
71   /**
72    * @copydoc Toolkit::ItemView::GetLayoutCount
73    */
74   unsigned int GetLayoutCount() const;
75
76   /**
77    * @copydoc Toolkit::ItemView::AddLayout
78    */
79   void AddLayout(ItemLayout& layout);
80
81   /**
82    * @copydoc Toolkit::ItemView::RemoveLayout
83    */
84   void RemoveLayout(unsigned int layoutIndex);
85
86   /**
87    * @copydoc Toolkit::ItemView::GetLayout
88    */
89   ItemLayoutPtr GetLayout(unsigned int layoutIndex) const;
90
91   /**
92    * @copydoc Toolkit::ItemView::GetActiveLayout
93    */
94   ItemLayoutPtr GetActiveLayout() const;
95
96   /**
97    * @copydoc Toolkit::ItemView::GetCurrentLayoutPosition
98    */
99   float GetCurrentLayoutPosition(unsigned int itemId) const;
100
101   /**
102    * @copydoc Toolkit::ItemView::ActivateLayout
103    */
104   void ActivateLayout(unsigned int layoutIndex, const Vector3& targetSize, float durationSeconds);
105
106   /**
107    * @copydoc Toolkit::ItemView::DeactivateCurrentLayout
108    */
109   void DeactivateCurrentLayout();
110
111   /**
112    * @copydoc Toolkit::ItemView::SetMinimumSwipeSpeed
113    */
114   void SetMinimumSwipeSpeed(float speed);
115
116   /**
117    * @copydoc Toolkit::ItemView::GetMinimumSwipeSpeed
118    */
119   float GetMinimumSwipeSpeed() const;
120
121   /**
122    * @copydoc Toolkit::ItemView::SetMinimumSwipeDistance
123    */
124   void SetMinimumSwipeDistance(float distance);
125
126   /**
127    * @copydoc Toolkit::ItemView::GetMinimumSwipeDistance
128    */
129   float GetMinimumSwipeDistance() const;
130
131   /**
132    * @copydoc Toolkit::ItemView::SetWheelScrollDistanceStep
133    */
134   void SetWheelScrollDistanceStep(float step);
135
136   /**
137    * @copydoc Toolkit::ItemView::GetWheelScrollDistanceStep
138    */
139   float GetWheelScrollDistanceStep() const;
140
141   /**
142    * @copydoc Toolkit::ItemView::SetAnchoring
143    */
144   void SetAnchoring(bool enabled);
145
146   /**
147    * @copydoc Toolkit::ItemView::GetAnchoring
148    */
149   bool GetAnchoring() const;
150
151   /**
152    * @copydoc Toolkit::ItemView::SetAnchoringDuration
153    */
154   void SetAnchoringDuration(float durationSeconds);
155
156   /**
157    * @copydoc Toolkit::ItemView::GetAnchoringDuration
158    */
159   float GetAnchoringDuration() const;
160
161   /**
162    * @copydoc Toolkit::ItemView::ScrollToItem
163    */
164   void ScrollToItem(unsigned int itemId, float durationSeconds);
165
166   /**
167    * @copydoc Toolkit::ItemView::SetRefreshInterval
168    */
169   void SetRefreshInterval(float intervalLayoutPositions);
170
171   /**
172    * @copydoc Toolkit::ItemView::GetRefreshInterval
173    */
174   float GetRefreshInterval() const;
175
176   /**
177    * @copydoc Toolkit::ItemView::Refresh
178    */
179   void Refresh();
180
181   /**
182    * @copydoc Toolkit::ItemView::GetItem
183    */
184   Actor GetItem(unsigned int itemId) const;
185
186   /**
187    * @copydoc Toolkit::ItemView::GetItemId
188    */
189   unsigned int GetItemId(Actor actor) const;
190
191   /**
192    * @copydoc Toolkit::ItemView::InsertItem
193    */
194   void InsertItem(Item newItem, float durationSeconds);
195
196   /**
197    * @copydoc Toolkit::ItemView::InsertItem
198    */
199   void InsertItems(const ItemContainer& newItems, float durationSeconds);
200
201   /**
202    * @copydoc Toolkit::ItemView::RemoveItem
203    */
204   void RemoveItem(ItemId itemId, float durationSeconds);
205
206   /**
207    * @copydoc Toolkit::ItemView::InsertItem
208    */
209   void RemoveItems(const ItemIdContainer& itemIds, float durationSeconds);
210
211   /**
212    * @copydoc Toolkit::ItemView::InsertItem
213    */
214   void ReplaceItem(Item replacementItem, float durationSeconds);
215
216   /**
217    * @copydoc Toolkit::ItemView::InsertItem
218    */
219   void ReplaceItems(const ItemContainer& replacementItems, float durationSeconds);
220
221   /**
222    * @copydoc Toolkit::Scrollable::GetCurrentScrollPosition
223    */
224   Vector2 GetCurrentScrollPosition() const;
225
226   /**
227    * @copydoc Toolkit::Scrollable::AddOverlay()
228    */
229   void AddOverlay(Actor actor);
230
231   /**
232    * @copydoc Toolkit::Scrollable::RemoveOverlay()
233    */
234   void RemoveOverlay(Actor actor);
235
236   /**
237    * @copydoc Toolkit::Scrollable::ScrollTo(const Vector2& position, float duration)
238    */
239   void ScrollTo(const Vector2& position, float duration);
240
241   /**
242    * @copydoc Toolkit::Internal::Scrollable::SetOvershootEffectColor
243    */
244   void SetOvershootEffectColor( const Vector4& color );
245
246   /**
247    * @brief Set whether to enable automatic refresh or not. When refresh is disabled,
248    * ItemView will not automatically refresh the cache in the given interval when the
249    * layout position is changed. This is useful in some cases, for example, automatic
250    * refresh is not needed during fast scrolling, otherwise it will cache unneeded
251    * items when the layout position changes quickly.
252    *
253    * @param[in] enabled True to enable automatic refresh or false to disable it.
254    */
255   void SetRefreshEnabled(bool enabled);
256
257   /**
258    * @brief Helper to perform the refresh.
259    *
260    * @param[in] currentLayoutPosition The current layout position.
261    * @param[in] cacheExtra Whether to cache extra items during refresh.
262    */
263   void DoRefresh(float currentLayoutPosition, bool cacheExtra);
264
265   /**
266    * @copydoc Toolkit::ItemView::SetItemsParentOrigin
267    */
268   void SetItemsParentOrigin( const Vector3& parentOrigin );
269
270   /**
271    * @copydoc Toolkit::ItemView::GetItemsParentOrigin
272    */
273   Vector3 GetItemsParentOrigin() const;
274
275   /**
276    * @copydoc Toolkit::ItemView::SetItemsAnchorPoint
277    */
278   void SetItemsAnchorPoint( const Vector3& anchorPoint );
279
280   /**
281    * @copydoc Toolkit::ItemView::GetItemsAnchorPoint
282    */
283   Vector3 GetItemsAnchorPoint() const;
284
285   /**
286    * @copydoc Toolkit::ItemView::GetItemsRange
287    */
288   void GetItemsRange(ItemRange& range);
289
290   /**
291    * @copydoc Toolkit::ItemView::LayoutActivatedSignal()
292    */
293   LayoutActivatedSignalType& LayoutActivatedSignal()
294   {
295     return mLayoutActivatedSignal;
296   }
297
298   /**
299    * Connects a callback function with the object's signals.
300    * @param[in] object The object providing the signal.
301    * @param[in] tracker Used to disconnect the signal.
302    * @param[in] signalName The signal to connect to.
303    * @param[in] functor A newly allocated FunctorDelegate.
304    * @return True if the signal was connected.
305    * @post If a signal was connected, ownership of functor was passed to CallbackBase. Otherwise the caller is responsible for deleting the unused functor.
306    */
307   static bool DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor );
308
309   //properties
310
311   /**
312    * Called when a property of an object of this type is set.
313    * @param[in] object The object whose property is set.
314    * @param[in] index The property index.
315    * @param[in] value The new property value.
316    */
317   static void SetProperty( BaseObject* object, Property::Index index, const Property::Value& value );
318
319   /**
320    * Called to retrieve a property of an object of this type.
321    * @param[in] object The object whose property is to be retrieved.
322    * @param[in] index The property index.
323    * @return The current value of the property.
324    */
325   static Property::Value GetProperty( BaseObject* object, Property::Index index );
326
327   /**
328    * Performs actions as requested using the action name.
329    * @param[in] object The object on which to perform the action.
330    * @param[in] actionName The action to perform.
331    * @param[in] attributes The attributes with which to perfrom this action.
332    * @return true if action has been accepted by this control
333    */
334   static bool DoAction( BaseObject* object, const std::string& actionName, const Property::Map& attributes );
335
336   /**
337    * Helper for DoAction( ACTION_STOP_SCROLLING ).
338    */
339   void DoStopScrolling();
340
341   /**
342    * Helper for DoAction( ACTION_ENABLE/DISABLE_REFRESH_NOTIFICATIONS ).
343    * @param[in] enabled Whether to disable refresh notifications or not.
344    */
345   void SetRefreshNotificationEnabled( bool enabled );
346
347 private:
348
349   /**
350    * Get all the layouts used in the ItemView.
351    * @return The layout array
352    */
353   Property::Array GetLayoutArray();
354
355   /**
356    * Set all the layouts. that will be used in the ItemView.
357    * @param[in] layouts The layouts used in the itemView.
358    */
359   void SetLayoutArray( const Property::Array& layouts );
360
361   /**
362    * Remove an Actor if found in the ItemPool.
363    * @param[in] itemId The item to remove.
364    * @return True if the remaining actors were reordered.
365    */
366   bool RemoveActor( unsigned int itemId );
367
368   /**
369    * Remove any Actors outside a given range.
370    * @param[in] @param[in] range The range of required items.
371    */
372   void RemoveActorsOutsideRange( ItemRange range );
373
374   /**
375    * Add a range of Actors, if they are not already in the ItemPool.
376    * @param[in] range The range of Item IDs to associate with the new actors.
377    * @param[in] layoutSize The layout-size.
378    */
379   void AddActorsWithinRange( ItemRange range, const Vector3& layoutSize );
380
381   /**
382    * Add a new Actor, if not already in the ItemPool.
383    * @param[in] item The ID for the new item.
384    * @param[in] layoutSize The layout-size.
385    */
386   void AddNewActor( ItemId item, const Vector3& layoutSize );
387
388   /**
389    * Apply the constraints etc. that are required for ItemView children.
390    * @param[in] item The item to setup.
391    * @param[in] layoutSize The layout-size.
392    */
393   void SetupActor( Item item, const Vector3& layoutSize );
394
395   /**
396    * Remove the Actor from the ItemPool and notify the ItemFactory the actor has been released by ItemView.
397    * @param[in] item The ID for the item to be released.
398    * @param[in] actor The actor to be removed from ItemView.
399    */
400   void ReleaseActor( ItemId item, Actor actor );
401
402 private: // From CustomActorImpl
403
404   /**
405    * From CustomActorImpl; called after a child has been added to the owning actor.
406    * @param[in] child The child which has been added.
407    */
408   virtual void OnChildAdd(Actor& child);
409
410   /**
411    * From CustomActorImpl; called after a wheel-event is received by the owning actor.
412    * @param[in] event The wheel event.
413    * @return True if the event should be consumed.
414    */
415   virtual bool OnWheelEvent(const WheelEvent& event);
416
417 private: // From Control
418
419   /**
420    * @copydoc Toolkit::Control::OnInitialize()
421    */
422   virtual void OnInitialize();
423
424   /**
425    * @copydoc Toolkit::Control::OnAccessibilityPan()
426    */
427   virtual bool OnAccessibilityPan(PanGesture gesture);
428
429   /**
430    * @copydoc Toolkit::Control::GetNextKeyboardFocusableActor()
431    */
432   virtual Actor GetNextKeyboardFocusableActor(Actor actor, Toolkit::Control::KeyboardFocus::Direction direction, bool loopEnabled);
433
434   /**
435    * @copydoc Toolkit::Control::OnKeyboardFocusChangeCommitted()
436    */
437   virtual void OnKeyboardFocusChangeCommitted(Actor commitedFocusableActor);
438
439 protected:
440
441   /**
442    * Construct a new ItemView.
443    * @param[in] factory The factory which provides ItemView with items.
444    */
445   ItemView(ItemFactory& factory);
446
447   /**
448    * A reference counted object may only be deleted by calling Unreference()
449    */
450   virtual ~ItemView();
451
452 private:
453
454   // Undefined
455   ItemView(const ItemView&);
456
457   // Undefined
458   ItemView& operator=(const ItemView& rhs);
459
460   /**
461    * Helper to re-apply all the constraints after items have been inserted, removed etc.
462    * @param[in] durationSeconds The time taken to fully constrain the actors.
463    */
464   void ReapplyAllConstraints();
465
466   /**
467    * Helper to relayout after item(s) are removed.
468    */
469   void OnItemsRemoved();
470
471   /**
472    * Helper to remove items outside a given range.
473    * @param[in] range The range of required items.
474    */
475   void RemoveItems(ItemRange range);
476
477   /**
478    * Helper to add a range of items, if not already in the ItemPool.
479    * @param[in] layout The layout used to position the new items.
480    * @param[in] layoutSize The current size of the layout.
481    * @param[in] range The range of required items.
482    */
483   void AddItems(ItemLayout& layout, const Vector3& layoutSize, ItemRange range);
484
485   /**
486    * Helper to find the range of items to populate with.
487    * @param[in] layout The current layout.
488    * @param[in] range The range of items.
489    * @param[in] reserveExtra True if reserve items should be included.
490    */
491   ItemRange GetItemRange(ItemLayout& layout, const Vector3& layoutSize, float layoutPosition, bool reserveExtra);
492
493   // Input Handling
494
495   /**
496    * Helper to clamp the first-item position when dragging/swiping.
497    * @param[in] targetPosition The target position of the drag etc.
498    * @param[in] targetSize The target ItemView & layout size.
499    * @param[in] layout The current layout.
500    * @param[in] updateOvershoot False stops the current overshoot value from being clamped also.
501    * @return The clamped first-item position.
502    */
503   float ClampFirstItemPosition(float targetPosition, const Vector3& targetSize, ItemLayout& layout, bool updateOvershoot = true);
504
505   /**
506    * Called after a touch-signal is received by the owning actor.
507    * @param[in] actor The touched actor.
508    * @param[in] touch The touch information.
509    * @return True if the event should be consumed.
510    */
511   bool OnTouch( Actor actor, const TouchData& touch );
512
513   /**
514    * Called upon pan gesture event.
515    *
516    * @param[in] gesture The gesture event.
517    */
518   void OnPan( const PanGesture& pan );
519
520   /**
521    * Helper to handle anchoring animations.
522    * @return The animation, or an uninitialized handle if not necessary.
523    */
524   Animation DoAnchoring();
525
526   /**
527    * Callback from scroll animations
528    * @param[in] animation The scroll-animation which has finished.
529    */
530   void OnScrollFinished(Animation& animation);
531
532   /**
533    * Callback from layout activation scroll animations
534    * @param[in] animation The scroll-animation which has finished.
535    */
536   void OnLayoutActivationScrollFinished(Animation& animation);
537
538   /**
539    * Called by animation system when overshoot has finished animating to maximum (either -1.0f or 1.0f)
540    *
541    * @param[in] animation the animation that has finished
542    */
543   void OnOvershootOnFinished(Animation& animation);
544
545   /**
546    * This is called after a timeout when no new wheel event is received for a certain period of time.
547    * @return will return false; one-shot timer.
548    */
549   bool OnWheelEventFinished();
550
551   /**
552    * Stops and removes animation if exists.
553    * @param[in,out] animation The animation handle to be removed.
554    */
555   void RemoveAnimation(Animation& animation);
556
557   /**
558    * @copydoc Toolkit::Internal::Scrollable::EnableScrollOvershoot
559    */
560   virtual void EnableScrollOvershoot( bool enable );
561
562   /**
563    * Helper to calculate the scroll overshoot according to the pan gesture displacement.
564    * @return The scroll overshoot.
565    */
566   float CalculateScrollOvershoot();
567
568   /**
569    * Helper to calculate the scroll overshoot according to the pan gesture displacement.
570    *
571    * @param[in] overshootAmount amount to animate to
572    * @param[in] animateBack whether to animate back to zero immediately after
573    * @return The scroll overshoot.
574    */
575   void AnimateScrollOvershoot(float overshootAmount, bool animateBack = false);
576
577   /**
578    * Gets the scroll position in pixels according to the logical layout position.
579    * @param[in] layoutSize The current size of the layout.
580    */
581   float GetScrollPosition(float layoutPosition, const Vector3& layoutSize) const;
582
583   /**
584    * Calculates the minimum and maximum positions for each axis to scroll to.
585    * @param[in] layoutSize The current size of the layout.
586    */
587   void CalculateDomainSize(const Vector3& layoutSize);
588
589   /**
590    * Calculates whether we want to allow current item view to scroll.
591    * @param[in] layoutSize The current size of the layout.
592    * @return    true if itemview is scrollable
593    */
594   bool IsLayoutScrollable(const Vector3& layoutSize);
595
596   /**
597    * Callback when the current layout position of ItemView changes in both positive
598    * and negative directions by the specified amount. Refresh the ItemView to create
599    * newly visible items.
600    * @param[in] source the property notification that triggered this callback
601    */
602   void OnRefreshNotification(PropertyNotification& source);
603
604 private:
605
606   typedef std::map<unsigned int, Actor> ItemPool;
607   typedef ItemPool::iterator            ItemPoolIter;
608   typedef ItemPool::const_iterator      ConstItemPoolIter;
609
610   Property::Array mlayoutArray;
611
612   ItemPool mItemPool;
613   ItemFactory& mItemFactory;
614   std::vector< ItemLayoutPtr > mLayouts;            ///< Container of Dali::Toolkit::ItemLayout objects
615   Actor mOvershootOverlay;                          ///< The overlay actor for overshoot effect
616   Animation mResizeAnimation;
617   Animation mScrollAnimation;
618   Animation mScrollOvershootAnimation;
619   Timer mWheelEventFinishedTimer;                   ///< The timer to determine whether there is no wheel event received for a certain period of time.
620   PropertyNotification mRefreshNotification;        ///< Stores the property notification used for item view refresh
621   LayoutActivatedSignalType mLayoutActivatedSignal;
622   Vector3 mActiveLayoutTargetSize;
623   Vector3 mItemsParentOrigin;
624   Vector3 mItemsAnchorPoint;
625   Vector2 mTotalPanDisplacement;
626   ItemLayout* mActiveLayout;
627
628   float mAnchoringDuration;
629   float mRefreshIntervalLayoutPositions;            ///< Refresh item view when the layout position changes by this interval in both positive and negative directions.
630   float mMinimumSwipeSpeed;
631   float mMinimumSwipeDistance;
632   float mWheelScrollDistanceStep;                   ///< The step of scroll distance in actor coordinates for each wheel event received.
633   float mScrollDistance;
634   float mScrollSpeed;
635   float mScrollOvershoot;
636
637   Dali::Gesture::State mGestureState    : 3;
638   bool mAnimatingOvershootOn            : 1;        ///< Whether we are currently animating overshoot to 1.0f/-1.0f (on) or to 0.0f (off)
639   bool mAnimateOvershootOff             : 1;        ///< Whether we are currently animating overshoot to 1.0f/-1.0f (on) or to 0.0f (off)
640   bool mAnchoringEnabled                : 1;
641   bool mRefreshOrderHint                : 1;        ///< True if scrolling towards the last item
642   bool mIsFlicking                      : 1;
643   bool mAddingItems                     : 1;
644   bool mRefreshEnabled                  : 1;        ///< Whether to refresh the cache automatically
645   bool mRefreshNotificationEnabled      : 1;        ///< Whether to disable refresh notifications or not.
646   bool mInAnimation                     : 1;        ///< Keeps track of whether an animation is controlling the overshoot property.
647 };
648
649 } // namespace Internal
650
651 // Helpers for public-api forwarding methods
652
653 inline Toolkit::Internal::ItemView& GetImpl(Toolkit::ItemView& itemView)
654 {
655   DALI_ASSERT_ALWAYS(itemView);
656
657   Dali::RefObject& handle = itemView.GetImplementation();
658
659   return static_cast<Toolkit::Internal::ItemView&>(handle);
660 }
661
662 inline const Toolkit::Internal::ItemView& GetImpl(const Toolkit::ItemView& itemView)
663 {
664   DALI_ASSERT_ALWAYS(itemView);
665
666   const Dali::RefObject& handle = itemView.GetImplementation();
667
668   return static_cast<const Toolkit::Internal::ItemView&>(handle);
669 }
670
671 } // namespace Toolkit
672
673 } // namespace Dali
674
675 #endif // __DALI_TOOLKIT_INTERNAL_ITEM_VIEW_H__