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