Prevent fighting of setting scroll position property by ItemView and ScrollBar
[platform/core/uifw/dali-toolkit.git] / base / dali-toolkit / internal / controls / scroll-bar / scroll-bar-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 #include <dali-toolkit/internal/controls/scroll-bar/scroll-bar-impl.h>
19 #include <dali-toolkit/internal/controls/scrollable/item-view/item-view-impl.h>
20
21 using namespace Dali;
22
23 namespace
24 {
25
26 const char* DEFAULT_INDICATOR_IMAGE_PATH = DALI_IMAGE_DIR "popup_scroll.png";
27 const Vector4 DEFAULT_INDICATOR_NINE_PATCH_BORDER(4.0f, 9.0f, 7.0f, 11.0f);
28 const float MINIMUM_INDICATOR_HEIGHT(20.0f); // The minimum indicator height for the nine patch border
29 const float DEFAULT_SLIDER_DEPTH(1.0f);
30 const float INDICATOR_SHOW_TIME(0.5f);
31 const float INDICATOR_HIDE_TIME(0.5f);
32 const float DEFAULT_PAN_GESTURE_PROCESS_TIME(16.7f); // 16.7 milliseconds, i.e. one frame
33 const float DEFAULT_INDICATOR_FIXED_HEIGHT(80.0f);
34
35 /**
36  * Indicator size constraint
37  * Indicator size depends on both indicator's parent size and the scroll content size
38  */
39 struct IndicatorSizeConstraint
40 {
41   /**
42    * @param[in] contentSize The size of scrollable content
43    */
44   IndicatorSizeConstraint(float contentSize)
45   : mContentSize(contentSize)
46   {
47   }
48
49   /**
50    * Constraint operator
51    * @param[in] current The current indicator size
52    * @param[in] parentSizeProperty The parent size of scroll indicator.
53    * @return The new scroll indicator size.
54    */
55   Vector3 operator()(const Vector3& current,
56                      const PropertyInput& parentSizeProperty)
57   {
58     const Vector3& parentSize = parentSizeProperty.GetVector3();
59     float height = mContentSize > parentSize.height ? parentSize.height * ( parentSize.height / mContentSize ) : parentSize.height * ( (parentSize.height - mContentSize * 0.5f) / parentSize.height);
60     return Vector3( parentSize.width, std::max(MINIMUM_INDICATOR_HEIGHT, height), parentSize.depth );
61   }
62
63   float mContentSize;  ///< The size of scrollable content
64 };
65
66 /**
67  * Indicator position constraint
68  * Positions the indicator to reflect the current scroll position within the scroll domain.
69  */
70 struct IndicatorPositionConstraint
71 {
72   /**
73    * @param[in] minPosition The minimum limit of scroll position
74    * @param[in] maxPosition the maximum limit of scroll position
75    */
76   IndicatorPositionConstraint(float minPosition, float maxPosition)
77   : mMinPosition(minPosition),
78     mMaxPosition(maxPosition)
79   {
80   }
81
82   /**
83    * Constraint operator
84    * @param[in] current The current indicator position
85    * @param[in] indicatorSizeProperty The size of indicator.
86    * @param[in] parentSizeProperty The parent size of indicator.
87    * @param[in] scrollPositionProperty The scroll position of the scrollable container // (from 0.0 -> 1.0 in each axis)
88    * @return The new indicator position is returned.
89    */
90   Vector3 operator()(const Vector3& current,
91                      const PropertyInput& indicatorSizeProperty,
92                      const PropertyInput& parentSizeProperty,
93                      const PropertyInput& scrollPositionProperty)
94   {
95     Vector3 indicatorSize = indicatorSizeProperty.GetVector3();
96     Vector3 parentSize = parentSizeProperty.GetVector3();
97     float scrollPosition = scrollPositionProperty.GetFloat();
98
99     const float domainSize = fabs(mMaxPosition - mMinPosition);
100     float relativePosition = (mMaxPosition - scrollPosition) / domainSize;
101     return Vector3(current.x, relativePosition * (parentSize.height - indicatorSize.height), DEFAULT_SLIDER_DEPTH);
102   }
103
104   float mMinPosition;  ///< The minimum scroll position
105   float mMaxPosition;  ///< The maximum scroll position
106 };
107
108 } // unnamed namespace
109
110 namespace Dali
111 {
112
113 namespace Toolkit
114 {
115
116 const Property::Index ScrollBar::PROPERTY_INDICATOR_HEIGHT_POLICY( Internal::ScrollBar::SCROLLBAR_PROPERTY_START_INDEX );
117 const Property::Index ScrollBar::PROPERTY_INDICATOR_FIXED_HEIGHT( Internal::ScrollBar::SCROLLBAR_PROPERTY_START_INDEX + 1 );
118
119 namespace Internal
120 {
121
122 namespace
123 {
124
125 using namespace Dali;
126
127 const char* INDICATOR_HEIGHT_POLICY_NAME[] = {"Variable", "Fixed"};
128
129 BaseHandle Create()
130 {
131   return Toolkit::ScrollBar::New();
132 }
133
134 TypeRegistration typeRegistration( typeid(Toolkit::ScrollBar), typeid(Toolkit::ScrollComponent), Create );
135
136 PropertyRegistration property1( typeRegistration, "indicator-height-policy", Toolkit::ScrollBar::PROPERTY_INDICATOR_HEIGHT_POLICY, Property::STRING, &ScrollBar::SetProperty, &ScrollBar::GetProperty );
137 PropertyRegistration property2( typeRegistration, "indicator-fixed-height",  Toolkit::ScrollBar::PROPERTY_INDICATOR_FIXED_HEIGHT,  Property::FLOAT,  &ScrollBar::SetProperty, &ScrollBar::GetProperty );
138 }
139
140 ScrollBar::ScrollBar()
141 : mScrollStart(0.0f),
142   mIsPanning(false),
143   mCurrentScrollPosition(0.0f),
144   mIndicatorHeightPolicy(Toolkit::ScrollBar::Variable),
145   mIndicatorFixedHeight(DEFAULT_INDICATOR_FIXED_HEIGHT)
146 {
147 }
148
149 ScrollBar::~ScrollBar()
150 {
151 }
152
153 void ScrollBar::OnInitialize()
154 {
155   Actor self = Self();
156
157   Image indicatorImage = Image::New( DEFAULT_INDICATOR_IMAGE_PATH );
158   mIndicator = ImageActor::New( indicatorImage );
159   mIndicator.SetNinePatchBorder( DEFAULT_INDICATOR_NINE_PATCH_BORDER );
160   mIndicator.SetStyle( ImageActor::STYLE_NINE_PATCH );
161   mIndicator.SetParentOrigin( ParentOrigin::TOP_LEFT );
162   mIndicator.SetAnchorPoint( AnchorPoint::TOP_LEFT );
163   self.Add(mIndicator);
164
165   self.SetDrawMode(DrawMode::OVERLAY);
166
167   // Enable the pan gesture which is attached to the control
168   EnableGestureDetection(Gesture::Type(Gesture::Pan));
169 }
170
171 void ScrollBar::OnScrollConnectorSet( Toolkit::ScrollConnector oldConnector )
172 {
173   if( oldConnector )
174   {
175     oldConnector.DomainChangedSignal().Disconnect(this, &ScrollBar::OnScrollDomainChanged);
176
177     mScrollPositionObject.Reset();
178   }
179
180   if( mScrollConnector )
181   {
182     mScrollPositionObject = mScrollConnector.GetScrollPositionObject();
183
184     ApplyConstraints();
185     mScrollConnector.DomainChangedSignal().Connect(this, &ScrollBar::OnScrollDomainChanged);
186   }
187 }
188
189 void ScrollBar::SetBackgroundImage( Image image, const Vector4& border )
190 {
191   if (!mBackground )
192   {
193     mBackground = ImageActor::New( image );
194     mBackground.SetParentOrigin( ParentOrigin::TOP_LEFT );
195     mBackground.SetAnchorPoint( AnchorPoint::TOP_LEFT );
196     Self().Add(mBackground);
197   }
198   else
199   {
200     mBackground.SetImage(image);
201   }
202   mBackground.SetNinePatchBorder( border );
203   mBackground.SetStyle( ImageActor::STYLE_NINE_PATCH );
204 }
205
206 void ScrollBar::SetIndicatorImage( Image image )
207 {
208   mIndicator.SetImage(image);
209 }
210
211 void ScrollBar::SetIndicatorImage( Image image, const Vector4& border )
212 {
213   mIndicator.SetImage(image);
214   mIndicator.SetNinePatchBorder( border );
215   mIndicator.SetStyle( ImageActor::STYLE_NINE_PATCH );
216 }
217
218 Actor ScrollBar::GetScrollIndicator()
219 {
220   return mIndicator;
221 }
222
223 void ScrollBar::ApplyConstraints()
224 {
225   if( mScrollConnector )
226   {
227     Constraint constraint;
228
229     if(mIndicatorSizeConstraint)
230     {
231       mIndicator.RemoveConstraint(mIndicatorSizeConstraint);
232     }
233
234     // Set indicator height according to the indicator's height policy
235     if(mIndicatorHeightPolicy == Toolkit::ScrollBar::Fixed)
236     {
237       mIndicator.SetSize(Self().GetCurrentSize().width, mIndicatorFixedHeight);
238     }
239     else
240     {
241       constraint = Constraint::New<Vector3>( Actor::SIZE,
242                                              ParentSource( Actor::SIZE ),
243                                              IndicatorSizeConstraint( mScrollConnector.GetContentLength() ) );
244       mIndicatorSizeConstraint = mIndicator.ApplyConstraint( constraint );
245     }
246
247     if(mIndicatorPositionConstraint)
248     {
249       mIndicator.RemoveConstraint(mIndicatorPositionConstraint);
250     }
251
252     constraint = Constraint::New<Vector3>( Actor::POSITION,
253                                            LocalSource( Actor::SIZE ),
254                                            ParentSource( Actor::SIZE ),
255                                            Source( mScrollPositionObject, Toolkit::ScrollConnector::SCROLL_POSITION ),
256                                            IndicatorPositionConstraint( mScrollConnector.GetMinLimit(), mScrollConnector.GetMaxLimit() ) );
257     mIndicatorPositionConstraint = mIndicator.ApplyConstraint( constraint );
258
259     if( mBackground )
260     {
261       mBackground.RemoveConstraints();
262
263       constraint = Constraint::New<Vector3>(Actor::SIZE,
264                                             ParentSource(Actor::SIZE),
265                                             EqualToConstraint());
266       mBackground.ApplyConstraint(constraint);
267     }
268   }
269 }
270
271 void ScrollBar::SetPositionNotifications( const std::vector<float>& positions )
272 {
273   if(mScrollPositionObject)
274   {
275     if(mPositionNotification)
276     {
277       mScrollPositionObject.RemovePropertyNotification(mPositionNotification);
278     }
279     mPositionNotification = mScrollPositionObject.AddPropertyNotification( Toolkit::ScrollConnector::SCROLL_POSITION, VariableStepCondition(positions) );
280     mPositionNotification.NotifySignal().Connect( this, &ScrollBar::OnScrollPositionNotified );
281   }
282 }
283
284 void ScrollBar::OnScrollPositionNotified(PropertyNotification& source)
285 {
286   // Emit the signal to notify the scroll position crossing
287   mScrollPositionNotifiedSignal.Emit(mScrollConnector.GetScrollPosition());
288 }
289
290 void ScrollBar::Show()
291 {
292   // Cancel any animation
293   if(mAnimation)
294   {
295     mAnimation.Clear();
296     mAnimation.Reset();
297   }
298
299   mAnimation = Animation::New( INDICATOR_SHOW_TIME );
300   mAnimation.OpacityTo( Self(), 1.0f, AlphaFunctions::EaseIn );
301   mAnimation.Play();
302 }
303
304 void ScrollBar::Hide()
305 {
306   // Cancel any animation
307   if(mAnimation)
308   {
309     mAnimation.Clear();
310     mAnimation.Reset();
311   }
312
313   mAnimation = Animation::New( INDICATOR_HIDE_TIME );
314   mAnimation.OpacityTo( Self(), 0.0f, AlphaFunctions::EaseIn );
315   mAnimation.Play();
316 }
317
318 bool ScrollBar::OnPanGestureProcessTick()
319 {
320   // Update the scroll position property.
321   if( mScrollConnector )
322   {
323     mScrollConnector.SetScrollPosition(mCurrentScrollPosition);
324   }
325
326   return true;
327 }
328
329 void ScrollBar::OnPan( PanGesture gesture )
330 {
331   if(mScrollConnector)
332   {
333     Dali::Toolkit::ItemView itemView = Dali::Toolkit::ItemView::DownCast(Self().GetParent());
334
335     switch(gesture.state)
336     {
337       case Gesture::Started:
338       {
339         if( !mTimer )
340         {
341           // Make sure the pan gesture is only being processed once per frame.
342           mTimer = Timer::New( DEFAULT_PAN_GESTURE_PROCESS_TIME );
343           mTimer.TickSignal().Connect( this, &ScrollBar::OnPanGestureProcessTick );
344           mTimer.Start();
345         }
346
347         Show();
348         mScrollStart = mScrollConnector.GetScrollPosition();
349         mGestureDisplacement = Vector3::ZERO;
350         mIsPanning = true;
351
352         break;
353       }
354       case Gesture::Continuing:
355       {
356         Vector3 delta(gesture.displacement.x, gesture.displacement.y, 0.0f);
357         mGestureDisplacement+=delta;
358
359         Vector3 span = Self().GetCurrentSize() - mIndicator.GetCurrentSize();
360         const float domainSize = fabs(mScrollConnector.GetMaxLimit() - mScrollConnector.GetMinLimit());
361         mCurrentScrollPosition = mScrollStart - mGestureDisplacement.y * domainSize / span.y;
362         mCurrentScrollPosition = std::min(mScrollConnector.GetMaxLimit(), std::max(mCurrentScrollPosition, mScrollConnector.GetMinLimit()));
363
364         break;
365       }
366       default:
367       {
368         mIsPanning = false;
369
370         if( mTimer )
371         {
372           // Destroy the timer when pan gesture is finished.
373           mTimer.Stop();
374           mTimer.TickSignal().Disconnect( this, &ScrollBar::OnPanGestureProcessTick );
375           mTimer.Reset();
376         }
377
378         if(itemView)
379         {
380           // Refresh the ItemView cache with extra items
381           GetImpl(itemView).DoRefresh(mCurrentScrollPosition, true);
382         }
383
384         break;
385       }
386     }
387
388     if(itemView)
389     {
390       // Disable automatic refresh in ItemView during fast scrolling
391       GetImpl(itemView).SetRefreshEnabled(!mIsPanning);
392     }
393   }
394 }
395
396 void ScrollBar::OnScrollDomainChanged(float minPosition, float maxPosition, float contentSize)
397 {
398   // Reapply constraints when the scroll domain is changed
399   ApplyConstraints();
400 }
401
402 void ScrollBar::SetIndicatorHeightPolicy( Toolkit::ScrollBar::IndicatorHeightPolicy policy )
403 {
404   mIndicatorHeightPolicy = policy;
405   ApplyConstraints();
406 }
407
408 Toolkit::ScrollBar::IndicatorHeightPolicy ScrollBar::GetIndicatorHeightPolicy()
409 {
410   return mIndicatorHeightPolicy;
411 }
412
413 void ScrollBar::SetIndicatorFixedHeight( float height )
414 {
415   mIndicatorFixedHeight = height;
416   ApplyConstraints();
417 }
418
419 float ScrollBar::GetIndicatorFixedHeight()
420 {
421   return mIndicatorFixedHeight;
422 }
423
424 void ScrollBar::OnIndicatorHeightPolicyPropertySet( Property::Value propertyValue )
425 {
426   std::string policyName( propertyValue.Get<std::string>() );
427   if(policyName == "Variable")
428   {
429     SetIndicatorHeightPolicy(Toolkit::ScrollBar::Variable);
430   }
431   else if(policyName == "Fixed")
432   {
433     SetIndicatorHeightPolicy(Toolkit::ScrollBar::Fixed);
434   }
435   else
436   {
437     DALI_ASSERT_ALWAYS( !"ScrollBar::OnIndicatorHeightPolicyPropertySet(). Invalid Property value." );
438   }
439 }
440
441 void ScrollBar::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
442 {
443   Toolkit::ScrollBar scrollBar = Toolkit::ScrollBar::DownCast( Dali::BaseHandle( object ) );
444
445   if( scrollBar )
446   {
447     ScrollBar& scrollBarImpl( GetImpl( scrollBar ) );
448     switch( index )
449     {
450       case Toolkit::ScrollBar::PROPERTY_INDICATOR_HEIGHT_POLICY:
451       {
452         scrollBarImpl.OnIndicatorHeightPolicyPropertySet( value );
453         break;
454       }
455       case Toolkit::ScrollBar::PROPERTY_INDICATOR_FIXED_HEIGHT:
456       {
457         scrollBarImpl.SetIndicatorFixedHeight(value.Get<float>());
458         break;
459       }
460     }
461   }
462 }
463
464 Property::Value ScrollBar::GetProperty( BaseObject* object, Property::Index index )
465 {
466   Property::Value value;
467
468   Toolkit::ScrollBar scrollBar = Toolkit::ScrollBar::DownCast( Dali::BaseHandle( object ) );
469
470   if( scrollBar )
471   {
472     ScrollBar& scrollBarImpl( GetImpl( scrollBar ) );
473     switch( index )
474     {
475       case Toolkit::ScrollBar::PROPERTY_INDICATOR_HEIGHT_POLICY:
476       {
477         value = INDICATOR_HEIGHT_POLICY_NAME[ scrollBarImpl.GetIndicatorHeightPolicy() ];
478         break;
479       }
480       case Toolkit::ScrollBar::PROPERTY_INDICATOR_FIXED_HEIGHT:
481       {
482         value = scrollBarImpl.GetIndicatorFixedHeight();
483         break;
484       }
485     }
486   }
487   return value;
488 }
489
490 Toolkit::ScrollBar ScrollBar::New()
491 {
492   // Create the implementation, temporarily owned by this handle on stack
493   IntrusivePtr< ScrollBar > impl = new ScrollBar();
494
495   // Pass ownership to CustomActor handle
496   Toolkit::ScrollBar handle( *impl );
497
498   // Second-phase init of the implementation
499   // This can only be done after the CustomActor connection has been made...
500   impl->Initialize();
501
502   return handle;
503 }
504
505 } // namespace Internal
506
507 } // namespace Toolkit
508
509 } // namespace Dali