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