Revert "BloomView & GaussianBlurView demo (for verification purpose only )"
[platform/core/uifw/dali-demo.git] / examples / magnifier / magnifier-example.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 // EXTERNAL INCLUDES
19
20 // INTERNAL INCLUDES
21 #include "../shared/view.h"
22
23 #include <dali-toolkit/dali-toolkit.h>
24
25 using namespace Dali;
26
27 namespace
28 {
29 const char* BACKGROUND_IMAGE( DALI_IMAGE_DIR "background-magnifier.jpg" );
30 const char* TOOLBAR_IMAGE( DALI_IMAGE_DIR "top-bar.png" );
31 const char* APPLICATION_TITLE( "Magnifier Example" );
32 const Vector3 MAGNIFIER_SIZE(0.25f, 0.25f, 0.0f);       ///< Magnifier sides should be 25% of the width of the stage
33 const float ANIMATION_DURATION(60.0f);                  ///< Run animation for a minute before repeating.
34 const float MAGNIFIER_DISPLAY_DURATION(0.125f);         ///< Duration in seconds for show/hide manual magnifier animation
35
36 const float MAGNIFICATION_FACTOR(2.0f);                 ///< Amount to magnify by.
37 const float MAGNIFIER_INDENT(10.0f);                    ///< Indentation around edge of stage to define where magnifiers may move.
38 const float FINGER_RADIUS_INCHES(0.25f);                ///< Average finger radius in inches from the center of index finger to edge.
39
40 /**
41  * MagnifierPathConstraint
42  * This constraint governs the position of the
43  * animating magnifier in a swirly pattern around
44  * the stage.
45  */
46 struct MagnifierPathConstraint
47 {
48   /**
49    * Constraint constructor
50    * @param[in] stageSize The stage size so that the constraint can create a path
51    * within stage bounds.
52    */
53   MagnifierPathConstraint(const Vector3& stageSize,
54                           Vector3 offset = Vector3::ZERO)
55   : mStageSize(stageSize),
56     mOffset(offset)
57   {
58   }
59
60   Vector3 operator()(const Vector3&    current,
61                      const PropertyInput& sizeProperty,
62                      const PropertyInput& animationTimeProperty)
63   {
64     float time = animationTimeProperty.GetFloat();
65     const Vector3& size = sizeProperty.GetVector3();
66
67     Vector3 range(mStageSize - size - Vector3::ONE * MAGNIFIER_INDENT * 2.0f);
68     Vector3 position(mOffset);
69
70     position.x += 0.5f * sinf(time * 0.471f) * range.width;
71     position.y += 0.5f * sinf(time * 0.8739f) * range.height;
72
73     return position;
74   }
75
76   Vector3 mStageSize;     ///< Keep track of the stage size for determining path within stage bounds
77   Vector3 mOffset;        ///< Amount to offset magnifier path
78 };
79
80 /**
81  * Confine Actor to boundaries of reference actor (e.g. Parent)
82  * Actor bounds (top-left position + size) are confined to reference Actor's
83  * bounds.
84  */
85 struct ConfinementConstraint
86 {
87   /**
88    * Confinement constraint constructor.
89    * @param[in] offsetOrigin (optional) Whether to offset the parent origin or not.
90    * @param[in] topLeftMargin (optional) Top-Left margins (defaults to 0.0f, 0.0f)
91    * @param[in] bottomRightMargin (optional) Bottom-Right margins (defaults to 0.0f, 0.0f)
92    * @param[in] flipHorizontal (optional) whether to flip Actor to the other side X if near edge, and by
93    * how much (defaults to 0.0f i.e. no flip)
94    * @param[in] flipVertical (optional) whether to flip Actor to the other side Y if near edge, and by
95    * how much (defaults to 0.0f i.e. no flip)
96    */
97   ConfinementConstraint(Vector3 offsetOrigin = Vector3::ZERO, Vector2 topLeftMargin = Vector2::ZERO, Vector2 bottomRightMargin = Vector2::ZERO, bool flipHorizontal = false, bool flipVertical = false)
98   : mOffsetOrigin(offsetOrigin),
99     mMinIndent(topLeftMargin),
100     mMaxIndent(bottomRightMargin),
101     mFlipHorizontal(flipHorizontal),
102     mFlipVertical(flipVertical)
103   {
104   }
105
106   Vector3 operator()(const Vector3&    constPosition,
107                      const PropertyInput& sizeProperty,
108                      const PropertyInput& parentOriginProperty,
109                      const PropertyInput& anchorPointProperty,
110                      const PropertyInput& referenceSizeProperty)
111   {
112     const Vector3& size = sizeProperty.GetVector3();
113     const Vector3 origin = parentOriginProperty.GetVector3();
114     const Vector3& anchor = anchorPointProperty.GetVector3();
115     const Vector3& referenceSize = referenceSizeProperty.GetVector3();
116
117     Vector3 offset(mOffsetOrigin * referenceSize);
118
119     Vector3 newPosition( constPosition + offset );
120
121     // Get actual position of Actor relative to parent's Top-Left.
122     Vector3 position(constPosition + offset + origin * referenceSize);
123
124     // if top-left corner is outside of Top-Left bounds, then push back in screen.
125     Vector3 corner(position - size * anchor - mMinIndent);
126
127     if(mFlipHorizontal && corner.x < 0.0f)
128     {
129       corner.x = 0.0f;
130       newPosition.x += size.width;
131     }
132
133     if(mFlipVertical && corner.y < 0.0f)
134     {
135       corner.y = 0.0f;
136       newPosition.y += size.height;
137     }
138
139     newPosition.x -= std::min(corner.x, 0.0f);
140     newPosition.y -= std::min(corner.y, 0.0f);
141
142     // if bottom-right corner is outside of Bottom-Right bounds, then push back in screen.
143     corner += size - referenceSize + mMinIndent + mMaxIndent;
144
145     if(mFlipHorizontal && corner.x > 0.0f)
146     {
147       corner.x = 0.0f;
148       newPosition.x -= size.width;
149     }
150
151     if(mFlipVertical && corner.y > 0.0f)
152     {
153       corner.y = 0.0f;
154       newPosition.y -= size.height;
155     }
156
157     newPosition.x -= std::max(corner.x, 0.0f);
158     newPosition.y -= std::max(corner.y, 0.0f);
159
160     return newPosition;
161   }
162
163   Vector3 mOffsetOrigin;                                ///< Manual Parent Offset Origin.
164   Vector3 mMinIndent;                                   ///< Top-Left Margin
165   Vector3 mMaxIndent;                                   ///< Bottom-Right Margin.
166   bool mFlipHorizontal;                                 ///< Whether to flip actor's position if exceeds horizontal screen bounds
167   bool mFlipVertical;                                   ///< Whether to flip actor's position if exceeds vertical screen bounds
168 };
169
170 }
171
172 // This example shows how to use the Magnifier component.
173 //
174 class ExampleController : public ConnectionTracker
175 {
176 public:
177
178   /**
179    * The example controller constructor.
180    * @param[in] application The application instance
181    */
182   ExampleController( Application& application )
183   : mApplication( application ),
184     mView(),
185     mAnimationTime(0.0f),
186     mMagnifierShown(false)
187   {
188     // Connect to the Application's Init signal
189     mApplication.InitSignal().Connect( this, &ExampleController::Create );
190   }
191
192   /**
193    * The example controller destructor
194    */
195   ~ExampleController()
196   {
197     // Nothing to do here;
198   }
199
200   /**
201    * Invoked upon creation of application
202    * @param[in] application The application instance
203    */
204   void Create( Application& application )
205   {
206     Stage::GetCurrent().KeyEventSignal().Connect(this, &ExampleController::OnKeyEvent);
207
208     mStageSize = Stage::GetCurrent().GetSize();
209
210     // The Init signal is received once (only) during the Application lifetime
211
212     // Hide the indicator bar
213     application.GetWindow().ShowIndicator( Dali::Window::INVISIBLE );
214
215     // Creates a default view with a default tool bar.
216     // The view is added to the stage.
217     Toolkit::ToolBar toolBar;
218     mContent = DemoHelper::CreateView( application,
219                                        mView,
220                                        toolBar,
221                                        BACKGROUND_IMAGE,
222                                        TOOLBAR_IMAGE,
223                                        APPLICATION_TITLE );
224
225     mContent.SetLeaveRequired(true);
226     mContent.TouchedSignal().Connect( this, &ExampleController::OnTouched );
227
228     // Create magnifier (controlled by human touch)
229     Layer overlay = Layer::New();
230     overlay.SetSensitive(false);
231     overlay.SetParentOrigin( ParentOrigin::CENTER );
232     overlay.SetSize(mStageSize);
233     Stage::GetCurrent().Add(overlay);
234
235     mMagnifier = Toolkit::Magnifier::New();
236     mMagnifier.SetSourceActor( mView.GetBackgroundLayer() );
237     mMagnifier.SetSize( MAGNIFIER_SIZE * mStageSize.width );  // Size of magnifier is in relation to stage width
238     mMagnifier.SetMagnificationFactor( MAGNIFICATION_FACTOR );
239     mMagnifier.SetFrameVisibility(false);
240     mMagnifier.SetScale(Vector3::ZERO);
241     overlay.Add( mMagnifier );
242
243     // Apply constraint to animate the position of the magnifier.
244     Constraint constraint = Constraint::New<Vector3>(Actor::POSITION,
245                                                      LocalSource(Actor::SIZE),
246                                                      LocalSource(Actor::PARENT_ORIGIN),
247                                                      LocalSource(Actor::ANCHOR_POINT),
248                                                      ParentSource(Actor::SIZE),
249                                                      ConfinementConstraint(ParentOrigin::CENTER, Vector2::ONE * MAGNIFIER_INDENT, Vector2::ONE * MAGNIFIER_INDENT));
250     constraint.SetRemoveAction(Constraint::Discard);
251     mMagnifier.ApplyConstraint( constraint );
252
253     // Create bouncing magnifier automatically bounces around screen.
254     mBouncingMagnifier = Toolkit::Magnifier::New();
255     mBouncingMagnifier.SetSourceActor( mView.GetBackgroundLayer() );
256     mBouncingMagnifier.SetSize( MAGNIFIER_SIZE * mStageSize.width ); // Size of magnifier is in relation to stage width
257     mBouncingMagnifier.SetMagnificationFactor( MAGNIFICATION_FACTOR );
258     overlay.Add( mBouncingMagnifier );
259
260     mAnimationTimeProperty = mBouncingMagnifier.RegisterProperty("animation-time", 0.0f);
261     ContinueAnimation();
262
263     // Apply constraint to animate the position of the magnifier.
264     constraint = Constraint::New<Vector3>(Actor::POSITION,
265                                           LocalSource(Actor::SIZE),
266                                           LocalSource(mAnimationTimeProperty),
267                                           MagnifierPathConstraint(mStageSize, mStageSize * 0.5f));
268     mBouncingMagnifier.ApplyConstraint( constraint );
269
270     // Apply constraint to animate the source of the magnifier.
271     constraint = Constraint::New<Vector3>(mBouncingMagnifier.GetPropertyIndex( Toolkit::Magnifier::SOURCE_POSITION_PROPERTY_NAME ),
272                                           LocalSource(Actor::SIZE),
273                                           LocalSource(mAnimationTimeProperty),
274                                           MagnifierPathConstraint(mStageSize));
275     mBouncingMagnifier.ApplyConstraint( constraint );
276   }
277
278   /**
279    * Invoked whenever the animation finishes (every 60 seconds)
280    * @param[in] animation The animation
281    */
282   void OnAnimationFinished( Animation& animation )
283   {
284     animation.FinishedSignal().Disconnect(this, &ExampleController::OnAnimationFinished);
285     animation.Clear();
286     ContinueAnimation();
287   }
288
289   /**
290    * Resumes animation for another ANIMATION_DURATION seconds.
291    */
292   void ContinueAnimation()
293   {
294     Animation animation = Animation::New(ANIMATION_DURATION);
295     mAnimationTime += ANIMATION_DURATION;
296     animation.AnimateTo( Property(mBouncingMagnifier, mAnimationTimeProperty), mAnimationTime );
297     animation.Play();
298     animation.FinishedSignal().Connect(this, &ExampleController::OnAnimationFinished);
299   }
300
301   /**
302    * Invoked whenever the quit button is clicked
303    * @param[in] button the quit button
304    */
305   bool OnQuitButtonClicked( Toolkit::Button button )
306   {
307     // quit the application
308     mApplication.Quit();
309     return true;
310   }
311
312   /**
313    * Invoked whenever the content (screen) is touched
314    * @param[in] actor The actor that received the touch
315    * @param[in] event The touch-event information
316    */
317   bool OnTouched( Actor actor, const TouchEvent& event )
318   {
319     if(event.GetPointCount() > 0)
320     {
321       const TouchPoint& point = event.GetPoint(0);
322       switch(point.state)
323       {
324         case TouchPoint::Down:
325         case TouchPoint::Motion:
326         {
327           ShowMagnifier();
328           break;
329         }
330         case TouchPoint::Up:
331         case TouchPoint::Leave:
332         case TouchPoint::Interrupted:
333         {
334           HideMagnifier();
335           break;
336         }
337         default:
338         {
339           break;
340         }
341       } // end switch
342
343       Vector3 touchPoint(point.screen);
344
345       SetMagnifierPosition(touchPoint - mStageSize * 0.5f);
346     }
347
348     return false;
349   }
350
351   /**
352    * Shows the magnifier
353    */
354   void ShowMagnifier()
355   {
356     if(!mMagnifierShown)
357     {
358       Animation animation = Animation::New(MAGNIFIER_DISPLAY_DURATION);
359       animation.AnimateTo(Property(mMagnifier, Actor::SCALE), Vector3::ONE, AlphaFunctions::EaseIn);
360       animation.Play();
361       mMagnifierShown = true;
362     }
363   }
364
365   /**
366    * Hides the magnifier
367    */
368   void HideMagnifier()
369   {
370     if(mMagnifierShown)
371     {
372       Animation animation = Animation::New(MAGNIFIER_DISPLAY_DURATION);
373       animation.AnimateTo(Property(mMagnifier, Actor::SCALE), Vector3::ZERO, AlphaFunctions::EaseOut);
374       animation.Play();
375       mMagnifierShown = false;
376     }
377   }
378
379   /**
380    * Manually sets the magnifier position
381    * @param[in] position The magnifier's position relative to center of stage
382    */
383   void SetMagnifierPosition(const Vector3 position)
384   {
385     mMagnifier.SetSourcePosition( position );
386
387     // position magnifier glass such that bottom edge is touching/near top of finger.
388     Vector3 glassPosition(position);
389     glassPosition.y -= mStageSize.width * MAGNIFIER_SIZE.height * 0.5f + Stage::GetCurrent().GetDpi().height * FINGER_RADIUS_INCHES;
390
391     mMagnifier.SetPosition( glassPosition );
392   }
393
394   void OnKeyEvent(const KeyEvent& event)
395   {
396     if(event.state == KeyEvent::Down)
397     {
398       if( IsKey( event, Dali::DALI_KEY_ESCAPE) || IsKey( event, Dali::DALI_KEY_BACK) )
399       {
400         mApplication.Quit();
401       }
402     }
403   }
404
405 private:
406
407   Application&  mApplication;                             ///< Application instance
408   Toolkit::View mView;                                    ///< The view
409   Layer mContent;                                         ///< The content layer
410   Toolkit::Magnifier mMagnifier;                          ///< The manually controlled magnifier
411   Toolkit::Magnifier mBouncingMagnifier;                  ///< The animating magnifier (swirly animation)
412   Vector3 mStageSize;                                     ///< The size of the stage
413   float mAnimationTime;                                   ///< Keep track of start animation time.
414   Property::Index mAnimationTimeProperty;                 ///< Animation time property (responsible for swirly animation)
415   bool mMagnifierShown;                                   ///< Flag indicating whether the magnifier is being shown or not.
416
417 };
418
419 void RunTest( Application& application )
420 {
421   ExampleController test( application );
422
423   application.MainLoop();
424 }
425
426 // Entry point for Linux & SLP applications
427 //
428 int main( int argc, char **argv )
429 {
430   Application application = Application::New( &argc, &argv );
431
432   RunTest( application );
433
434   return 0;
435 }