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