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