Merge branch 'tizen' into devel/new_mesh
[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   // Cancel any animation
254   if(mAnimation)
255   {
256     mAnimation.Clear();
257     mAnimation.Reset();
258   }
259
260   if(mIndicatorShowDuration > 0.0f)
261   {
262     mAnimation = Animation::New( mIndicatorShowDuration );
263     mAnimation.OpacityTo( Self(), 1.0f, AlphaFunctions::EaseIn );
264     mAnimation.Play();
265   }
266   else
267   {
268     Self().SetOpacity(1.0f);
269   }
270 }
271
272 void ScrollBar::Hide()
273 {
274   // Cancel any animation
275   if(mAnimation)
276   {
277     mAnimation.Clear();
278     mAnimation.Reset();
279   }
280
281   if(mIndicatorHideDuration > 0.0f)
282   {
283     mAnimation = Animation::New( mIndicatorHideDuration );
284     mAnimation.OpacityTo( Self(), 0.0f, AlphaFunctions::EaseIn );
285     mAnimation.Play();
286   }
287   else
288   {
289     Self().SetOpacity(0.0f);
290   }
291 }
292
293 bool ScrollBar::OnPanGestureProcessTick()
294 {
295   // Update the scroll position property.
296   if( mScrollConnector )
297   {
298     mScrollConnector.SetScrollPosition(mCurrentScrollPosition);
299   }
300
301   return true;
302 }
303
304 void ScrollBar::OnPan( PanGesture gesture )
305 {
306   if(mScrollConnector)
307   {
308     Dali::Toolkit::ItemView itemView = Dali::Toolkit::ItemView::DownCast(Self().GetParent());
309
310     switch(gesture.state)
311     {
312       case Gesture::Started:
313       {
314         if( !mTimer )
315         {
316           // Make sure the pan gesture is only being processed once per frame.
317           mTimer = Timer::New( DEFAULT_PAN_GESTURE_PROCESS_TIME );
318           mTimer.TickSignal().Connect( this, &ScrollBar::OnPanGestureProcessTick );
319           mTimer.Start();
320         }
321
322         Show();
323         mScrollStart = mScrollConnector.GetScrollPosition();
324         mGestureDisplacement = Vector3::ZERO;
325         mIsPanning = true;
326
327         break;
328       }
329       case Gesture::Continuing:
330       {
331         Vector3 delta(gesture.displacement.x, gesture.displacement.y, 0.0f);
332         mGestureDisplacement+=delta;
333
334         Vector3 span = Self().GetCurrentSize() - mIndicator.GetCurrentSize();
335         const float domainSize = fabs(mScrollConnector.GetMaxLimit() - mScrollConnector.GetMinLimit());
336         mCurrentScrollPosition = mScrollStart - mGestureDisplacement.y * domainSize / span.y;
337         mCurrentScrollPosition = std::min(mScrollConnector.GetMaxLimit(), std::max(mCurrentScrollPosition, mScrollConnector.GetMinLimit()));
338
339         break;
340       }
341       default:
342       {
343         mIsPanning = false;
344
345         if( mTimer )
346         {
347           // Destroy the timer when pan gesture is finished.
348           mTimer.Stop();
349           mTimer.TickSignal().Disconnect( this, &ScrollBar::OnPanGestureProcessTick );
350           mTimer.Reset();
351         }
352
353         if(itemView)
354         {
355           // Refresh the ItemView cache with extra items
356           GetImpl(itemView).DoRefresh(mCurrentScrollPosition, true);
357         }
358
359         break;
360       }
361     }
362
363     if(itemView)
364     {
365       // Disable automatic refresh in ItemView during fast scrolling
366       GetImpl(itemView).SetRefreshEnabled(!mIsPanning);
367     }
368   }
369 }
370
371 void ScrollBar::OnControlSizeSet( const Vector3& size )
372 {
373   if(mIndicatorHeightPolicy != Toolkit::ScrollBar::Fixed && mScrollConnector)
374   {
375     mIndicator.SetSize( IndicatorSize( size, mScrollConnector.GetContentLength() ) );
376   }
377 }
378
379 void ScrollBar::OnScrollDomainChanged(float minPosition, float maxPosition, float contentSize)
380 {
381   // Reapply constraints when the scroll domain is changed
382   ApplyConstraints();
383 }
384
385 void ScrollBar::SetIndicatorHeightPolicy( Toolkit::ScrollBar::IndicatorHeightPolicy policy )
386 {
387   mIndicatorHeightPolicy = policy;
388   ApplyConstraints();
389 }
390
391 Toolkit::ScrollBar::IndicatorHeightPolicy ScrollBar::GetIndicatorHeightPolicy()
392 {
393   return mIndicatorHeightPolicy;
394 }
395
396 void ScrollBar::SetIndicatorFixedHeight( float height )
397 {
398   mIndicatorFixedHeight = height;
399   ApplyConstraints();
400 }
401
402 float ScrollBar::GetIndicatorFixedHeight()
403 {
404   return mIndicatorFixedHeight;
405 }
406
407 void ScrollBar::SetIndicatorShowDuration( float durationSeconds )
408 {
409   mIndicatorShowDuration = durationSeconds;
410 }
411
412 float ScrollBar::GetIndicatorShowDuration()
413 {
414   return mIndicatorShowDuration;
415 }
416
417 void ScrollBar::SetIndicatorHideDuration( float durationSeconds )
418 {
419   mIndicatorHideDuration = durationSeconds;
420 }
421
422 float ScrollBar::GetIndicatorHideDuration()
423 {
424   return mIndicatorHideDuration;
425 }
426
427 void ScrollBar::OnIndicatorHeightPolicyPropertySet( Property::Value propertyValue )
428 {
429   std::string policyName( propertyValue.Get<std::string>() );
430   if(policyName == "Variable")
431   {
432     SetIndicatorHeightPolicy(Toolkit::ScrollBar::Variable);
433   }
434   else if(policyName == "Fixed")
435   {
436     SetIndicatorHeightPolicy(Toolkit::ScrollBar::Fixed);
437   }
438   else
439   {
440     DALI_ASSERT_ALWAYS( !"ScrollBar::OnIndicatorHeightPolicyPropertySet(). Invalid Property value." );
441   }
442 }
443
444 bool ScrollBar::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
445 {
446   Dali::BaseHandle handle( object );
447
448   bool connected( true );
449   Toolkit::ScrollBar scrollBar = Toolkit::ScrollBar::DownCast( handle );
450
451   if( 0 == strcmp( signalName.c_str(), SCROLL_POSITION_NOTIFIED_SIGNAL ) )
452   {
453     scrollBar.ScrollPositionNotifiedSignal().Connect( tracker, functor );
454   }
455   else
456   {
457     // signalName does not match any signal
458     connected = false;
459   }
460
461   return connected;
462 }
463
464 void ScrollBar::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
465 {
466   Toolkit::ScrollBar scrollBar = Toolkit::ScrollBar::DownCast( Dali::BaseHandle( object ) );
467
468   if( scrollBar )
469   {
470     ScrollBar& scrollBarImpl( GetImpl( scrollBar ) );
471     switch( index )
472     {
473       case Toolkit::ScrollBar::Property::INDICATOR_HEIGHT_POLICY:
474       {
475         scrollBarImpl.OnIndicatorHeightPolicyPropertySet( value );
476         break;
477       }
478       case Toolkit::ScrollBar::Property::INDICATOR_FIXED_HEIGHT:
479       {
480         scrollBarImpl.SetIndicatorFixedHeight(value.Get<float>());
481         break;
482       }
483       case Toolkit::ScrollBar::Property::INDICATOR_SHOW_DURATION:
484       {
485         scrollBarImpl.SetIndicatorShowDuration(value.Get<float>());
486         break;
487       }
488       case Toolkit::ScrollBar::Property::INDICATOR_HIDE_DURATION:
489       {
490         scrollBarImpl.SetIndicatorHideDuration(value.Get<float>());
491         break;
492       }
493     }
494   }
495 }
496
497 Property::Value ScrollBar::GetProperty( BaseObject* object, Property::Index index )
498 {
499   Property::Value value;
500
501   Toolkit::ScrollBar scrollBar = Toolkit::ScrollBar::DownCast( Dali::BaseHandle( object ) );
502
503   if( scrollBar )
504   {
505     ScrollBar& scrollBarImpl( GetImpl( scrollBar ) );
506     switch( index )
507     {
508       case Toolkit::ScrollBar::Property::INDICATOR_HEIGHT_POLICY:
509       {
510         value = INDICATOR_HEIGHT_POLICY_NAME[ scrollBarImpl.GetIndicatorHeightPolicy() ];
511         break;
512       }
513       case Toolkit::ScrollBar::Property::INDICATOR_FIXED_HEIGHT:
514       {
515         value = scrollBarImpl.GetIndicatorFixedHeight();
516         break;
517       }
518       case Toolkit::ScrollBar::Property::INDICATOR_SHOW_DURATION:
519       {
520         value = scrollBarImpl.GetIndicatorShowDuration();
521         break;
522       }
523       case Toolkit::ScrollBar::Property::INDICATOR_HIDE_DURATION:
524       {
525         value = scrollBarImpl.GetIndicatorHideDuration();
526         break;
527       }
528     }
529   }
530   return value;
531 }
532
533 Toolkit::ScrollBar ScrollBar::New()
534 {
535   // Create the implementation, temporarily owned by this handle on stack
536   IntrusivePtr< ScrollBar > impl = new ScrollBar();
537
538   // Pass ownership to CustomActor handle
539   Toolkit::ScrollBar handle( *impl );
540
541   // Second-phase init of the implementation
542   // This can only be done after the CustomActor connection has been made...
543   impl->Initialize();
544
545   return handle;
546 }
547
548 } // namespace Internal
549
550 } // namespace Toolkit
551
552 } // namespace Dali