[dali_1.0.8] Merge branch 'tizen'
[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 DEFAULT_INDICATOR_SHOW_DURATION(0.5f);
31 const float DEFAULT_INDICATOR_HIDE_DURATION(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 const Property::Index ScrollBar::PROPERTY_INDICATOR_SHOW_DURATION( Internal::ScrollBar::SCROLLBAR_PROPERTY_START_INDEX + 2 );
119 const Property::Index ScrollBar::PROPERTY_INDICATOR_HIDE_DURATION( Internal::ScrollBar::SCROLLBAR_PROPERTY_START_INDEX + 3 );
120
121 namespace Internal
122 {
123
124 namespace
125 {
126
127 using namespace Dali;
128
129 const char* INDICATOR_HEIGHT_POLICY_NAME[] = {"Variable", "Fixed"};
130
131 BaseHandle Create()
132 {
133   return Toolkit::ScrollBar::New();
134 }
135
136 TypeRegistration typeRegistration( typeid(Toolkit::ScrollBar), typeid(Toolkit::ScrollComponent), Create );
137
138 PropertyRegistration property1( typeRegistration, "indicator-height-policy", Toolkit::ScrollBar::PROPERTY_INDICATOR_HEIGHT_POLICY, Property::STRING, &ScrollBar::SetProperty, &ScrollBar::GetProperty );
139 PropertyRegistration property2( typeRegistration, "indicator-fixed-height",  Toolkit::ScrollBar::PROPERTY_INDICATOR_FIXED_HEIGHT,  Property::FLOAT,  &ScrollBar::SetProperty, &ScrollBar::GetProperty );
140 PropertyRegistration property3( typeRegistration, "indicator-show-duration",  Toolkit::ScrollBar::PROPERTY_INDICATOR_SHOW_DURATION,  Property::FLOAT,  &ScrollBar::SetProperty, &ScrollBar::GetProperty );
141 PropertyRegistration property4( typeRegistration, "indicator-hide-duration",  Toolkit::ScrollBar::PROPERTY_INDICATOR_HIDE_DURATION,  Property::FLOAT,  &ScrollBar::SetProperty, &ScrollBar::GetProperty );
142 }
143
144 ScrollBar::ScrollBar()
145 : mIndicatorShowDuration(DEFAULT_INDICATOR_SHOW_DURATION),
146   mIndicatorHideDuration(DEFAULT_INDICATOR_HIDE_DURATION),
147   mScrollStart(0.0f),
148   mIsPanning(false),
149   mCurrentScrollPosition(0.0f),
150   mIndicatorHeightPolicy(Toolkit::ScrollBar::Variable),
151   mIndicatorFixedHeight(DEFAULT_INDICATOR_FIXED_HEIGHT)
152 {
153 }
154
155 ScrollBar::~ScrollBar()
156 {
157 }
158
159 void ScrollBar::OnInitialize()
160 {
161   Actor self = Self();
162
163   Image indicatorImage = Image::New( DEFAULT_INDICATOR_IMAGE_PATH );
164   mIndicator = ImageActor::New( indicatorImage );
165   mIndicator.SetNinePatchBorder( DEFAULT_INDICATOR_NINE_PATCH_BORDER );
166   mIndicator.SetStyle( ImageActor::STYLE_NINE_PATCH );
167   mIndicator.SetParentOrigin( ParentOrigin::TOP_LEFT );
168   mIndicator.SetAnchorPoint( AnchorPoint::TOP_LEFT );
169   self.Add(mIndicator);
170
171   self.SetDrawMode(DrawMode::OVERLAY);
172
173   // Enable the pan gesture which is attached to the control
174   EnableGestureDetection(Gesture::Type(Gesture::Pan));
175 }
176
177 void ScrollBar::OnScrollConnectorSet( Toolkit::ScrollConnector oldConnector )
178 {
179   if( oldConnector )
180   {
181     oldConnector.DomainChangedSignal().Disconnect(this, &ScrollBar::OnScrollDomainChanged);
182
183     mScrollPositionObject.Reset();
184   }
185
186   if( mScrollConnector )
187   {
188     mScrollPositionObject = mScrollConnector.GetScrollPositionObject();
189
190     ApplyConstraints();
191     mScrollConnector.DomainChangedSignal().Connect(this, &ScrollBar::OnScrollDomainChanged);
192   }
193 }
194
195 void ScrollBar::SetIndicatorImage( Image image )
196 {
197   mIndicator.SetImage(image);
198 }
199
200 Actor ScrollBar::GetScrollIndicator()
201 {
202   return mIndicator;
203 }
204
205 void ScrollBar::ApplyConstraints()
206 {
207   if( mScrollConnector )
208   {
209     Constraint constraint;
210
211     if(mIndicatorSizeConstraint)
212     {
213       mIndicator.RemoveConstraint(mIndicatorSizeConstraint);
214     }
215
216     // Set indicator height according to the indicator's height policy
217     if(mIndicatorHeightPolicy == Toolkit::ScrollBar::Fixed)
218     {
219       mIndicator.SetSize(Self().GetCurrentSize().width, mIndicatorFixedHeight);
220     }
221     else
222     {
223       constraint = Constraint::New<Vector3>( Actor::SIZE,
224                                              ParentSource( Actor::SIZE ),
225                                              IndicatorSizeConstraint( mScrollConnector.GetContentLength() ) );
226       mIndicatorSizeConstraint = mIndicator.ApplyConstraint( constraint );
227     }
228
229     if(mIndicatorPositionConstraint)
230     {
231       mIndicator.RemoveConstraint(mIndicatorPositionConstraint);
232     }
233
234     constraint = Constraint::New<Vector3>( Actor::POSITION,
235                                            LocalSource( Actor::SIZE ),
236                                            ParentSource( Actor::SIZE ),
237                                            Source( mScrollPositionObject, Toolkit::ScrollConnector::SCROLL_POSITION ),
238                                            IndicatorPositionConstraint( mScrollConnector.GetMinLimit(), mScrollConnector.GetMaxLimit() ) );
239     mIndicatorPositionConstraint = mIndicator.ApplyConstraint( constraint );
240
241     if( mBackground )
242     {
243       mBackground.RemoveConstraints();
244
245       constraint = Constraint::New<Vector3>(Actor::SIZE,
246                                             ParentSource(Actor::SIZE),
247                                             EqualToConstraint());
248       mBackground.ApplyConstraint(constraint);
249     }
250   }
251 }
252
253 void ScrollBar::SetPositionNotifications( const std::vector<float>& positions )
254 {
255   if(mScrollPositionObject)
256   {
257     if(mPositionNotification)
258     {
259       mScrollPositionObject.RemovePropertyNotification(mPositionNotification);
260     }
261     mPositionNotification = mScrollPositionObject.AddPropertyNotification( Toolkit::ScrollConnector::SCROLL_POSITION, VariableStepCondition(positions) );
262     mPositionNotification.NotifySignal().Connect( this, &ScrollBar::OnScrollPositionNotified );
263   }
264 }
265
266 void ScrollBar::OnScrollPositionNotified(PropertyNotification& source)
267 {
268   // Emit the signal to notify the scroll position crossing
269   mScrollPositionNotifiedSignal.Emit(mScrollConnector.GetScrollPosition());
270 }
271
272 void ScrollBar::Show()
273 {
274   // Cancel any animation
275   if(mAnimation)
276   {
277     mAnimation.Clear();
278     mAnimation.Reset();
279   }
280
281   if(mIndicatorShowDuration > 0.0f)
282   {
283     mAnimation = Animation::New( mIndicatorShowDuration );
284     mAnimation.OpacityTo( Self(), 1.0f, AlphaFunctions::EaseIn );
285     mAnimation.Play();
286   }
287   else
288   {
289     Self().SetOpacity(1.0f);
290   }
291 }
292
293 void ScrollBar::Hide()
294 {
295   // Cancel any animation
296   if(mAnimation)
297   {
298     mAnimation.Clear();
299     mAnimation.Reset();
300   }
301
302   if(mIndicatorHideDuration > 0.0f)
303   {
304     mAnimation = Animation::New( mIndicatorHideDuration );
305     mAnimation.OpacityTo( Self(), 0.0f, AlphaFunctions::EaseIn );
306     mAnimation.Play();
307   }
308   else
309   {
310     Self().SetOpacity(0.0f);
311   }
312 }
313
314 bool ScrollBar::OnPanGestureProcessTick()
315 {
316   // Update the scroll position property.
317   if( mScrollConnector )
318   {
319     mScrollConnector.SetScrollPosition(mCurrentScrollPosition);
320   }
321
322   return true;
323 }
324
325 void ScrollBar::OnPan( PanGesture gesture )
326 {
327   if(mScrollConnector)
328   {
329     Dali::Toolkit::ItemView itemView = Dali::Toolkit::ItemView::DownCast(Self().GetParent());
330
331     switch(gesture.state)
332     {
333       case Gesture::Started:
334       {
335         if( !mTimer )
336         {
337           // Make sure the pan gesture is only being processed once per frame.
338           mTimer = Timer::New( DEFAULT_PAN_GESTURE_PROCESS_TIME );
339           mTimer.TickSignal().Connect( this, &ScrollBar::OnPanGestureProcessTick );
340           mTimer.Start();
341         }
342
343         Show();
344         mScrollStart = mScrollConnector.GetScrollPosition();
345         mGestureDisplacement = Vector3::ZERO;
346         mIsPanning = true;
347
348         break;
349       }
350       case Gesture::Continuing:
351       {
352         Vector3 delta(gesture.displacement.x, gesture.displacement.y, 0.0f);
353         mGestureDisplacement+=delta;
354
355         Vector3 span = Self().GetCurrentSize() - mIndicator.GetCurrentSize();
356         const float domainSize = fabs(mScrollConnector.GetMaxLimit() - mScrollConnector.GetMinLimit());
357         mCurrentScrollPosition = mScrollStart - mGestureDisplacement.y * domainSize / span.y;
358         mCurrentScrollPosition = std::min(mScrollConnector.GetMaxLimit(), std::max(mCurrentScrollPosition, mScrollConnector.GetMinLimit()));
359
360         break;
361       }
362       default:
363       {
364         mIsPanning = false;
365
366         if( mTimer )
367         {
368           // Destroy the timer when pan gesture is finished.
369           mTimer.Stop();
370           mTimer.TickSignal().Disconnect( this, &ScrollBar::OnPanGestureProcessTick );
371           mTimer.Reset();
372         }
373
374         if(itemView)
375         {
376           // Refresh the ItemView cache with extra items
377           GetImpl(itemView).DoRefresh(mCurrentScrollPosition, true);
378         }
379
380         break;
381       }
382     }
383
384     if(itemView)
385     {
386       // Disable automatic refresh in ItemView during fast scrolling
387       GetImpl(itemView).SetRefreshEnabled(!mIsPanning);
388     }
389   }
390 }
391
392 void ScrollBar::OnScrollDomainChanged(float minPosition, float maxPosition, float contentSize)
393 {
394   // Reapply constraints when the scroll domain is changed
395   ApplyConstraints();
396 }
397
398 void ScrollBar::SetIndicatorHeightPolicy( Toolkit::ScrollBar::IndicatorHeightPolicy policy )
399 {
400   mIndicatorHeightPolicy = policy;
401   ApplyConstraints();
402 }
403
404 Toolkit::ScrollBar::IndicatorHeightPolicy ScrollBar::GetIndicatorHeightPolicy()
405 {
406   return mIndicatorHeightPolicy;
407 }
408
409 void ScrollBar::SetIndicatorFixedHeight( float height )
410 {
411   mIndicatorFixedHeight = height;
412   ApplyConstraints();
413 }
414
415 float ScrollBar::GetIndicatorFixedHeight()
416 {
417   return mIndicatorFixedHeight;
418 }
419
420 void ScrollBar::SetIndicatorShowDuration( float durationSeconds )
421 {
422   mIndicatorShowDuration = durationSeconds;
423 }
424
425 float ScrollBar::GetIndicatorShowDuration()
426 {
427   return mIndicatorShowDuration;
428 }
429
430 void ScrollBar::SetIndicatorHideDuration( float durationSeconds )
431 {
432   mIndicatorHideDuration = durationSeconds;
433 }
434
435 float ScrollBar::GetIndicatorHideDuration()
436 {
437   return mIndicatorHideDuration;
438 }
439
440 void ScrollBar::OnIndicatorHeightPolicyPropertySet( Property::Value propertyValue )
441 {
442   std::string policyName( propertyValue.Get<std::string>() );
443   if(policyName == "Variable")
444   {
445     SetIndicatorHeightPolicy(Toolkit::ScrollBar::Variable);
446   }
447   else if(policyName == "Fixed")
448   {
449     SetIndicatorHeightPolicy(Toolkit::ScrollBar::Fixed);
450   }
451   else
452   {
453     DALI_ASSERT_ALWAYS( !"ScrollBar::OnIndicatorHeightPolicyPropertySet(). Invalid Property value." );
454   }
455 }
456
457 void ScrollBar::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
458 {
459   Toolkit::ScrollBar scrollBar = Toolkit::ScrollBar::DownCast( Dali::BaseHandle( object ) );
460
461   if( scrollBar )
462   {
463     ScrollBar& scrollBarImpl( GetImpl( scrollBar ) );
464     switch( index )
465     {
466       case Toolkit::ScrollBar::PROPERTY_INDICATOR_HEIGHT_POLICY:
467       {
468         scrollBarImpl.OnIndicatorHeightPolicyPropertySet( value );
469         break;
470       }
471       case Toolkit::ScrollBar::PROPERTY_INDICATOR_FIXED_HEIGHT:
472       {
473         scrollBarImpl.SetIndicatorFixedHeight(value.Get<float>());
474         break;
475       }
476       case Toolkit::ScrollBar::PROPERTY_INDICATOR_SHOW_DURATION:
477       {
478         scrollBarImpl.SetIndicatorShowDuration(value.Get<float>());
479         break;
480       }
481       case Toolkit::ScrollBar::PROPERTY_INDICATOR_HIDE_DURATION:
482       {
483         scrollBarImpl.SetIndicatorHideDuration(value.Get<float>());
484         break;
485       }
486     }
487   }
488 }
489
490 Property::Value ScrollBar::GetProperty( BaseObject* object, Property::Index index )
491 {
492   Property::Value value;
493
494   Toolkit::ScrollBar scrollBar = Toolkit::ScrollBar::DownCast( Dali::BaseHandle( object ) );
495
496   if( scrollBar )
497   {
498     ScrollBar& scrollBarImpl( GetImpl( scrollBar ) );
499     switch( index )
500     {
501       case Toolkit::ScrollBar::PROPERTY_INDICATOR_HEIGHT_POLICY:
502       {
503         value = INDICATOR_HEIGHT_POLICY_NAME[ scrollBarImpl.GetIndicatorHeightPolicy() ];
504         break;
505       }
506       case Toolkit::ScrollBar::PROPERTY_INDICATOR_FIXED_HEIGHT:
507       {
508         value = scrollBarImpl.GetIndicatorFixedHeight();
509         break;
510       }
511       case Toolkit::ScrollBar::PROPERTY_INDICATOR_SHOW_DURATION:
512       {
513         value = scrollBarImpl.GetIndicatorShowDuration();
514         break;
515       }
516       case Toolkit::ScrollBar::PROPERTY_INDICATOR_HIDE_DURATION:
517       {
518         value = scrollBarImpl.GetIndicatorHideDuration();
519         break;
520       }
521     }
522   }
523   return value;
524 }
525
526 Toolkit::ScrollBar ScrollBar::New()
527 {
528   // Create the implementation, temporarily owned by this handle on stack
529   IntrusivePtr< ScrollBar > impl = new ScrollBar();
530
531   // Pass ownership to CustomActor handle
532   Toolkit::ScrollBar handle( *impl );
533
534   // Second-phase init of the implementation
535   // This can only be done after the CustomActor connection has been made...
536   impl->Initialize();
537
538   return handle;
539 }
540
541 } // namespace Internal
542
543 } // namespace Toolkit
544
545 } // namespace Dali