bf377512e4da1a9252e1f8deb52c3a71c9514ca9
[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(0.0f, 12.0f, 14.0f, 14.0f);
28 const float DEFAULT_SLIDER_DEPTH(1.0f);
29 const float INDICATOR_SHOW_TIME(0.5f);
30 const float INDICATOR_HIDE_TIME(0.5f);
31 const float DEFAULT_PAN_GESTURE_PROCESS_TIME(16.7f); // 16.7 milliseconds, i.e. one frame
32
33 /**
34  * Indicator size constraint
35  * Indicator size depends on both indicator's parent size and the scroll content size
36  */
37 struct IndicatorSizeConstraint
38 {
39   /**
40    * @param[in] contentSize The size of scrollable content
41    */
42   IndicatorSizeConstraint(float contentSize)
43   : mContentSize(contentSize)
44   {
45   }
46
47   /**
48    * Constraint operator
49    * @param[in] current The current indicator size
50    * @param[in] parentSizeProperty The parent size of scroll indicator.
51    * @return The new scroll indicator size.
52    */
53   Vector3 operator()(const Vector3& current,
54                      const PropertyInput& parentSizeProperty)
55   {
56     const Vector3& parentSize = parentSizeProperty.GetVector3();
57     float height = mContentSize > parentSize.height ? parentSize.height * ( parentSize.height / mContentSize ) : parentSize.height * ( (parentSize.height - mContentSize * 0.5f) / parentSize.height);
58     return Vector3( parentSize.width, height, parentSize.depth );
59   }
60
61   float mContentSize;  ///< The size of scrollable content
62 };
63
64 /**
65  * Indicator position constraint
66  * Positions the indicator to reflect the current scroll position within the scroll domain.
67  */
68 struct IndicatorPositionConstraint
69 {
70   /**
71    * @param[in] minPosition The minimum limit of scroll position
72    * @param[in] maxPosition the maximum limit of scroll position
73    */
74   IndicatorPositionConstraint(float minPosition, float maxPosition)
75   : mMinPosition(minPosition),
76     mMaxPosition(maxPosition)
77   {
78   }
79
80   /**
81    * Constraint operator
82    * @param[in] current The current indicator position
83    * @param[in] indicatorSizeProperty The size of indicator.
84    * @param[in] parentSizeProperty The parent size of indicator.
85    * @param[in] scrollPositionProperty The scroll position of the scrollable container // (from 0.0 -> 1.0 in each axis)
86    * @return The new indicator position is returned.
87    */
88   Vector3 operator()(const Vector3& current,
89                      const PropertyInput& indicatorSizeProperty,
90                      const PropertyInput& parentSizeProperty,
91                      const PropertyInput& scrollPositionProperty)
92   {
93     Vector3 indicatorSize = indicatorSizeProperty.GetVector3();
94     Vector3 parentSize = parentSizeProperty.GetVector3();
95     float scrollPosition = scrollPositionProperty.GetFloat();
96
97     const float domainSize = fabs(mMaxPosition - mMinPosition);
98     float relativePosition = (mMaxPosition - scrollPosition) / domainSize;
99     return Vector3(current.x, relativePosition * (parentSize.height - indicatorSize.height), DEFAULT_SLIDER_DEPTH);
100   }
101
102   float mMinPosition;  ///< The minimum scroll position
103   float mMaxPosition;  ///< The maximum scroll position
104 };
105
106 } // unnamed namespace
107
108 namespace Dali
109 {
110
111 namespace Toolkit
112 {
113
114 namespace Internal
115 {
116
117 namespace
118 {
119
120 using namespace Dali;
121
122 BaseHandle Create()
123 {
124   return BaseHandle();
125 }
126
127 TypeRegistration mType( typeid(Toolkit::ScrollBar), typeid(Toolkit::Control), Create );
128
129 }
130
131 ScrollBar::ScrollBar()
132 : mScrollStart(0.0f),
133   mIsPanning(false),
134   mCurrentScrollPosition(0.0f)
135 {
136 }
137
138 ScrollBar::~ScrollBar()
139 {
140 }
141
142 void ScrollBar::OnInitialize()
143 {
144   Actor self = Self();
145
146   Image indicatorImage = Image::New( DEFAULT_INDICATOR_IMAGE_PATH );
147   mIndicator = ImageActor::New( indicatorImage );
148   mIndicator.SetNinePatchBorder( DEFAULT_INDICATOR_NINE_PATCH_BORDER );
149   mIndicator.SetStyle( ImageActor::STYLE_NINE_PATCH );
150   mIndicator.SetParentOrigin( ParentOrigin::TOP_LEFT );
151   mIndicator.SetAnchorPoint( AnchorPoint::TOP_LEFT );
152   self.Add(mIndicator);
153
154   self.SetDrawMode(DrawMode::OVERLAY);
155
156   // Enable the pan gesture which is attached to the control
157   EnableGestureDetection(Gesture::Type(Gesture::Pan));
158 }
159
160 void ScrollBar::OnScrollConnectorSet( Toolkit::ScrollConnector oldConnector )
161 {
162   if( oldConnector )
163   {
164     oldConnector.DomainChangedSignal().Disconnect(this, &ScrollBar::OnScrollDomainChanged);
165
166     mScrollPositionObject.Reset();
167   }
168
169   if( mScrollConnector )
170   {
171     mScrollPositionObject = mScrollConnector.GetScrollPositionObject();
172
173     ApplyConstraints();
174     mScrollConnector.DomainChangedSignal().Connect(this, &ScrollBar::OnScrollDomainChanged);
175   }
176 }
177
178 void ScrollBar::SetBackgroundImage( Image image, const Vector4& border )
179 {
180   if (!mBackground )
181   {
182     mBackground = ImageActor::New( image );
183     mBackground.SetParentOrigin( ParentOrigin::TOP_LEFT );
184     mBackground.SetAnchorPoint( AnchorPoint::TOP_LEFT );
185     Self().Add(mBackground);
186   }
187   else
188   {
189     mBackground.SetImage(image);
190   }
191
192   mBackground.SetNinePatchBorder( border );
193   mBackground.SetStyle( ImageActor::STYLE_NINE_PATCH );
194 }
195
196 void ScrollBar::SetIndicatorImage( Image image, const Vector4& border )
197 {
198   mIndicator.SetImage(image);
199   mIndicator.SetNinePatchBorder( border );
200   mIndicator.SetStyle( ImageActor::STYLE_NINE_PATCH );
201 }
202
203 Actor ScrollBar::GetScrollIndicator()
204 {
205   return mIndicator;
206 }
207
208 void ScrollBar::ApplyConstraints()
209 {
210   mIndicator.RemoveConstraints();
211
212   Constraint constraint = Constraint::New<Vector3>( Actor::SIZE,
213                                                     ParentSource( Actor::SIZE ),
214                                                     IndicatorSizeConstraint( mScrollConnector.GetContentLength() ) );
215   mIndicator.ApplyConstraint( constraint );
216
217   constraint = Constraint::New<Vector3>( Actor::POSITION,
218                                          LocalSource( Actor::SIZE ),
219                                          ParentSource( Actor::SIZE ),
220                                          Source( mScrollPositionObject, Toolkit::ScrollConnector::SCROLL_POSITION ),
221                                          IndicatorPositionConstraint( mScrollConnector.GetMinLimit(), mScrollConnector.GetMaxLimit() ) );
222   mIndicator.ApplyConstraint( constraint );
223
224   if( mBackground )
225   {
226     mBackground.RemoveConstraints();
227
228     constraint = Constraint::New<Vector3>(Actor::SIZE,
229                                           ParentSource(Actor::SIZE),
230                                           EqualToConstraint());
231     mBackground.ApplyConstraint(constraint);
232   }
233 }
234
235 void ScrollBar::SetPositionNotifications( const std::vector<float>& positions )
236 {
237   if(mScrollPositionObject)
238   {
239     if(mPositionNotification)
240     {
241       mScrollPositionObject.RemovePropertyNotification(mPositionNotification);
242     }
243     mPositionNotification = mScrollPositionObject.AddPropertyNotification( Toolkit::ScrollConnector::SCROLL_POSITION, VariableStepCondition(positions) );
244     mPositionNotification.NotifySignal().Connect( this, &ScrollBar::OnScrollPositionNotified );
245   }
246 }
247
248 void ScrollBar::OnScrollPositionNotified(PropertyNotification& source)
249 {
250   // Emit the signal to notify the scroll position crossing
251   mScrollPositionNotifiedSignal.Emit(mScrollPositionObject.GetProperty<float>( Toolkit::ScrollConnector::SCROLL_POSITION ));
252 }
253
254 void ScrollBar::Show()
255 {
256   // Cancel any animation
257   if(mAnimation)
258   {
259     mAnimation.Clear();
260     mAnimation.Reset();
261   }
262
263   mAnimation = Animation::New( INDICATOR_SHOW_TIME );
264   mAnimation.OpacityTo( Self(), 1.0f, AlphaFunctions::EaseIn );
265   mAnimation.Play();
266 }
267
268 void ScrollBar::Hide()
269 {
270   // Cancel any animation
271   if(mAnimation)
272   {
273     mAnimation.Clear();
274     mAnimation.Reset();
275   }
276
277   mAnimation = Animation::New( INDICATOR_HIDE_TIME );
278   mAnimation.OpacityTo( Self(), 0.0f, AlphaFunctions::EaseIn );
279   mAnimation.Play();
280 }
281
282 bool ScrollBar::OnPanGestureProcessTick()
283 {
284   // Update the scroll position property.
285   mScrollPositionObject.SetProperty( Toolkit::ScrollConnector::SCROLL_POSITION, mCurrentScrollPosition );
286
287   Dali::Toolkit::ItemView itemView = Dali::Toolkit::ItemView::DownCast(Self().GetParent());
288   if(itemView)
289   {
290     // Refresh ItemView immediately when the scroll position is changed.
291     GetImpl(itemView).DoRefresh(mCurrentScrollPosition, false); // No need to cache extra items.
292   }
293
294   return true;
295 }
296
297 void ScrollBar::OnPan( PanGesture gesture )
298 {
299   if(mScrollPositionObject)
300   {
301     switch(gesture.state)
302     {
303       case Gesture::Started:
304       {
305         if( !mTimer )
306         {
307           // Make sure the pan gesture is only being processed once per frame.
308           mTimer = Timer::New( DEFAULT_PAN_GESTURE_PROCESS_TIME );
309           mTimer.TickSignal().Connect( this, &ScrollBar::OnPanGestureProcessTick );
310           mTimer.Start();
311         }
312
313         Show();
314         mScrollStart = mScrollPositionObject.GetProperty<float>( Toolkit::ScrollConnector::SCROLL_POSITION );
315         mGestureDisplacement = Vector3::ZERO;
316         mIsPanning = true;
317
318         break;
319       }
320       case Gesture::Continuing:
321       {
322         Vector3 delta(gesture.displacement.x, gesture.displacement.y, 0.0f);
323         mGestureDisplacement+=delta;
324
325         Vector3 span = Self().GetCurrentSize() - mIndicator.GetCurrentSize();
326         const float domainSize = fabs(mScrollConnector.GetMaxLimit() - mScrollConnector.GetMinLimit());
327         mCurrentScrollPosition = mScrollStart - mGestureDisplacement.y * domainSize / span.y;
328         mCurrentScrollPosition = std::min(mScrollConnector.GetMaxLimit(), std::max(mCurrentScrollPosition, mScrollConnector.GetMinLimit()));
329
330         break;
331       }
332       default:
333       {
334         mIsPanning = false;
335
336         if( mTimer )
337         {
338           // Destroy the timer when pan gesture is finished.
339           mTimer.Stop();
340           mTimer.TickSignal().Disconnect( this, &ScrollBar::OnPanGestureProcessTick );
341           mTimer.Reset();
342         }
343
344         break;
345       }
346     }
347
348     Dali::Toolkit::ItemView itemView = Dali::Toolkit::ItemView::DownCast(Self().GetParent());
349     if(itemView)
350     {
351       // Disable automatic refresh in ItemView during fast scrolling
352       GetImpl(itemView).SetRefreshEnabled(!mIsPanning);
353     }
354   }
355 }
356
357 void ScrollBar::OnScrollDomainChanged(float minPosition, float maxPosition, float contentSize)
358 {
359   // Reapply constraints when the scroll domain is changed
360   ApplyConstraints();
361 }
362
363 Toolkit::ScrollBar ScrollBar::New()
364 {
365   // Create the implementation, temporarily owned by this handle on stack
366   IntrusivePtr< ScrollBar > impl = new ScrollBar();
367
368   // Pass ownership to CustomActor handle
369   Toolkit::ScrollBar handle( *impl );
370
371   // Second-phase init of the implementation
372   // This can only be done after the CustomActor connection has been made...
373   impl->Initialize();
374
375   return handle;
376 }
377
378 } // namespace Internal
379
380 } // namespace Toolkit
381
382 } // namespace Dali