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