Improve fast scrolling performance in ItemView
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / controls / scroll-bar / scroll-bar-impl.cpp
1 //
2 // Copyright (c) 2014 Samsung Electronics Co., Ltd.
3 //
4 // Licensed under the Flora License, Version 1.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://floralicense.org/license/
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 #include <dali-toolkit/internal/controls/scroll-bar/scroll-bar-impl.h>
18 #include <dali-toolkit/internal/controls/scrollable/item-view/item-view-impl.h>
19
20 using namespace Dali;
21
22 namespace
23 {
24
25 const char* DEFAULT_INDICATOR_IMAGE_PATH = DALI_IMAGE_DIR "popup_scroll.png";
26 const Vector4 DEFAULT_INDICATOR_NINE_PATCH_BORDER(0.0f, 12.0f, 14.0f, 14.0f);
27 const float DEFAULT_SLIDER_DEPTH(1.0f);
28 const float INDICATOR_SHOW_TIME(0.5f);
29 const float INDICATOR_HIDE_TIME(0.5f);
30 const float DEFAULT_PAN_GESTURE_PROCESS_TIME(16.7f); // 16.7 milliseconds, i.e. one frame
31
32 /**
33  * Indicator size constraint
34  * Indicator size depends on both indicator's parent size and the scroll content size
35  */
36 struct IndicatorSizeConstraint
37 {
38   /**
39    * @param[in] contentSize The size of scrollable content
40    */
41   IndicatorSizeConstraint(float contentSize)
42   : mContentSize(contentSize)
43   {
44   }
45
46   /**
47    * Constraint operator
48    * @param[in] current The current indicator size
49    * @param[in] parentSizeProperty The parent size of scroll indicator.
50    * @return The new scroll indicator size.
51    */
52   Vector3 operator()(const Vector3& current,
53                      const PropertyInput& parentSizeProperty)
54   {
55     const Vector3& parentSize = parentSizeProperty.GetVector3();
56     float height = mContentSize > parentSize.height ? parentSize.height * ( parentSize.height / mContentSize ) : parentSize.height * ( (parentSize.height - mContentSize * 0.5f) / parentSize.height);
57     return Vector3( parentSize.width, height, parentSize.depth );
58   }
59
60   float mContentSize;  ///< The size of scrollable content
61 };
62
63 /**
64  * Indicator position constraint
65  * Positions the indicator to reflect the current scroll position within the scroll domain.
66  */
67 struct IndicatorPositionConstraint
68 {
69   /**
70    * @param[in] minPosition The minimum limit of scroll position
71    * @param[in] maxPosition the maximum limit of scroll position
72    */
73   IndicatorPositionConstraint(float minPosition, float maxPosition)
74   : mMinPosition(minPosition),
75     mMaxPosition(maxPosition)
76   {
77   }
78
79   /**
80    * Constraint operator
81    * @param[in] current The current indicator position
82    * @param[in] indicatorSizeProperty The size of indicator.
83    * @param[in] parentSizeProperty The parent size of indicator.
84    * @param[in] scrollPositionProperty The scroll position of the scrollable container // (from 0.0 -> 1.0 in each axis)
85    * @return The new indicator position is returned.
86    */
87   Vector3 operator()(const Vector3& current,
88                      const PropertyInput& indicatorSizeProperty,
89                      const PropertyInput& parentSizeProperty,
90                      const PropertyInput& scrollPositionProperty)
91   {
92     Vector3 indicatorSize = indicatorSizeProperty.GetVector3();
93     Vector3 parentSize = parentSizeProperty.GetVector3();
94     float scrollPosition = scrollPositionProperty.GetFloat();
95
96     const float domainSize = fabs(mMaxPosition - mMinPosition);
97     float relativePosition = (mMaxPosition - scrollPosition) / domainSize;
98     return Vector3(current.x, relativePosition * (parentSize.height - indicatorSize.height), DEFAULT_SLIDER_DEPTH);
99   }
100
101   float mMinPosition;  ///< The minimum scroll position
102   float mMaxPosition;  ///< The maximum scroll position
103 };
104
105 } // unnamed namespace
106
107 namespace Dali
108 {
109
110 namespace Toolkit
111 {
112
113 namespace Internal
114 {
115
116 namespace
117 {
118
119 using namespace Dali;
120
121 BaseHandle Create()
122 {
123   return BaseHandle();
124 }
125
126 TypeRegistration mType( typeid(Toolkit::ScrollBar), typeid(Toolkit::Control), Create );
127
128 }
129
130 ScrollBar::ScrollBar()
131 : mScrollStart(0.0f),
132   mIsPanning(false),
133   mCurrentScrollPosition(0.0f)
134 {
135 }
136
137 ScrollBar::~ScrollBar()
138 {
139 }
140
141 void ScrollBar::OnInitialize()
142 {
143   Actor self = Self();
144
145   Image indicatorImage = Image::New( DEFAULT_INDICATOR_IMAGE_PATH );
146   mIndicator = ImageActor::New( indicatorImage );
147   mIndicator.SetNinePatchBorder( DEFAULT_INDICATOR_NINE_PATCH_BORDER );
148   mIndicator.SetStyle( ImageActor::STYLE_NINE_PATCH );
149   mIndicator.SetParentOrigin( ParentOrigin::TOP_LEFT );
150   mIndicator.SetAnchorPoint( AnchorPoint::TOP_LEFT );
151   self.Add(mIndicator);
152
153   self.SetDrawMode(DrawMode::OVERLAY);
154
155   // Enable the pan gesture which is attached to the control
156   EnableGestureDetection(Gesture::Type(Gesture::Pan));
157 }
158
159 void ScrollBar::OnScrollConnectorSet( Toolkit::ScrollConnector oldConnector )
160 {
161   if( oldConnector )
162   {
163     oldConnector.DomainChangedSignal().Disconnect(this, &ScrollBar::OnScrollDomainChanged);
164
165     mScrollPositionObject.Reset();
166   }
167
168   if( mScrollConnector )
169   {
170     mScrollPositionObject = mScrollConnector.GetScrollPositionObject();
171
172     ApplyConstraints();
173     mScrollConnector.DomainChangedSignal().Connect(this, &ScrollBar::OnScrollDomainChanged);
174   }
175 }
176
177 void ScrollBar::SetBackgroundImage( Image image, const Vector4& border )
178 {
179   if (!mBackground )
180   {
181     mBackground = ImageActor::New( image );
182     mBackground.SetParentOrigin( ParentOrigin::TOP_LEFT );
183     mBackground.SetAnchorPoint( AnchorPoint::TOP_LEFT );
184     Self().Add(mBackground);
185   }
186   else
187   {
188     mBackground.SetImage(image);
189   }
190
191   mBackground.SetNinePatchBorder( border );
192   mBackground.SetStyle( ImageActor::STYLE_NINE_PATCH );
193 }
194
195 void ScrollBar::SetIndicatorImage( Image image, const Vector4& border )
196 {
197   mIndicator.SetImage(image);
198   mIndicator.SetNinePatchBorder( border );
199   mIndicator.SetStyle( ImageActor::STYLE_NINE_PATCH );
200 }
201
202 Actor ScrollBar::GetScrollIndicator()
203 {
204   return mIndicator;
205 }
206
207 void ScrollBar::ApplyConstraints()
208 {
209   mIndicator.RemoveConstraints();
210
211   Constraint constraint = Constraint::New<Vector3>( Actor::SIZE,
212                                                     ParentSource( Actor::SIZE ),
213                                                     IndicatorSizeConstraint( mScrollConnector.GetContentLength() ) );
214   mIndicator.ApplyConstraint( constraint );
215
216   constraint = Constraint::New<Vector3>( Actor::POSITION,
217                                          LocalSource( Actor::SIZE ),
218                                          ParentSource( Actor::SIZE ),
219                                          Source( mScrollPositionObject, Toolkit::ScrollConnector::SCROLL_POSITION ),
220                                          IndicatorPositionConstraint( mScrollConnector.GetMinLimit(), mScrollConnector.GetMaxLimit() ) );
221   mIndicator.ApplyConstraint( constraint );
222
223   if( mBackground )
224   {
225     mBackground.RemoveConstraints();
226
227     constraint = Constraint::New<Vector3>(Actor::SIZE,
228                                           ParentSource(Actor::SIZE),
229                                           EqualToConstraint());
230     mBackground.ApplyConstraint(constraint);
231   }
232 }
233
234 void ScrollBar::SetPositionNotifications( const std::vector<float>& positions )
235 {
236   if(mScrollPositionObject)
237   {
238     if(mPositionNotification)
239     {
240       mScrollPositionObject.RemovePropertyNotification(mPositionNotification);
241     }
242     mPositionNotification = mScrollPositionObject.AddPropertyNotification( Toolkit::ScrollConnector::SCROLL_POSITION, VariableStepCondition(positions) );
243     mPositionNotification.NotifySignal().Connect( this, &ScrollBar::OnScrollPositionNotified );
244   }
245 }
246
247 void ScrollBar::OnScrollPositionNotified(PropertyNotification& source)
248 {
249   // Emit the signal to notify the scroll position crossing
250   mScrollPositionNotifiedSignal.Emit(mScrollPositionObject.GetProperty<float>( Toolkit::ScrollConnector::SCROLL_POSITION ));
251 }
252
253 void ScrollBar::Show()
254 {
255   // Cancel any animation
256   if(mAnimation)
257   {
258     mAnimation.Clear();
259     mAnimation.Reset();
260   }
261
262   mAnimation = Animation::New( INDICATOR_SHOW_TIME );
263   mAnimation.OpacityTo( Self(), 1.0f, AlphaFunctions::EaseIn );
264   mAnimation.Play();
265 }
266
267 void ScrollBar::Hide()
268 {
269   // Cancel any animation
270   if(mAnimation)
271   {
272     mAnimation.Clear();
273     mAnimation.Reset();
274   }
275
276   mAnimation = Animation::New( INDICATOR_HIDE_TIME );
277   mAnimation.OpacityTo( Self(), 0.0f, AlphaFunctions::EaseIn );
278   mAnimation.Play();
279 }
280
281 bool ScrollBar::OnPanGestureProcessTick()
282 {
283   // Update the scroll position property.
284   mScrollPositionObject.SetProperty( Toolkit::ScrollConnector::SCROLL_POSITION, mCurrentScrollPosition );
285
286   Dali::Toolkit::ItemView itemView = Dali::Toolkit::ItemView::DownCast(Self().GetParent());
287   if(itemView)
288   {
289     // Refresh ItemView immediately when the scroll position is changed.
290     GetImpl(itemView).DoRefresh(mCurrentScrollPosition, false); // No need to cache extra items.
291   }
292
293   return true;
294 }
295
296 void ScrollBar::OnPan( PanGesture gesture )
297 {
298   if(mScrollPositionObject)
299   {
300     switch(gesture.state)
301     {
302       case Gesture::Started:
303       {
304         if( !mTimer )
305         {
306           // Make sure the pan gesture is only being processed once per frame.
307           mTimer = Timer::New( DEFAULT_PAN_GESTURE_PROCESS_TIME );
308           mTimer.TickSignal().Connect( this, &ScrollBar::OnPanGestureProcessTick );
309           mTimer.Start();
310         }
311
312         Show();
313         mScrollStart = mScrollPositionObject.GetProperty<float>( Toolkit::ScrollConnector::SCROLL_POSITION );
314         mGestureDisplacement = Vector3::ZERO;
315         mIsPanning = true;
316
317         break;
318       }
319       case Gesture::Continuing:
320       {
321         Vector3 delta(gesture.displacement.x, gesture.displacement.y, 0.0f);
322         mGestureDisplacement+=delta;
323
324         Vector3 span = Self().GetCurrentSize() - mIndicator.GetCurrentSize();
325         const float domainSize = fabs(mScrollConnector.GetMaxLimit() - mScrollConnector.GetMinLimit());
326         mCurrentScrollPosition = mScrollStart - mGestureDisplacement.y * domainSize / span.y;
327         mCurrentScrollPosition = std::min(mScrollConnector.GetMaxLimit(), std::max(mCurrentScrollPosition, mScrollConnector.GetMinLimit()));
328
329         break;
330       }
331       default:
332       {
333         mIsPanning = false;
334
335         if( mTimer )
336         {
337           // Destroy the timer when pan gesture is finished.
338           mTimer.Stop();
339           mTimer.TickSignal().Disconnect( this, &ScrollBar::OnPanGestureProcessTick );
340           mTimer.Reset();
341         }
342
343         break;
344       }
345     }
346
347     Dali::Toolkit::ItemView itemView = Dali::Toolkit::ItemView::DownCast(Self().GetParent());
348     if(itemView)
349     {
350       // Disable automatic refresh in ItemView during fast scrolling
351       GetImpl(itemView).SetRefreshEnabled(!mIsPanning);
352     }
353   }
354 }
355
356 void ScrollBar::OnScrollDomainChanged(float minPosition, float maxPosition, float contentSize)
357 {
358   // Reapply constraints when the scroll domain is changed
359   ApplyConstraints();
360 }
361
362 Toolkit::ScrollBar ScrollBar::New()
363 {
364   // Create the implementation, temporarily owned by this handle on stack
365   IntrusivePtr< ScrollBar > impl = new ScrollBar();
366
367   // Pass ownership to CustomActor handle
368   Toolkit::ScrollBar handle( *impl );
369
370   // Second-phase init of the implementation
371   // This can only be done after the CustomActor connection has been made...
372   impl->Initialize();
373
374   return handle;
375 }
376
377 } // namespace Internal
378
379 } // namespace Toolkit
380
381 } // namespace Dali