Conversion to Apache 2.0 license
[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(mScrollPositionObject.GetProperty<float>( Toolkit::ScrollConnector::SCROLL_POSITION ));
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   mScrollPositionObject.SetProperty( Toolkit::ScrollConnector::SCROLL_POSITION, mCurrentScrollPosition );
322
323   Dali::Toolkit::ItemView itemView = Dali::Toolkit::ItemView::DownCast(Self().GetParent());
324   if(itemView)
325   {
326     // Refresh ItemView immediately when the scroll position is changed.
327     GetImpl(itemView).DoRefresh(mCurrentScrollPosition, false); // No need to cache extra items.
328   }
329
330   return true;
331 }
332
333 void ScrollBar::OnPan( PanGesture gesture )
334 {
335   if(mScrollPositionObject)
336   {
337     switch(gesture.state)
338     {
339       case Gesture::Started:
340       {
341         if( !mTimer )
342         {
343           // Make sure the pan gesture is only being processed once per frame.
344           mTimer = Timer::New( DEFAULT_PAN_GESTURE_PROCESS_TIME );
345           mTimer.TickSignal().Connect( this, &ScrollBar::OnPanGestureProcessTick );
346           mTimer.Start();
347         }
348
349         Show();
350         mScrollStart = mScrollPositionObject.GetProperty<float>( Toolkit::ScrollConnector::SCROLL_POSITION );
351         mGestureDisplacement = Vector3::ZERO;
352         mIsPanning = true;
353
354         break;
355       }
356       case Gesture::Continuing:
357       {
358         Vector3 delta(gesture.displacement.x, gesture.displacement.y, 0.0f);
359         mGestureDisplacement+=delta;
360
361         Vector3 span = Self().GetCurrentSize() - mIndicator.GetCurrentSize();
362         const float domainSize = fabs(mScrollConnector.GetMaxLimit() - mScrollConnector.GetMinLimit());
363         mCurrentScrollPosition = mScrollStart - mGestureDisplacement.y * domainSize / span.y;
364         mCurrentScrollPosition = std::min(mScrollConnector.GetMaxLimit(), std::max(mCurrentScrollPosition, mScrollConnector.GetMinLimit()));
365
366         break;
367       }
368       default:
369       {
370         mIsPanning = false;
371
372         if( mTimer )
373         {
374           // Destroy the timer when pan gesture is finished.
375           mTimer.Stop();
376           mTimer.TickSignal().Disconnect( this, &ScrollBar::OnPanGestureProcessTick );
377           mTimer.Reset();
378         }
379
380         break;
381       }
382     }
383
384     Dali::Toolkit::ItemView itemView = Dali::Toolkit::ItemView::DownCast(Self().GetParent());
385     if(itemView)
386     {
387       // Disable automatic refresh in ItemView during fast scrolling
388       GetImpl(itemView).SetRefreshEnabled(!mIsPanning);
389     }
390   }
391 }
392
393 void ScrollBar::OnScrollDomainChanged(float minPosition, float maxPosition, float contentSize)
394 {
395   // Reapply constraints when the scroll domain is changed
396   ApplyConstraints();
397 }
398
399 void ScrollBar::SetIndicatorHeightPolicy( Toolkit::ScrollBar::IndicatorHeightPolicy policy )
400 {
401   mIndicatorHeightPolicy = policy;
402   ApplyConstraints();
403 }
404
405 Toolkit::ScrollBar::IndicatorHeightPolicy ScrollBar::GetIndicatorHeightPolicy()
406 {
407   return mIndicatorHeightPolicy;
408 }
409
410 void ScrollBar::SetIndicatorFixedHeight( float height )
411 {
412   mIndicatorFixedHeight = height;
413   ApplyConstraints();
414 }
415
416 float ScrollBar::GetIndicatorFixedHeight()
417 {
418   return mIndicatorFixedHeight;
419 }
420
421 void ScrollBar::OnIndicatorHeightPolicyPropertySet( Property::Value propertyValue )
422 {
423   std::string policyName( propertyValue.Get<std::string>() );
424   if(policyName == "Variable")
425   {
426     SetIndicatorHeightPolicy(Toolkit::ScrollBar::Variable);
427   }
428   else if(policyName == "Fixed")
429   {
430     SetIndicatorHeightPolicy(Toolkit::ScrollBar::Fixed);
431   }
432   else
433   {
434     DALI_ASSERT_ALWAYS( !"ScrollBar::OnIndicatorHeightPolicyPropertySet(). Invalid Property value." );
435   }
436 }
437
438 void ScrollBar::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
439 {
440   Toolkit::ScrollBar scrollBar = Toolkit::ScrollBar::DownCast( Dali::BaseHandle( object ) );
441
442   if( scrollBar )
443   {
444     ScrollBar& scrollBarImpl( GetImpl( scrollBar ) );
445     switch( index )
446     {
447       case Toolkit::ScrollBar::PROPERTY_INDICATOR_HEIGHT_POLICY:
448       {
449         scrollBarImpl.OnIndicatorHeightPolicyPropertySet( value );
450         break;
451       }
452       case Toolkit::ScrollBar::PROPERTY_INDICATOR_FIXED_HEIGHT:
453       {
454         scrollBarImpl.SetIndicatorFixedHeight(value.Get<float>());
455         break;
456       }
457     }
458   }
459 }
460
461 Property::Value ScrollBar::GetProperty( BaseObject* object, Property::Index index )
462 {
463   Property::Value value;
464
465   Toolkit::ScrollBar scrollBar = Toolkit::ScrollBar::DownCast( Dali::BaseHandle( object ) );
466
467   if( scrollBar )
468   {
469     ScrollBar& scrollBarImpl( GetImpl( scrollBar ) );
470     switch( index )
471     {
472       case Toolkit::ScrollBar::PROPERTY_INDICATOR_HEIGHT_POLICY:
473       {
474         value = INDICATOR_HEIGHT_POLICY_NAME[ scrollBarImpl.GetIndicatorHeightPolicy() ];
475         break;
476       }
477       case Toolkit::ScrollBar::PROPERTY_INDICATOR_FIXED_HEIGHT:
478       {
479         value = scrollBarImpl.GetIndicatorFixedHeight();
480         break;
481       }
482     }
483   }
484   return value;
485 }
486
487 Toolkit::ScrollBar ScrollBar::New()
488 {
489   // Create the implementation, temporarily owned by this handle on stack
490   IntrusivePtr< ScrollBar > impl = new ScrollBar();
491
492   // Pass ownership to CustomActor handle
493   Toolkit::ScrollBar handle( *impl );
494
495   // Second-phase init of the implementation
496   // This can only be done after the CustomActor connection has been made...
497   impl->Initialize();
498
499   return handle;
500 }
501
502 } // namespace Internal
503
504 } // namespace Toolkit
505
506 } // namespace Dali