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