Move new mesh API to devel-api.
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / public-api / controls / control-impl.cpp
1 /*
2  * Copyright (c) 2015 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/public-api/controls/control-impl.h>
20
21 // EXTERNAL INCLUDES
22 #include <cstring> // for strcmp
23 #include <limits>
24 #include <stack>
25 #include <dali/public-api/actors/image-actor.h>
26 #include <dali/public-api/animation/constraint.h>
27 #include <dali/public-api/animation/constraints.h>
28 #include <dali/public-api/object/type-registry.h>
29 #include <dali/public-api/size-negotiation/relayout-container.h>
30 #include <dali/devel-api/object/type-registry-helper.h>
31 #include <dali/devel-api/rendering/renderer.h>
32 #include <dali/devel-api/scripting/scripting.h>
33 #include <dali/integration-api/debug.h>
34
35 // INTERNAL INCLUDES
36 #include <dali-toolkit/public-api/controls/control-depth-index-ranges.h>
37 #include <dali-toolkit/devel-api/focus-manager/keyinput-focus-manager.h>
38 #include <dali-toolkit/public-api/focus-manager/keyboard-focus-manager.h>
39 #include <dali-toolkit/public-api/controls/control.h>
40 #include <dali-toolkit/devel-api/styling/style-manager.h>
41 #include <dali-toolkit/internal/styling/style-manager-impl.h>
42
43 namespace Dali
44 {
45
46 namespace Toolkit
47 {
48
49 namespace
50 {
51
52 /**
53  * Creates control through type registry
54  */
55 BaseHandle Create()
56 {
57   return Internal::Control::New();
58 }
59
60 /**
61  * Performs actions as requested using the action name.
62  * @param[in] object The object on which to perform the action.
63  * @param[in] actionName The action to perform.
64  * @param[in] attributes The attributes with which to perfrom this action.
65  * @return true if action has been accepted by this control
66  */
67 const char* ACTION_CONTROL_ACTIVATED = "control-activated";
68 static bool DoAction( BaseObject* object, const std::string& actionName, const Property::Map& attributes )
69 {
70   bool ret = false;
71
72   if( object && ( 0 == strcmp( actionName.c_str(), ACTION_CONTROL_ACTIVATED ) ) )
73   {
74     Toolkit::Control control = Toolkit::Control::DownCast( BaseHandle( object ) );
75     if( control )
76     {
77       // if cast succeeds there is an implementation so no need to check
78       ret = Internal::GetImplementation( control ).OnAccessibilityActivated();
79     }
80   }
81
82   return ret;
83 }
84
85 /**
86  * Connects a callback function with the object's signals.
87  * @param[in] object The object providing the signal.
88  * @param[in] tracker Used to disconnect the signal.
89  * @param[in] signalName The signal to connect to.
90  * @param[in] functor A newly allocated FunctorDelegate.
91  * @return True if the signal was connected.
92  * @post If a signal was connected, ownership of functor was passed to CallbackBase. Otherwise the caller is responsible for deleting the unused functor.
93  */
94 const char* SIGNAL_KEY_EVENT = "key-event";
95 const char* SIGNAL_KEY_INPUT_FOCUS_GAINED = "key-input-focus-gained";
96 const char* SIGNAL_KEY_INPUT_FOCUS_LOST = "key-input-focus-lost";
97 const char* SIGNAL_TAPPED = "tapped";
98 const char* SIGNAL_PANNED = "panned";
99 const char* SIGNAL_PINCHED = "pinched";
100 const char* SIGNAL_LONG_PRESSED = "long-pressed";
101 static bool DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
102 {
103   Dali::BaseHandle handle( object );
104
105   bool connected( false );
106   Toolkit::Control control = Toolkit::Control::DownCast( handle );
107   if ( control )
108   {
109     Internal::Control& controlImpl( Internal::GetImplementation( control ) );
110     connected = true;
111
112     if ( 0 == strcmp( signalName.c_str(), SIGNAL_KEY_EVENT ) )
113     {
114       controlImpl.KeyEventSignal().Connect( tracker, functor );
115     }
116     else if( 0 == strcmp( signalName.c_str(), SIGNAL_KEY_INPUT_FOCUS_GAINED ) )
117     {
118       controlImpl.KeyInputFocusGainedSignal().Connect( tracker, functor );
119     }
120     else if( 0 == strcmp( signalName.c_str(), SIGNAL_KEY_INPUT_FOCUS_LOST ) )
121     {
122       controlImpl.KeyInputFocusLostSignal().Connect( tracker, functor );
123     }
124     else if( 0 == strcmp( signalName.c_str(), SIGNAL_TAPPED ) )
125     {
126       controlImpl.EnableGestureDetection( Gesture::Tap );
127       controlImpl.GetTapGestureDetector().DetectedSignal().Connect( tracker, functor );
128     }
129     else if( 0 == strcmp( signalName.c_str(), SIGNAL_PANNED ) )
130     {
131       controlImpl.EnableGestureDetection( Gesture::Pan );
132       controlImpl.GetPanGestureDetector().DetectedSignal().Connect( tracker, functor );
133     }
134     else if( 0 == strcmp( signalName.c_str(), SIGNAL_PINCHED ) )
135     {
136       controlImpl.EnableGestureDetection( Gesture::Pinch );
137       controlImpl.GetPinchGestureDetector().DetectedSignal().Connect( tracker, functor );
138     }
139     else if( 0 == strcmp( signalName.c_str(), SIGNAL_LONG_PRESSED ) )
140     {
141       controlImpl.EnableGestureDetection( Gesture::LongPress );
142       controlImpl.GetLongPressGestureDetector().DetectedSignal().Connect( tracker, functor );
143     }
144   }
145   return connected;
146 }
147
148 // Setup signals and actions using the type-registry.
149 DALI_TYPE_REGISTRATION_BEGIN( Control, CustomActor, Create );
150
151 // Note: Properties are registered separately below.
152
153 SignalConnectorType registerSignal1( typeRegistration, SIGNAL_KEY_EVENT, &DoConnectSignal );
154 SignalConnectorType registerSignal2( typeRegistration, SIGNAL_KEY_INPUT_FOCUS_GAINED, &DoConnectSignal );
155 SignalConnectorType registerSignal3( typeRegistration, SIGNAL_KEY_INPUT_FOCUS_LOST, &DoConnectSignal );
156 SignalConnectorType registerSignal4( typeRegistration, SIGNAL_TAPPED, &DoConnectSignal );
157 SignalConnectorType registerSignal5( typeRegistration, SIGNAL_PANNED, &DoConnectSignal );
158 SignalConnectorType registerSignal6( typeRegistration, SIGNAL_PINCHED, &DoConnectSignal );
159 SignalConnectorType registerSignal7( typeRegistration, SIGNAL_LONG_PRESSED, &DoConnectSignal );
160
161 TypeAction registerAction( typeRegistration, ACTION_CONTROL_ACTIVATED, &DoAction );
162
163 DALI_TYPE_REGISTRATION_END()
164
165 /**
166  * Structure which holds information about the background of a control
167  */
168 struct Background
169 {
170   Actor actor;   ///< Background actor
171   Vector4 color; ///< The color of the actor.
172
173   /**
174    * Constructor
175    */
176   Background()
177   : actor(),
178     color( Color::WHITE )
179   {
180   }
181 };
182
183 unsigned int gQuadIndex[6] = { 0, 2, 1, 1, 2, 3 };
184
185 Vector2 gQuad[] = {
186                    Vector2( -0.5f, -0.5f ),
187                    Vector2(  0.5f, -0.5f ),
188                    Vector2( -0.5f,  0.5f ),
189                    Vector2(  0.5f,  0.5f )
190 };
191
192 struct VertexWithTexture
193 {
194   Vector2 position;
195   Vector2 texCoord;
196 };
197
198 VertexWithTexture gQuadWithTexture[] = {
199                                         { Vector2( -0.5f, -0.5f ), Vector2( 0.0f, 0.0f ) },
200                                         { Vector2(  0.5f, -0.5f ), Vector2( 1.0f, 0.0f ) },
201                                         { Vector2( -0.5f,  0.5f ), Vector2( 0.0f, 1.0f ) },
202                                         { Vector2(  0.5f,  0.5f ), Vector2( 1.0f, 1.0f ) }
203 };
204
205 const char* VERTEX_SHADER_COLOR = DALI_COMPOSE_SHADER(
206     attribute mediump vec2 aPosition;\n
207     uniform mediump mat4 uMvpMatrix;\n
208     void main()\n
209     {\n
210       gl_Position = uMvpMatrix * vec4( aPosition, 0.0, 1.0 );\n
211     }\n
212 );
213
214 const char* FRAGMENT_SHADER_COLOR = DALI_COMPOSE_SHADER(
215     uniform lowp vec4 uBackgroundColor;\n
216     uniform lowp vec4 uColor;\n
217     void main()\n
218     {\n
219       gl_FragColor = uBackgroundColor * uColor;\n
220     }\n
221 );
222
223 const char* VERTEX_SHADER_TEXTURE = DALI_COMPOSE_SHADER(
224     attribute mediump vec2 aPosition;\n
225     attribute mediump vec2 aTexCoord;\n
226     uniform mediump mat4 uMvpMatrix;\n
227     varying mediump vec2 vTexCoord;\n
228     void main()\n
229     {\n
230       gl_Position = uMvpMatrix * vec4( aPosition, 0.0, 1.0 );\n
231       vTexCoord = aTexCoord;\n
232     }\n
233 );
234
235 const char* FRAGMENT_SHADER_TEXTURE = DALI_COMPOSE_SHADER(
236     uniform lowp vec4 uBackgroundColor;\n
237     uniform lowp vec4 uColor;\n
238     uniform sampler2D sTexture;\n
239     varying mediump vec2 vTexCoord;\n
240
241     void main()\n
242     {\n
243       gl_FragColor = texture2D( sTexture, vTexCoord ) * uBackgroundColor * uColor;\n
244     }\n
245 );
246
247 /**
248  * @brief Create the background actor for the control.
249  *
250  * @param[in] actor The parent actor of the background
251  * @param[in] color The background color
252  * @param[in] image If a valid image is supplied this will be the texture used by the background
253  *
254  * @return An actor which will render the background
255  *
256  */
257 Actor CreateBackground( Actor parent, const Vector4& color, Image image = Image() )
258 {
259   PropertyBuffer vertexBuffer;
260   Shader shader;
261   Material material;
262   if( image )
263   {
264     Property::Map vertexFormat;
265     vertexFormat["aPosition"] = Property::VECTOR2;
266     vertexFormat["aTexCoord"] = Property::VECTOR2;
267
268     //Create a vertex buffer for vertex positions and texture coordinates
269     vertexBuffer = PropertyBuffer::New( vertexFormat, 4u );
270     vertexBuffer.SetData( gQuadWithTexture );
271
272     shader = Shader::New( VERTEX_SHADER_TEXTURE, FRAGMENT_SHADER_TEXTURE );
273     Sampler textureSampler = Sampler::New( image, "sTexture" );
274     material = Material::New( shader );
275     material.AddSampler(textureSampler);
276   }
277   else
278   {
279     Property::Map vertexFormat;
280     vertexFormat["aPosition"] = Property::VECTOR2;
281
282     //Create a vertex buffer for vertex positions
283     vertexBuffer = PropertyBuffer::New( vertexFormat, 4u );
284     vertexBuffer.SetData( gQuad );
285
286     shader = Shader::New( VERTEX_SHADER_COLOR, FRAGMENT_SHADER_COLOR );
287     material = Material::New( shader );
288   }
289
290   //Create the index buffer
291   Property::Map indexFormat;
292   indexFormat["indices"] = Property::UNSIGNED_INTEGER;
293   PropertyBuffer indexBuffer = PropertyBuffer::New( indexFormat, 6u );
294   indexBuffer.SetData(gQuadIndex);
295
296   //Create the geometry
297   Geometry mesh = Geometry::New();
298   mesh.AddVertexBuffer( vertexBuffer );
299   mesh.SetIndexBuffer( indexBuffer );
300
301   //Add uniforms to the shader
302   shader.RegisterProperty( "uBackgroundColor", color );
303
304   //Create the renderer
305   Renderer renderer = Renderer::New( mesh, material );
306   renderer.SetDepthIndex( BACKGROUND_DEPTH_INDEX );
307
308   //Create the actor
309   Actor meshActor = Actor::New();
310   meshActor.SetSize( Vector3::ONE );
311   meshActor.AddRenderer( renderer );
312   meshActor.SetPositionInheritanceMode( USE_PARENT_POSITION_PLUS_LOCAL_POSITION );
313   meshActor.SetColorMode( USE_PARENT_COLOR );
314
315   //Constraint scale of the mesh actor to the size of the control
316   Constraint constraint = Constraint::New<Vector3>( meshActor,
317                                                     Actor::Property::SCALE,
318                                                     EqualToConstraint() );
319   constraint.AddSource( ParentSource( Actor::Property::SIZE ) );
320   constraint.Apply();
321
322   return meshActor;
323 }
324
325 } // unnamed namespace
326
327 namespace Internal
328 {
329
330 class Control::Impl : public ConnectionTracker
331 {
332 public:
333
334   // Construction & Destruction
335   Impl(Control& controlImpl)
336 : mControlImpl( controlImpl ),
337   mStyleName(""),
338   mBackground( NULL ),
339   mStartingPinchScale( NULL ),
340   mKeyEventSignal(),
341   mPinchGestureDetector(),
342   mPanGestureDetector(),
343   mTapGestureDetector(),
344   mLongPressGestureDetector(),
345   mFlags( Control::ControlBehaviour( ACTOR_BEHAVIOUR_NONE ) ),
346   mIsKeyboardNavigationSupported( false ),
347   mIsKeyboardFocusGroup( false ),
348   mAddRemoveBackgroundChild( false )
349 {
350 }
351
352   ~Impl()
353   {
354     // All gesture detectors will be destroyed so no need to disconnect.
355     delete mBackground;
356     delete mStartingPinchScale;
357   }
358
359   // Gesture Detection Methods
360
361   void PinchDetected(Actor actor, const PinchGesture& pinch)
362   {
363     mControlImpl.OnPinch(pinch);
364   }
365
366   void PanDetected(Actor actor, const PanGesture& pan)
367   {
368     mControlImpl.OnPan(pan);
369   }
370
371   void TapDetected(Actor actor, const TapGesture& tap)
372   {
373     mControlImpl.OnTap(tap);
374   }
375
376   void LongPressDetected(Actor actor, const LongPressGesture& longPress)
377   {
378     mControlImpl.OnLongPress(longPress);
379   }
380
381   // Background Methods
382
383   /**
384    * Only creates an instance of the background if we actually use it.
385    * @return A reference to the Background structure.
386    */
387   Background& GetBackground()
388   {
389     if ( !mBackground )
390     {
391       mBackground = new Background;
392     }
393     return *mBackground;
394   }
395
396   // Properties
397
398   /**
399    * Called when a property of an object of this type is set.
400    * @param[in] object The object whose property is set.
401    * @param[in] index The property index.
402    * @param[in] value The new property value.
403    */
404   static void SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
405   {
406     Toolkit::Control control = Toolkit::Control::DownCast( BaseHandle( object ) );
407
408     if ( control )
409     {
410       Control& controlImpl( GetImplementation( control ) );
411
412       switch ( index )
413       {
414         case Toolkit::Control::Property::STYLE_NAME:
415         {
416           controlImpl.SetStyleName( value.Get< std::string >() );
417           break;
418         }
419
420         case Toolkit::Control::Property::BACKGROUND_COLOR:
421         {
422           controlImpl.SetBackgroundColor( value.Get< Vector4 >() );
423           break;
424         }
425
426         case Toolkit::Control::Property::BACKGROUND_IMAGE:
427         {
428           if ( value.HasKey( "image" ) )
429           {
430             Property::Map imageMap = value.GetValue( "image" ).Get< Property::Map >();
431             Image image = Scripting::NewImage( imageMap );
432
433             if ( image )
434             {
435               controlImpl.SetBackgroundImage( image );
436             }
437           }
438           else if ( value.Get< Property::Map >().Empty() )
439           {
440             // An empty map means the background is no longer required
441             controlImpl.ClearBackground();
442           }
443           break;
444         }
445
446         case Toolkit::Control::Property::KEY_INPUT_FOCUS:
447         {
448           if ( value.Get< bool >() )
449           {
450             controlImpl.SetKeyInputFocus();
451           }
452           else
453           {
454             controlImpl.ClearKeyInputFocus();
455           }
456           break;
457         }
458       }
459     }
460   }
461
462   /**
463    * Called to retrieve a property of an object of this type.
464    * @param[in] object The object whose property is to be retrieved.
465    * @param[in] index The property index.
466    * @return The current value of the property.
467    */
468   static Property::Value GetProperty( BaseObject* object, Property::Index index )
469   {
470     Property::Value value;
471
472     Toolkit::Control control = Toolkit::Control::DownCast( BaseHandle( object ) );
473
474     if ( control )
475     {
476       Control& controlImpl( GetImplementation( control ) );
477
478       switch ( index )
479       {
480         case Toolkit::Control::Property::STYLE_NAME:
481         {
482           value = controlImpl.GetStyleName();
483           break;
484         }
485
486         case Toolkit::Control::Property::BACKGROUND_COLOR:
487         {
488           value = controlImpl.GetBackgroundColor();
489           break;
490         }
491
492         case Toolkit::Control::Property::BACKGROUND_IMAGE:
493         {
494           Property::Map map;
495
496           Background* back = controlImpl.mImpl->mBackground;
497           if ( back && back->actor && back->actor.GetRendererAt(0).GetMaterial().GetNumberOfSamplers() > 0)
498           {
499             Image image = back->actor.GetRendererAt(0).GetMaterial().GetSamplerAt(0).GetImage();
500             if ( image )
501             {
502               Property::Map imageMap;
503               Scripting::CreatePropertyMap( image, imageMap );
504               map[ "image" ] = imageMap;
505             }
506           }
507
508           value = map;
509           break;
510         }
511
512         case Toolkit::Control::Property::KEY_INPUT_FOCUS:
513         {
514           value = controlImpl.HasKeyInputFocus();
515           break;
516         }
517       }
518     }
519
520     return value;
521   }
522
523   // Data
524
525   Control& mControlImpl;
526   std::string mStyleName;
527   Background* mBackground;           ///< Only create the background if we use it
528   Vector3* mStartingPinchScale;      ///< The scale when a pinch gesture starts, TODO: consider removing this
529   Toolkit::Control::KeyEventSignalType mKeyEventSignal;
530   Toolkit::Control::KeyInputFocusSignalType mKeyInputFocusGainedSignal;
531   Toolkit::Control::KeyInputFocusSignalType mKeyInputFocusLostSignal;
532
533   // Gesture Detection
534   PinchGestureDetector mPinchGestureDetector;
535   PanGestureDetector mPanGestureDetector;
536   TapGestureDetector mTapGestureDetector;
537   LongPressGestureDetector mLongPressGestureDetector;
538
539   ControlBehaviour mFlags :CONTROL_BEHAVIOUR_FLAG_COUNT;    ///< Flags passed in from constructor.
540   bool mIsKeyboardNavigationSupported :1;  ///< Stores whether keyboard navigation is supported by the control.
541   bool mIsKeyboardFocusGroup :1;           ///< Stores whether the control is a focus group.
542   bool mAddRemoveBackgroundChild:1;        ///< Flag to know when we are adding or removing our own actor to avoid call to OnControlChildAdd
543
544   // Properties - these need to be members of Internal::Control::Impl as they need to function within this class.
545   static PropertyRegistration PROPERTY_1;
546   static PropertyRegistration PROPERTY_2;
547   static PropertyRegistration PROPERTY_3;
548   static PropertyRegistration PROPERTY_4;
549 };
550
551 // Properties registered without macro to use specific member variables.
552 PropertyRegistration Control::Impl::PROPERTY_1( typeRegistration, "style-name",       Toolkit::Control::Property::STYLE_NAME,       Property::STRING,  &Control::Impl::SetProperty, &Control::Impl::GetProperty );
553 PropertyRegistration Control::Impl::PROPERTY_2( typeRegistration, "background-color", Toolkit::Control::Property::BACKGROUND_COLOR, Property::VECTOR4, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
554 PropertyRegistration Control::Impl::PROPERTY_3( typeRegistration, "background-image", Toolkit::Control::Property::BACKGROUND_IMAGE, Property::MAP,     &Control::Impl::SetProperty, &Control::Impl::GetProperty );
555 PropertyRegistration Control::Impl::PROPERTY_4( typeRegistration, "key-input-focus",  Toolkit::Control::Property::KEY_INPUT_FOCUS,  Property::BOOLEAN, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
556
557 Toolkit::Control Control::New()
558 {
559   // Create the implementation, temporarily owned on stack
560   IntrusivePtr<Control> controlImpl = new Control( ControlBehaviour( ACTOR_BEHAVIOUR_NONE ) );
561
562   // Pass ownership to handle
563   Toolkit::Control handle( *controlImpl );
564
565   // Second-phase init of the implementation
566   // This can only be done after the CustomActor connection has been made...
567   controlImpl->Initialize();
568
569   return handle;
570 }
571
572 Control::~Control()
573 {
574   delete mImpl;
575 }
576
577 void Control::SetStyleName( const std::string& styleName )
578 {
579   if( styleName != mImpl->mStyleName )
580   {
581     mImpl->mStyleName = styleName;
582
583     // Apply new style
584     Toolkit::StyleManager styleManager = Toolkit::StyleManager::Get();
585     GetImpl( styleManager ).ApplyThemeStyle( Toolkit::Control( GetOwner() ) );
586   }
587 }
588
589 const std::string& Control::GetStyleName() const
590 {
591   return mImpl->mStyleName;
592 }
593
594 void Control::SetBackgroundColor( const Vector4& color )
595 {
596   Background& background( mImpl->GetBackground() );
597
598   if ( background.actor )
599   {
600     Shader shader = background.actor.GetRendererAt(0).GetMaterial().GetShader();
601     shader.SetProperty( shader.GetPropertyIndex("uBackgroundColor"), color );
602   }
603   else
604   {
605     // Create Mesh Actor
606     Actor actor = CreateBackground(Self(), color );
607     background.actor = actor;
608     mImpl->mAddRemoveBackgroundChild = true;
609     // use insert to guarantee its the first child (so that OVERLAY mode works)
610     Self().Insert( 0, actor );
611     mImpl->mAddRemoveBackgroundChild = false;
612   }
613
614   background.color = color;
615 }
616
617 Vector4 Control::GetBackgroundColor() const
618 {
619   if ( mImpl->mBackground )
620   {
621     return mImpl->mBackground->color;
622   }
623   return Color::TRANSPARENT;
624 }
625
626 void Control::SetBackgroundImage( Image image )
627 {
628   Background& background( mImpl->GetBackground() );
629   if( !background.actor || background.actor.GetRendererAt(0).GetMaterial().GetNumberOfSamplers() == 0)
630   {
631     // Remove current actor as it has not texture coordinates
632     if( background.actor )
633     {
634       mImpl->mAddRemoveBackgroundChild = true;
635       Self().Remove( background.actor );
636       mImpl->mAddRemoveBackgroundChild = false;
637       background.actor.Reset();
638     }
639
640     //Create a new actor with texture coordinates
641     Actor actor = CreateBackground(Self(), background.color, image);
642     mImpl->mAddRemoveBackgroundChild = true;
643     // use insert to guarantee its the first child (so that OVERLAY mode works)
644     Self().Insert( 0, actor );
645     mImpl->mAddRemoveBackgroundChild = false;
646     background.actor = actor;
647   }
648   else
649   {
650     //Change sampler image
651     Sampler sampler =  background.actor.GetRendererAt(0).GetMaterial().GetSamplerAt(0);
652     sampler.SetImage(image);
653   }
654 }
655
656 void Control::ClearBackground()
657 {
658   if ( mImpl->mBackground )
659   {
660     Background& background( mImpl->GetBackground() );
661     mImpl->mAddRemoveBackgroundChild = true;
662     Self().Remove( background.actor );
663     mImpl->mAddRemoveBackgroundChild = false;
664
665     delete mImpl->mBackground;
666     mImpl->mBackground = NULL;
667   }
668 }
669
670 void Control::EnableGestureDetection(Gesture::Type type)
671 {
672   if ( (type & Gesture::Pinch) && !mImpl->mPinchGestureDetector )
673   {
674     mImpl->mPinchGestureDetector = PinchGestureDetector::New();
675     mImpl->mPinchGestureDetector.DetectedSignal().Connect(mImpl, &Impl::PinchDetected);
676     mImpl->mPinchGestureDetector.Attach(Self());
677   }
678
679   if ( (type & Gesture::Pan) && !mImpl->mPanGestureDetector )
680   {
681     mImpl->mPanGestureDetector = PanGestureDetector::New();
682     mImpl->mPanGestureDetector.DetectedSignal().Connect(mImpl, &Impl::PanDetected);
683     mImpl->mPanGestureDetector.Attach(Self());
684   }
685
686   if ( (type & Gesture::Tap) && !mImpl->mTapGestureDetector )
687   {
688     mImpl->mTapGestureDetector = TapGestureDetector::New();
689     mImpl->mTapGestureDetector.DetectedSignal().Connect(mImpl, &Impl::TapDetected);
690     mImpl->mTapGestureDetector.Attach(Self());
691   }
692
693   if ( (type & Gesture::LongPress) && !mImpl->mLongPressGestureDetector )
694   {
695     mImpl->mLongPressGestureDetector = LongPressGestureDetector::New();
696     mImpl->mLongPressGestureDetector.DetectedSignal().Connect(mImpl, &Impl::LongPressDetected);
697     mImpl->mLongPressGestureDetector.Attach(Self());
698   }
699 }
700
701 void Control::DisableGestureDetection(Gesture::Type type)
702 {
703   if ( (type & Gesture::Pinch) && mImpl->mPinchGestureDetector )
704   {
705     mImpl->mPinchGestureDetector.Detach(Self());
706     mImpl->mPinchGestureDetector.Reset();
707   }
708
709   if ( (type & Gesture::Pan) && mImpl->mPanGestureDetector )
710   {
711     mImpl->mPanGestureDetector.Detach(Self());
712     mImpl->mPanGestureDetector.Reset();
713   }
714
715   if ( (type & Gesture::Tap) && mImpl->mTapGestureDetector )
716   {
717     mImpl->mTapGestureDetector.Detach(Self());
718     mImpl->mTapGestureDetector.Reset();
719   }
720
721   if ( (type & Gesture::LongPress) && mImpl->mLongPressGestureDetector)
722   {
723     mImpl->mLongPressGestureDetector.Detach(Self());
724     mImpl->mLongPressGestureDetector.Reset();
725   }
726 }
727
728 PinchGestureDetector Control::GetPinchGestureDetector() const
729 {
730   return mImpl->mPinchGestureDetector;
731 }
732
733 PanGestureDetector Control::GetPanGestureDetector() const
734 {
735   return mImpl->mPanGestureDetector;
736 }
737
738 TapGestureDetector Control::GetTapGestureDetector() const
739 {
740   return mImpl->mTapGestureDetector;
741 }
742
743 LongPressGestureDetector Control::GetLongPressGestureDetector() const
744 {
745   return mImpl->mLongPressGestureDetector;
746 }
747
748 void Control::SetKeyboardNavigationSupport(bool isSupported)
749 {
750   mImpl->mIsKeyboardNavigationSupported = isSupported;
751 }
752
753 bool Control::IsKeyboardNavigationSupported()
754 {
755   return mImpl->mIsKeyboardNavigationSupported;
756 }
757
758 void Control::SetKeyInputFocus()
759 {
760   if( Self().OnStage() )
761   {
762     Toolkit::KeyInputFocusManager::Get().SetFocus(Toolkit::Control::DownCast(Self()));
763   }
764 }
765
766 bool Control::HasKeyInputFocus()
767 {
768   bool result = false;
769   if( Self().OnStage() )
770   {
771     result = Toolkit::KeyInputFocusManager::Get().IsKeyboardListener(Toolkit::Control::DownCast(Self()));
772   }
773   return result;
774 }
775
776 void Control::ClearKeyInputFocus()
777 {
778   if( Self().OnStage() )
779   {
780     Toolkit::KeyInputFocusManager::Get().RemoveFocus(Toolkit::Control::DownCast(Self()));
781   }
782 }
783
784 void Control::SetAsKeyboardFocusGroup(bool isFocusGroup)
785 {
786   mImpl->mIsKeyboardFocusGroup = isFocusGroup;
787
788   // The following line will be removed when the deprecated API in KeyboardFocusManager is deleted
789   Toolkit::KeyboardFocusManager::Get().SetAsFocusGroup(Self(), isFocusGroup);
790 }
791
792 bool Control::IsKeyboardFocusGroup()
793 {
794   return Toolkit::KeyboardFocusManager::Get().IsFocusGroup(Self());
795 }
796
797 void Control::AccessibilityActivate()
798 {
799   // Inform deriving classes
800   OnAccessibilityActivated();
801 }
802
803 bool Control::OnAccessibilityActivated()
804 {
805   return false; // Accessibility activation is not handled by default
806 }
807
808 bool Control::OnAccessibilityPan(PanGesture gesture)
809 {
810   return false; // Accessibility pan gesture is not handled by default
811 }
812
813 bool Control::OnAccessibilityTouch(const TouchEvent& touchEvent)
814 {
815   return false; // Accessibility touch event is not handled by default
816 }
817
818 bool Control::OnAccessibilityValueChange(bool isIncrease)
819 {
820   return false; // Accessibility value change action is not handled by default
821 }
822
823 Actor Control::GetNextKeyboardFocusableActor(Actor currentFocusedActor, Toolkit::Control::KeyboardFocus::Direction direction, bool loopEnabled)
824 {
825   return Actor();
826 }
827
828 void Control::OnKeyboardFocusChangeCommitted(Actor commitedFocusableActor)
829 {
830 }
831
832 Toolkit::Control::KeyEventSignalType& Control::KeyEventSignal()
833 {
834   return mImpl->mKeyEventSignal;
835 }
836
837 Toolkit::Control::KeyInputFocusSignalType& Control:: KeyInputFocusGainedSignal()
838 {
839   return mImpl->mKeyInputFocusGainedSignal;
840 }
841
842 Toolkit::Control::KeyInputFocusSignalType& Control:: KeyInputFocusLostSignal()
843 {
844   return mImpl->mKeyInputFocusLostSignal;
845 }
846
847 bool Control::EmitKeyEventSignal( const KeyEvent& event )
848 {
849   // Guard against destruction during signal emission
850   Dali::Toolkit::Control handle( GetOwner() );
851
852   bool consumed = false;
853
854   // signals are allocated dynamically when someone connects
855   if ( !mImpl->mKeyEventSignal.Empty() )
856   {
857     consumed = mImpl->mKeyEventSignal.Emit( handle, event );
858   }
859
860   if (!consumed)
861   {
862     // Notification for derived classes
863     consumed = OnKeyEvent(event);
864   }
865
866   return consumed;
867 }
868
869 Control::Control( ControlBehaviour behaviourFlags )
870 : CustomActorImpl( static_cast< ActorFlags >( behaviourFlags ) ),
871   mImpl(new Impl(*this))
872 {
873   mImpl->mFlags = behaviourFlags;
874 }
875
876 void Control::Initialize()
877 {
878   if( mImpl->mFlags & REQUIRES_STYLE_CHANGE_SIGNALS )
879   {
880     Toolkit::StyleManager styleManager = Toolkit::StyleManager::Get();
881
882     // Register for style changes
883     styleManager.StyleChangeSignal().Connect( this, &Control::OnStyleChange );
884
885     // SetTheme
886     GetImpl( styleManager ).ApplyThemeStyle( Toolkit::Control( GetOwner() ) );
887   }
888
889   if( mImpl->mFlags & REQUIRES_KEYBOARD_NAVIGATION_SUPPORT )
890   {
891     SetKeyboardNavigationSupport( true );
892   }
893
894   // Calling deriving classes
895   OnInitialize();
896 }
897
898 void Control::OnInitialize()
899 {
900 }
901
902 void Control::OnControlChildAdd( Actor& child )
903 {
904 }
905
906 void Control::OnControlChildRemove( Actor& child )
907 {
908 }
909
910 void Control::OnStyleChange( Toolkit::StyleManager styleManager, StyleChange::Type change )
911 {
912   // By default the control is only interested in theme (not font) changes
913   if( change == StyleChange::THEME_CHANGE )
914   {
915     GetImpl( styleManager ).ApplyThemeStyle( Toolkit::Control( GetOwner() ) );
916   }
917 }
918
919 void Control::OnPinch(const PinchGesture& pinch)
920 {
921   if( !( mImpl->mStartingPinchScale ) )
922   {
923     // lazy allocate
924     mImpl->mStartingPinchScale = new Vector3;
925   }
926
927   if( pinch.state == Gesture::Started )
928   {
929     *( mImpl->mStartingPinchScale ) = Self().GetCurrentScale();
930   }
931
932   Self().SetScale( *( mImpl->mStartingPinchScale ) * pinch.scale );
933 }
934
935 void Control::OnPan( const PanGesture& pan )
936 {
937 }
938
939 void Control::OnTap(const TapGesture& tap)
940 {
941 }
942
943 void Control::OnLongPress( const LongPressGesture& longPress )
944 {
945 }
946
947 void Control::EmitKeyInputFocusSignal( bool focusGained )
948 {
949   Dali::Toolkit::Control handle( GetOwner() );
950
951   if ( focusGained )
952   {
953     // signals are allocated dynamically when someone connects
954     if ( !mImpl->mKeyInputFocusGainedSignal.Empty() )
955     {
956       mImpl->mKeyInputFocusGainedSignal.Emit( handle );
957     }
958   }
959   else
960   {
961     // signals are allocated dynamically when someone connects
962     if ( !mImpl->mKeyInputFocusLostSignal.Empty() )
963     {
964       mImpl->mKeyInputFocusLostSignal.Emit( handle );
965     }
966   }
967 }
968
969 void Control::OnStageConnection( unsigned int depth )
970 {
971   unsigned int controlRendererCount = Self().GetRendererCount();
972   for( unsigned int i(0); i<controlRendererCount; ++i )
973   {
974     Renderer controlRenderer = Self().GetRendererAt(i);
975     if( controlRenderer )
976     {
977       controlRenderer.SetDepthIndex( CONTENT_DEPTH_INDEX+depth );
978     }
979   }
980
981   if( mImpl->mBackground )
982   {
983     Renderer backgroundRenderer = mImpl->mBackground->actor.GetRendererAt( 0 );
984     if(backgroundRenderer)
985     {
986       backgroundRenderer.SetDepthIndex( BACKGROUND_DEPTH_INDEX+depth );
987     }
988   }
989 }
990
991 void Control::OnStageDisconnection()
992 {
993 }
994
995 void Control::OnKeyInputFocusGained()
996 {
997   EmitKeyInputFocusSignal( true );
998 }
999
1000 void Control::OnKeyInputFocusLost()
1001 {
1002   EmitKeyInputFocusSignal( false );
1003 }
1004
1005 void Control::OnChildAdd(Actor& child)
1006 {
1007   // If this is the background actor, then we do not want to inform deriving classes
1008   if ( mImpl->mAddRemoveBackgroundChild )
1009   {
1010     return;
1011   }
1012
1013   // Notify derived classes.
1014   OnControlChildAdd( child );
1015 }
1016
1017 void Control::OnChildRemove(Actor& child)
1018 {
1019   // If this is the background actor, then we do not want to inform deriving classes
1020   if ( mImpl->mAddRemoveBackgroundChild )
1021   {
1022     return;
1023   }
1024
1025   // Notify derived classes.
1026   OnControlChildRemove( child );
1027 }
1028
1029 void Control::OnSizeSet(const Vector3& targetSize)
1030 {
1031   // Background is resized through size negotiation
1032 }
1033
1034 void Control::OnSizeAnimation(Animation& animation, const Vector3& targetSize)
1035 {
1036   // @todo size negotiate background to new size, animate as well?
1037 }
1038
1039 bool Control::OnTouchEvent(const TouchEvent& event)
1040 {
1041   return false; // Do not consume
1042 }
1043
1044 bool Control::OnHoverEvent(const HoverEvent& event)
1045 {
1046   return false; // Do not consume
1047 }
1048
1049 bool Control::OnKeyEvent(const KeyEvent& event)
1050 {
1051   return false; // Do not consume
1052 }
1053
1054 bool Control::OnWheelEvent(const WheelEvent& event)
1055 {
1056   return false; // Do not consume
1057 }
1058
1059 void Control::OnRelayout( const Vector2& size, RelayoutContainer& container )
1060 {
1061   for( unsigned int i = 0, numChildren = Self().GetChildCount(); i < numChildren; ++i )
1062   {
1063     container.Add( Self().GetChildAt( i ), size );
1064   }
1065 }
1066
1067 void Control::OnSetResizePolicy( ResizePolicy::Type policy, Dimension::Type dimension )
1068 {
1069 }
1070
1071 Vector3 Control::GetNaturalSize()
1072 {
1073   //Control's natural size is the size of its background image if it has been set, or ZERO otherwise
1074   Vector3 naturalSize = Vector3::ZERO;
1075   if( mImpl->mBackground )
1076   {
1077     Material backgroundMaterial = mImpl->mBackground->actor.GetRendererAt(0).GetMaterial();
1078     if( backgroundMaterial.GetNumberOfSamplers() > 0 )
1079     {
1080       Image backgroundImage =  backgroundMaterial.GetSamplerAt(0).GetImage();
1081       if( backgroundImage )
1082       {
1083         naturalSize.x = backgroundImage.GetWidth();
1084         naturalSize.y = backgroundImage.GetHeight();
1085       }
1086     }
1087   }
1088
1089   return naturalSize;
1090 }
1091
1092 float Control::CalculateChildSize( const Dali::Actor& child, Dimension::Type dimension )
1093 {
1094   return CalculateChildSizeBase( child, dimension );
1095 }
1096
1097 float Control::GetHeightForWidth( float width )
1098 {
1099   if( mImpl->mBackground )
1100   {
1101     Actor actor = mImpl->mBackground->actor;
1102     if( actor )
1103     {
1104       return actor.GetHeightForWidth( width );
1105     }
1106   }
1107   return GetHeightForWidthBase( width );
1108 }
1109
1110 float Control::GetWidthForHeight( float height )
1111 {
1112   if( mImpl->mBackground )
1113   {
1114     Actor actor = mImpl->mBackground->actor;
1115     if( actor )
1116     {
1117       return actor.GetWidthForHeight( height );
1118     }
1119   }
1120   return GetWidthForHeightBase( height );
1121 }
1122
1123 bool Control::RelayoutDependentOnChildren( Dimension::Type dimension )
1124 {
1125   return RelayoutDependentOnChildrenBase( dimension );
1126 }
1127
1128 void Control::OnCalculateRelayoutSize( Dimension::Type dimension )
1129 {
1130 }
1131
1132 void Control::OnLayoutNegotiated( float size, Dimension::Type dimension )
1133 {
1134 }
1135
1136 void Control::SignalConnected( SlotObserver* slotObserver, CallbackBase* callback )
1137 {
1138   mImpl->SignalConnected( slotObserver, callback );
1139 }
1140
1141 void Control::SignalDisconnected( SlotObserver* slotObserver, CallbackBase* callback )
1142 {
1143   mImpl->SignalDisconnected( slotObserver, callback );
1144 }
1145
1146 Control& GetImplementation( Dali::Toolkit::Control& handle )
1147 {
1148   CustomActorImpl& customInterface = handle.GetImplementation();
1149   // downcast to control
1150   Control& impl = dynamic_cast< Internal::Control& >( customInterface );
1151   return impl;
1152 }
1153
1154 const Control& GetImplementation( const Dali::Toolkit::Control& handle )
1155 {
1156   const CustomActorImpl& customInterface = handle.GetImplementation();
1157   // downcast to control
1158   const Control& impl = dynamic_cast< const Internal::Control& >( customInterface );
1159   return impl;
1160 }
1161
1162 } // namespace Internal
1163
1164 } // namespace Toolkit
1165
1166 } // namespace Dali