88b588d53fca794b76ec24486c48169992e83e5a
[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           Image image = Scripting::NewImage( value );
429           if ( image )
430           {
431             controlImpl.SetBackgroundImage( image );
432           }
433           else
434           {
435             // An empty map means the background is no longer required
436             controlImpl.ClearBackground();
437           }
438           break;
439         }
440
441         case Toolkit::Control::Property::KEY_INPUT_FOCUS:
442         {
443           if ( value.Get< bool >() )
444           {
445             controlImpl.SetKeyInputFocus();
446           }
447           else
448           {
449             controlImpl.ClearKeyInputFocus();
450           }
451           break;
452         }
453       }
454     }
455   }
456
457   /**
458    * Called to retrieve a property of an object of this type.
459    * @param[in] object The object whose property is to be retrieved.
460    * @param[in] index The property index.
461    * @return The current value of the property.
462    */
463   static Property::Value GetProperty( BaseObject* object, Property::Index index )
464   {
465     Property::Value value;
466
467     Toolkit::Control control = Toolkit::Control::DownCast( BaseHandle( object ) );
468
469     if ( control )
470     {
471       Control& controlImpl( GetImplementation( control ) );
472
473       switch ( index )
474       {
475         case Toolkit::Control::Property::STYLE_NAME:
476         {
477           value = controlImpl.GetStyleName();
478           break;
479         }
480
481         case Toolkit::Control::Property::BACKGROUND_COLOR:
482         {
483           value = controlImpl.GetBackgroundColor();
484           break;
485         }
486
487         case Toolkit::Control::Property::BACKGROUND_IMAGE:
488         {
489           Property::Map map;
490
491           Background* back = controlImpl.mImpl->mBackground;
492           if ( back && back->actor && back->actor.GetRendererAt(0).GetMaterial().GetNumberOfSamplers() > 0)
493           {
494             Image image = back->actor.GetRendererAt(0).GetMaterial().GetSamplerAt(0).GetImage();
495             if ( image )
496             {
497               Scripting::CreatePropertyMap( image, map );
498             }
499           }
500
501           value = map;
502           break;
503         }
504
505         case Toolkit::Control::Property::KEY_INPUT_FOCUS:
506         {
507           value = controlImpl.HasKeyInputFocus();
508           break;
509         }
510       }
511     }
512
513     return value;
514   }
515
516   // Data
517
518   Control& mControlImpl;
519   std::string mStyleName;
520   Background* mBackground;           ///< Only create the background if we use it
521   Vector3* mStartingPinchScale;      ///< The scale when a pinch gesture starts, TODO: consider removing this
522   Toolkit::Control::KeyEventSignalType mKeyEventSignal;
523   Toolkit::Control::KeyInputFocusSignalType mKeyInputFocusGainedSignal;
524   Toolkit::Control::KeyInputFocusSignalType mKeyInputFocusLostSignal;
525
526   // Gesture Detection
527   PinchGestureDetector mPinchGestureDetector;
528   PanGestureDetector mPanGestureDetector;
529   TapGestureDetector mTapGestureDetector;
530   LongPressGestureDetector mLongPressGestureDetector;
531
532   ControlBehaviour mFlags :CONTROL_BEHAVIOUR_FLAG_COUNT;    ///< Flags passed in from constructor.
533   bool mIsKeyboardNavigationSupported :1;  ///< Stores whether keyboard navigation is supported by the control.
534   bool mIsKeyboardFocusGroup :1;           ///< Stores whether the control is a focus group.
535   bool mAddRemoveBackgroundChild:1;        ///< Flag to know when we are adding or removing our own actor to avoid call to OnControlChildAdd
536
537   // Properties - these need to be members of Internal::Control::Impl as they need to function within this class.
538   static PropertyRegistration PROPERTY_1;
539   static PropertyRegistration PROPERTY_2;
540   static PropertyRegistration PROPERTY_3;
541   static PropertyRegistration PROPERTY_4;
542 };
543
544 // Properties registered without macro to use specific member variables.
545 PropertyRegistration Control::Impl::PROPERTY_1( typeRegistration, "style-name",       Toolkit::Control::Property::STYLE_NAME,       Property::STRING,  &Control::Impl::SetProperty, &Control::Impl::GetProperty );
546 PropertyRegistration Control::Impl::PROPERTY_2( typeRegistration, "background-color", Toolkit::Control::Property::BACKGROUND_COLOR, Property::VECTOR4, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
547 PropertyRegistration Control::Impl::PROPERTY_3( typeRegistration, "background-image", Toolkit::Control::Property::BACKGROUND_IMAGE, Property::MAP,     &Control::Impl::SetProperty, &Control::Impl::GetProperty );
548 PropertyRegistration Control::Impl::PROPERTY_4( typeRegistration, "key-input-focus",  Toolkit::Control::Property::KEY_INPUT_FOCUS,  Property::BOOLEAN, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
549
550 Toolkit::Control Control::New()
551 {
552   // Create the implementation, temporarily owned on stack
553   IntrusivePtr<Control> controlImpl = new Control( ControlBehaviour( ACTOR_BEHAVIOUR_NONE ) );
554
555   // Pass ownership to handle
556   Toolkit::Control handle( *controlImpl );
557
558   // Second-phase init of the implementation
559   // This can only be done after the CustomActor connection has been made...
560   controlImpl->Initialize();
561
562   return handle;
563 }
564
565 Control::~Control()
566 {
567   delete mImpl;
568 }
569
570 void Control::SetStyleName( const std::string& styleName )
571 {
572   if( styleName != mImpl->mStyleName )
573   {
574     mImpl->mStyleName = styleName;
575
576     // Apply new style
577     Toolkit::StyleManager styleManager = Toolkit::StyleManager::Get();
578     GetImpl( styleManager ).ApplyThemeStyle( Toolkit::Control( GetOwner() ) );
579   }
580 }
581
582 const std::string& Control::GetStyleName() const
583 {
584   return mImpl->mStyleName;
585 }
586
587 void Control::SetBackgroundColor( const Vector4& color )
588 {
589   Background& background( mImpl->GetBackground() );
590
591   if ( background.actor )
592   {
593     Shader shader = background.actor.GetRendererAt(0).GetMaterial().GetShader();
594     shader.SetProperty( shader.GetPropertyIndex("uBackgroundColor"), color );
595   }
596   else
597   {
598     // Create Mesh Actor
599     Actor actor = CreateBackground(Self(), color );
600     background.actor = actor;
601     mImpl->mAddRemoveBackgroundChild = true;
602     // use insert to guarantee its the first child (so that OVERLAY mode works)
603     Self().Insert( 0, actor );
604     mImpl->mAddRemoveBackgroundChild = false;
605   }
606
607   background.color = color;
608 }
609
610 Vector4 Control::GetBackgroundColor() const
611 {
612   if ( mImpl->mBackground )
613   {
614     return mImpl->mBackground->color;
615   }
616   return Color::TRANSPARENT;
617 }
618
619 void Control::SetBackgroundImage( Image image )
620 {
621   Background& background( mImpl->GetBackground() );
622   if( !background.actor || background.actor.GetRendererAt(0).GetMaterial().GetNumberOfSamplers() == 0)
623   {
624     // Remove current actor as it has not texture coordinates
625     if( background.actor )
626     {
627       mImpl->mAddRemoveBackgroundChild = true;
628       Self().Remove( background.actor );
629       mImpl->mAddRemoveBackgroundChild = false;
630       background.actor.Reset();
631     }
632
633     //Create a new actor with texture coordinates
634     Actor actor = CreateBackground(Self(), background.color, image);
635     mImpl->mAddRemoveBackgroundChild = true;
636     // use insert to guarantee its the first child (so that OVERLAY mode works)
637     Self().Insert( 0, actor );
638     mImpl->mAddRemoveBackgroundChild = false;
639     background.actor = actor;
640   }
641   else
642   {
643     //Change sampler image
644     Sampler sampler =  background.actor.GetRendererAt(0).GetMaterial().GetSamplerAt(0);
645     sampler.SetImage(image);
646   }
647 }
648
649 void Control::ClearBackground()
650 {
651   if ( mImpl->mBackground )
652   {
653     Background& background( mImpl->GetBackground() );
654     mImpl->mAddRemoveBackgroundChild = true;
655     Self().Remove( background.actor );
656     mImpl->mAddRemoveBackgroundChild = false;
657
658     delete mImpl->mBackground;
659     mImpl->mBackground = NULL;
660   }
661 }
662
663 void Control::EnableGestureDetection(Gesture::Type type)
664 {
665   if ( (type & Gesture::Pinch) && !mImpl->mPinchGestureDetector )
666   {
667     mImpl->mPinchGestureDetector = PinchGestureDetector::New();
668     mImpl->mPinchGestureDetector.DetectedSignal().Connect(mImpl, &Impl::PinchDetected);
669     mImpl->mPinchGestureDetector.Attach(Self());
670   }
671
672   if ( (type & Gesture::Pan) && !mImpl->mPanGestureDetector )
673   {
674     mImpl->mPanGestureDetector = PanGestureDetector::New();
675     mImpl->mPanGestureDetector.DetectedSignal().Connect(mImpl, &Impl::PanDetected);
676     mImpl->mPanGestureDetector.Attach(Self());
677   }
678
679   if ( (type & Gesture::Tap) && !mImpl->mTapGestureDetector )
680   {
681     mImpl->mTapGestureDetector = TapGestureDetector::New();
682     mImpl->mTapGestureDetector.DetectedSignal().Connect(mImpl, &Impl::TapDetected);
683     mImpl->mTapGestureDetector.Attach(Self());
684   }
685
686   if ( (type & Gesture::LongPress) && !mImpl->mLongPressGestureDetector )
687   {
688     mImpl->mLongPressGestureDetector = LongPressGestureDetector::New();
689     mImpl->mLongPressGestureDetector.DetectedSignal().Connect(mImpl, &Impl::LongPressDetected);
690     mImpl->mLongPressGestureDetector.Attach(Self());
691   }
692 }
693
694 void Control::DisableGestureDetection(Gesture::Type type)
695 {
696   if ( (type & Gesture::Pinch) && mImpl->mPinchGestureDetector )
697   {
698     mImpl->mPinchGestureDetector.Detach(Self());
699     mImpl->mPinchGestureDetector.Reset();
700   }
701
702   if ( (type & Gesture::Pan) && mImpl->mPanGestureDetector )
703   {
704     mImpl->mPanGestureDetector.Detach(Self());
705     mImpl->mPanGestureDetector.Reset();
706   }
707
708   if ( (type & Gesture::Tap) && mImpl->mTapGestureDetector )
709   {
710     mImpl->mTapGestureDetector.Detach(Self());
711     mImpl->mTapGestureDetector.Reset();
712   }
713
714   if ( (type & Gesture::LongPress) && mImpl->mLongPressGestureDetector)
715   {
716     mImpl->mLongPressGestureDetector.Detach(Self());
717     mImpl->mLongPressGestureDetector.Reset();
718   }
719 }
720
721 PinchGestureDetector Control::GetPinchGestureDetector() const
722 {
723   return mImpl->mPinchGestureDetector;
724 }
725
726 PanGestureDetector Control::GetPanGestureDetector() const
727 {
728   return mImpl->mPanGestureDetector;
729 }
730
731 TapGestureDetector Control::GetTapGestureDetector() const
732 {
733   return mImpl->mTapGestureDetector;
734 }
735
736 LongPressGestureDetector Control::GetLongPressGestureDetector() const
737 {
738   return mImpl->mLongPressGestureDetector;
739 }
740
741 void Control::SetKeyboardNavigationSupport(bool isSupported)
742 {
743   mImpl->mIsKeyboardNavigationSupported = isSupported;
744 }
745
746 bool Control::IsKeyboardNavigationSupported()
747 {
748   return mImpl->mIsKeyboardNavigationSupported;
749 }
750
751 void Control::SetKeyInputFocus()
752 {
753   if( Self().OnStage() )
754   {
755     Toolkit::KeyInputFocusManager::Get().SetFocus(Toolkit::Control::DownCast(Self()));
756   }
757 }
758
759 bool Control::HasKeyInputFocus()
760 {
761   bool result = false;
762   if( Self().OnStage() )
763   {
764     result = Toolkit::KeyInputFocusManager::Get().IsKeyboardListener(Toolkit::Control::DownCast(Self()));
765   }
766   return result;
767 }
768
769 void Control::ClearKeyInputFocus()
770 {
771   if( Self().OnStage() )
772   {
773     Toolkit::KeyInputFocusManager::Get().RemoveFocus(Toolkit::Control::DownCast(Self()));
774   }
775 }
776
777 void Control::SetAsKeyboardFocusGroup(bool isFocusGroup)
778 {
779   mImpl->mIsKeyboardFocusGroup = isFocusGroup;
780
781   // The following line will be removed when the deprecated API in KeyboardFocusManager is deleted
782   Toolkit::KeyboardFocusManager::Get().SetAsFocusGroup(Self(), isFocusGroup);
783 }
784
785 bool Control::IsKeyboardFocusGroup()
786 {
787   return Toolkit::KeyboardFocusManager::Get().IsFocusGroup(Self());
788 }
789
790 void Control::AccessibilityActivate()
791 {
792   // Inform deriving classes
793   OnAccessibilityActivated();
794 }
795
796 bool Control::OnAccessibilityActivated()
797 {
798   return false; // Accessibility activation is not handled by default
799 }
800
801 bool Control::OnAccessibilityPan(PanGesture gesture)
802 {
803   return false; // Accessibility pan gesture is not handled by default
804 }
805
806 bool Control::OnAccessibilityTouch(const TouchEvent& touchEvent)
807 {
808   return false; // Accessibility touch event is not handled by default
809 }
810
811 bool Control::OnAccessibilityValueChange(bool isIncrease)
812 {
813   return false; // Accessibility value change action is not handled by default
814 }
815
816 Actor Control::GetNextKeyboardFocusableActor(Actor currentFocusedActor, Toolkit::Control::KeyboardFocus::Direction direction, bool loopEnabled)
817 {
818   return Actor();
819 }
820
821 void Control::OnKeyboardFocusChangeCommitted(Actor commitedFocusableActor)
822 {
823 }
824
825 Toolkit::Control::KeyEventSignalType& Control::KeyEventSignal()
826 {
827   return mImpl->mKeyEventSignal;
828 }
829
830 Toolkit::Control::KeyInputFocusSignalType& Control:: KeyInputFocusGainedSignal()
831 {
832   return mImpl->mKeyInputFocusGainedSignal;
833 }
834
835 Toolkit::Control::KeyInputFocusSignalType& Control:: KeyInputFocusLostSignal()
836 {
837   return mImpl->mKeyInputFocusLostSignal;
838 }
839
840 bool Control::EmitKeyEventSignal( const KeyEvent& event )
841 {
842   // Guard against destruction during signal emission
843   Dali::Toolkit::Control handle( GetOwner() );
844
845   bool consumed = false;
846
847   // signals are allocated dynamically when someone connects
848   if ( !mImpl->mKeyEventSignal.Empty() )
849   {
850     consumed = mImpl->mKeyEventSignal.Emit( handle, event );
851   }
852
853   if (!consumed)
854   {
855     // Notification for derived classes
856     consumed = OnKeyEvent(event);
857   }
858
859   return consumed;
860 }
861
862 Control::Control( ControlBehaviour behaviourFlags )
863 : CustomActorImpl( static_cast< ActorFlags >( behaviourFlags ) ),
864   mImpl(new Impl(*this))
865 {
866   mImpl->mFlags = behaviourFlags;
867 }
868
869 void Control::Initialize()
870 {
871   // Call deriving classes so initialised before styling is applied to them.
872   OnInitialize();
873
874   if( mImpl->mFlags & REQUIRES_STYLE_CHANGE_SIGNALS )
875   {
876     Toolkit::StyleManager styleManager = Toolkit::StyleManager::Get();
877
878     // Register for style changes
879     styleManager.StyleChangeSignal().Connect( this, &Control::OnStyleChange );
880
881     // Apply the current style
882     GetImpl( styleManager ).ApplyThemeStyle( Toolkit::Control( GetOwner() ) );
883   }
884
885   if( mImpl->mFlags & REQUIRES_KEYBOARD_NAVIGATION_SUPPORT )
886   {
887     SetKeyboardNavigationSupport( true );
888   }
889 }
890
891 void Control::OnInitialize()
892 {
893 }
894
895 void Control::OnControlChildAdd( Actor& child )
896 {
897 }
898
899 void Control::OnControlChildRemove( Actor& child )
900 {
901 }
902
903 void Control::OnStyleChange( Toolkit::StyleManager styleManager, StyleChange::Type change )
904 {
905   // By default the control is only interested in theme (not font) changes
906   if( change == StyleChange::THEME_CHANGE )
907   {
908     GetImpl( styleManager ).ApplyThemeStyle( Toolkit::Control( GetOwner() ) );
909   }
910 }
911
912 void Control::OnPinch(const PinchGesture& pinch)
913 {
914   if( !( mImpl->mStartingPinchScale ) )
915   {
916     // lazy allocate
917     mImpl->mStartingPinchScale = new Vector3;
918   }
919
920   if( pinch.state == Gesture::Started )
921   {
922     *( mImpl->mStartingPinchScale ) = Self().GetCurrentScale();
923   }
924
925   Self().SetScale( *( mImpl->mStartingPinchScale ) * pinch.scale );
926 }
927
928 void Control::OnPan( const PanGesture& pan )
929 {
930 }
931
932 void Control::OnTap(const TapGesture& tap)
933 {
934 }
935
936 void Control::OnLongPress( const LongPressGesture& longPress )
937 {
938 }
939
940 void Control::EmitKeyInputFocusSignal( bool focusGained )
941 {
942   Dali::Toolkit::Control handle( GetOwner() );
943
944   if ( focusGained )
945   {
946     // signals are allocated dynamically when someone connects
947     if ( !mImpl->mKeyInputFocusGainedSignal.Empty() )
948     {
949       mImpl->mKeyInputFocusGainedSignal.Emit( handle );
950     }
951   }
952   else
953   {
954     // signals are allocated dynamically when someone connects
955     if ( !mImpl->mKeyInputFocusLostSignal.Empty() )
956     {
957       mImpl->mKeyInputFocusLostSignal.Emit( handle );
958     }
959   }
960 }
961
962 void Control::OnStageConnection( unsigned int depth )
963 {
964   unsigned int controlRendererCount = Self().GetRendererCount();
965   for( unsigned int i(0); i<controlRendererCount; ++i )
966   {
967     Renderer controlRenderer = Self().GetRendererAt(i);
968     if( controlRenderer )
969     {
970       controlRenderer.SetDepthIndex( CONTENT_DEPTH_INDEX+depth );
971     }
972   }
973
974   if( mImpl->mBackground )
975   {
976     Renderer backgroundRenderer = mImpl->mBackground->actor.GetRendererAt( 0 );
977     if(backgroundRenderer)
978     {
979       backgroundRenderer.SetDepthIndex( BACKGROUND_DEPTH_INDEX+depth );
980     }
981   }
982 }
983
984 void Control::OnStageDisconnection()
985 {
986 }
987
988 void Control::OnKeyInputFocusGained()
989 {
990   EmitKeyInputFocusSignal( true );
991 }
992
993 void Control::OnKeyInputFocusLost()
994 {
995   EmitKeyInputFocusSignal( false );
996 }
997
998 void Control::OnChildAdd(Actor& child)
999 {
1000   // If this is the background actor, then we do not want to inform deriving classes
1001   if ( mImpl->mAddRemoveBackgroundChild )
1002   {
1003     return;
1004   }
1005
1006   // Notify derived classes.
1007   OnControlChildAdd( child );
1008 }
1009
1010 void Control::OnChildRemove(Actor& child)
1011 {
1012   // If this is the background actor, then we do not want to inform deriving classes
1013   if ( mImpl->mAddRemoveBackgroundChild )
1014   {
1015     return;
1016   }
1017
1018   // Notify derived classes.
1019   OnControlChildRemove( child );
1020 }
1021
1022 void Control::OnSizeSet(const Vector3& targetSize)
1023 {
1024   // Background is resized through size negotiation
1025 }
1026
1027 void Control::OnSizeAnimation(Animation& animation, const Vector3& targetSize)
1028 {
1029   // @todo size negotiate background to new size, animate as well?
1030 }
1031
1032 bool Control::OnTouchEvent(const TouchEvent& event)
1033 {
1034   return false; // Do not consume
1035 }
1036
1037 bool Control::OnHoverEvent(const HoverEvent& event)
1038 {
1039   return false; // Do not consume
1040 }
1041
1042 bool Control::OnKeyEvent(const KeyEvent& event)
1043 {
1044   return false; // Do not consume
1045 }
1046
1047 bool Control::OnWheelEvent(const WheelEvent& event)
1048 {
1049   return false; // Do not consume
1050 }
1051
1052 void Control::OnRelayout( const Vector2& size, RelayoutContainer& container )
1053 {
1054   for( unsigned int i = 0, numChildren = Self().GetChildCount(); i < numChildren; ++i )
1055   {
1056     container.Add( Self().GetChildAt( i ), size );
1057   }
1058 }
1059
1060 void Control::OnSetResizePolicy( ResizePolicy::Type policy, Dimension::Type dimension )
1061 {
1062 }
1063
1064 Vector3 Control::GetNaturalSize()
1065 {
1066   //Control's natural size is the size of its background image if it has been set, or ZERO otherwise
1067   Vector3 naturalSize = Vector3::ZERO;
1068   if( mImpl->mBackground )
1069   {
1070     Material backgroundMaterial = mImpl->mBackground->actor.GetRendererAt(0).GetMaterial();
1071     if( backgroundMaterial.GetNumberOfSamplers() > 0 )
1072     {
1073       Image backgroundImage =  backgroundMaterial.GetSamplerAt(0).GetImage();
1074       if( backgroundImage )
1075       {
1076         naturalSize.x = backgroundImage.GetWidth();
1077         naturalSize.y = backgroundImage.GetHeight();
1078       }
1079     }
1080   }
1081
1082   return naturalSize;
1083 }
1084
1085 float Control::CalculateChildSize( const Dali::Actor& child, Dimension::Type dimension )
1086 {
1087   return CalculateChildSizeBase( child, dimension );
1088 }
1089
1090 float Control::GetHeightForWidth( float width )
1091 {
1092   if( mImpl->mBackground )
1093   {
1094     Actor actor = mImpl->mBackground->actor;
1095     if( actor )
1096     {
1097       return actor.GetHeightForWidth( width );
1098     }
1099   }
1100   return GetHeightForWidthBase( width );
1101 }
1102
1103 float Control::GetWidthForHeight( float height )
1104 {
1105   if( mImpl->mBackground )
1106   {
1107     Actor actor = mImpl->mBackground->actor;
1108     if( actor )
1109     {
1110       return actor.GetWidthForHeight( height );
1111     }
1112   }
1113   return GetWidthForHeightBase( height );
1114 }
1115
1116 bool Control::RelayoutDependentOnChildren( Dimension::Type dimension )
1117 {
1118   return RelayoutDependentOnChildrenBase( dimension );
1119 }
1120
1121 void Control::OnCalculateRelayoutSize( Dimension::Type dimension )
1122 {
1123 }
1124
1125 void Control::OnLayoutNegotiated( float size, Dimension::Type dimension )
1126 {
1127 }
1128
1129 void Control::SignalConnected( SlotObserver* slotObserver, CallbackBase* callback )
1130 {
1131   mImpl->SignalConnected( slotObserver, callback );
1132 }
1133
1134 void Control::SignalDisconnected( SlotObserver* slotObserver, CallbackBase* callback )
1135 {
1136   mImpl->SignalDisconnected( slotObserver, callback );
1137 }
1138
1139 Control& GetImplementation( Dali::Toolkit::Control& handle )
1140 {
1141   CustomActorImpl& customInterface = handle.GetImplementation();
1142   // downcast to control
1143   Control& impl = dynamic_cast< Internal::Control& >( customInterface );
1144   return impl;
1145 }
1146
1147 const Control& GetImplementation( const Dali::Toolkit::Control& handle )
1148 {
1149   const CustomActorImpl& customInterface = handle.GetImplementation();
1150   // downcast to control
1151   const Control& impl = dynamic_cast< const Internal::Control& >( customInterface );
1152   return impl;
1153 }
1154
1155 } // namespace Internal
1156
1157 } // namespace Toolkit
1158
1159 } // namespace Dali