Merge "Bug fix when creating background of control using ImageActor" into devel/master
[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( 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
552     Toolkit::StyleManager styleManager = Toolkit::StyleManager::Get();
553     GetImpl( styleManager ).ApplyThemeStyle( Toolkit::Control( GetOwner() ) );
554   }
555 }
556
557 const std::string& Control::GetStyleName() const
558 {
559   return mImpl->mStyleName;
560 }
561
562 void Control::SetBackgroundColor( const Vector4& color )
563 {
564   Background& background( mImpl->GetBackground() );
565
566   if ( background.actor )
567   {
568     if( background.actor.GetRendererCount() > 0 )
569     {
570       Shader shader = background.actor.GetRendererAt(0).GetMaterial().GetShader();
571       shader.SetProperty( shader.GetPropertyIndex("uBackgroundColor"), color );
572     }
573     else
574     {
575       background.actor.SetColor( color );
576     }
577   }
578   else
579   {
580     // Create Mesh Actor
581     Actor actor = CreateBackground(Self(), color );
582     background.actor = actor;
583     mImpl->mAddRemoveBackgroundChild = true;
584     // use insert to guarantee its the first child (so that OVERLAY mode works)
585     Self().Insert( 0, actor );
586     mImpl->mAddRemoveBackgroundChild = false;
587   }
588
589   background.color = color;
590 }
591
592 Vector4 Control::GetBackgroundColor() const
593 {
594   if ( mImpl->mBackground )
595   {
596     return mImpl->mBackground->color;
597   }
598   return Color::TRANSPARENT;
599 }
600
601 void Control::SetBackgroundImage( Image image )
602 {
603   Background& background( mImpl->GetBackground() );
604
605    if ( background.actor )
606    {
607      // Remove Current actor, unset AFTER removal
608      mImpl->mAddRemoveBackgroundChild = true;
609      Self().Remove( background.actor );
610      mImpl->mAddRemoveBackgroundChild = false;
611      background.actor.Reset();
612    }
613
614    Actor actor = CreateBackground(Self(), background.color, image);
615
616    // Set the background actor before adding so that we do not inform derived classes
617    background.actor = actor;
618    mImpl->mAddRemoveBackgroundChild = true;
619    // use insert to guarantee its the first child (so that OVERLAY mode works)
620    Self().Insert( 0, actor );
621    mImpl->mAddRemoveBackgroundChild = false;
622 }
623
624 void Control::ClearBackground()
625 {
626   if ( mImpl->mBackground )
627   {
628     Background& background( mImpl->GetBackground() );
629     mImpl->mAddRemoveBackgroundChild = true;
630     Self().Remove( background.actor );
631     mImpl->mAddRemoveBackgroundChild = false;
632
633     delete mImpl->mBackground;
634     mImpl->mBackground = NULL;
635   }
636 }
637
638 void Control::EnableGestureDetection(Gesture::Type type)
639 {
640   if ( (type & Gesture::Pinch) && !mImpl->mPinchGestureDetector )
641   {
642     mImpl->mPinchGestureDetector = PinchGestureDetector::New();
643     mImpl->mPinchGestureDetector.DetectedSignal().Connect(mImpl, &Impl::PinchDetected);
644     mImpl->mPinchGestureDetector.Attach(Self());
645   }
646
647   if ( (type & Gesture::Pan) && !mImpl->mPanGestureDetector )
648   {
649     mImpl->mPanGestureDetector = PanGestureDetector::New();
650     mImpl->mPanGestureDetector.DetectedSignal().Connect(mImpl, &Impl::PanDetected);
651     mImpl->mPanGestureDetector.Attach(Self());
652   }
653
654   if ( (type & Gesture::Tap) && !mImpl->mTapGestureDetector )
655   {
656     mImpl->mTapGestureDetector = TapGestureDetector::New();
657     mImpl->mTapGestureDetector.DetectedSignal().Connect(mImpl, &Impl::TapDetected);
658     mImpl->mTapGestureDetector.Attach(Self());
659   }
660
661   if ( (type & Gesture::LongPress) && !mImpl->mLongPressGestureDetector )
662   {
663     mImpl->mLongPressGestureDetector = LongPressGestureDetector::New();
664     mImpl->mLongPressGestureDetector.DetectedSignal().Connect(mImpl, &Impl::LongPressDetected);
665     mImpl->mLongPressGestureDetector.Attach(Self());
666   }
667 }
668
669 void Control::DisableGestureDetection(Gesture::Type type)
670 {
671   if ( (type & Gesture::Pinch) && mImpl->mPinchGestureDetector )
672   {
673     mImpl->mPinchGestureDetector.Detach(Self());
674     mImpl->mPinchGestureDetector.Reset();
675   }
676
677   if ( (type & Gesture::Pan) && mImpl->mPanGestureDetector )
678   {
679     mImpl->mPanGestureDetector.Detach(Self());
680     mImpl->mPanGestureDetector.Reset();
681   }
682
683   if ( (type & Gesture::Tap) && mImpl->mTapGestureDetector )
684   {
685     mImpl->mTapGestureDetector.Detach(Self());
686     mImpl->mTapGestureDetector.Reset();
687   }
688
689   if ( (type & Gesture::LongPress) && mImpl->mLongPressGestureDetector)
690   {
691     mImpl->mLongPressGestureDetector.Detach(Self());
692     mImpl->mLongPressGestureDetector.Reset();
693   }
694 }
695
696 PinchGestureDetector Control::GetPinchGestureDetector() const
697 {
698   return mImpl->mPinchGestureDetector;
699 }
700
701 PanGestureDetector Control::GetPanGestureDetector() const
702 {
703   return mImpl->mPanGestureDetector;
704 }
705
706 TapGestureDetector Control::GetTapGestureDetector() const
707 {
708   return mImpl->mTapGestureDetector;
709 }
710
711 LongPressGestureDetector Control::GetLongPressGestureDetector() const
712 {
713   return mImpl->mLongPressGestureDetector;
714 }
715
716 void Control::SetKeyboardNavigationSupport(bool isSupported)
717 {
718   mImpl->mIsKeyboardNavigationSupported = isSupported;
719 }
720
721 bool Control::IsKeyboardNavigationSupported()
722 {
723   return mImpl->mIsKeyboardNavigationSupported;
724 }
725
726 void Control::SetKeyInputFocus()
727 {
728   if( Self().OnStage() )
729   {
730     Toolkit::KeyInputFocusManager::Get().SetFocus(Toolkit::Control::DownCast(Self()));
731   }
732 }
733
734 bool Control::HasKeyInputFocus()
735 {
736   bool result = false;
737   if( Self().OnStage() )
738   {
739     result = Toolkit::KeyInputFocusManager::Get().IsKeyboardListener(Toolkit::Control::DownCast(Self()));
740   }
741   return result;
742 }
743
744 void Control::ClearKeyInputFocus()
745 {
746   if( Self().OnStage() )
747   {
748     Toolkit::KeyInputFocusManager::Get().RemoveFocus(Toolkit::Control::DownCast(Self()));
749   }
750 }
751
752 void Control::SetAsKeyboardFocusGroup(bool isFocusGroup)
753 {
754   mImpl->mIsKeyboardFocusGroup = isFocusGroup;
755
756   // The following line will be removed when the deprecated API in KeyboardFocusManager is deleted
757   Toolkit::KeyboardFocusManager::Get().SetAsFocusGroup(Self(), isFocusGroup);
758 }
759
760 bool Control::IsKeyboardFocusGroup()
761 {
762   return Toolkit::KeyboardFocusManager::Get().IsFocusGroup(Self());
763 }
764
765 void Control::AccessibilityActivate()
766 {
767   // Inform deriving classes
768   OnAccessibilityActivated();
769 }
770
771 void Control::KeyboardEnter()
772 {
773   // Inform deriving classes
774   OnKeyboardEnter();
775 }
776
777 bool Control::OnAccessibilityActivated()
778 {
779   return false; // Accessibility activation is not handled by default
780 }
781
782 bool Control::OnKeyboardEnter()
783 {
784   return false; // Keyboard enter is not handled by default
785 }
786
787 bool Control::OnAccessibilityPan(PanGesture gesture)
788 {
789   return false; // Accessibility pan gesture is not handled by default
790 }
791
792 bool Control::OnAccessibilityTouch(const TouchEvent& touchEvent)
793 {
794   return false; // Accessibility touch event is not handled by default
795 }
796
797 bool Control::OnAccessibilityValueChange(bool isIncrease)
798 {
799   return false; // Accessibility value change action is not handled by default
800 }
801
802 bool Control::OnAccessibilityZoom()
803 {
804   return false; // Accessibility zoom action is not handled by default
805 }
806
807 Actor Control::GetNextKeyboardFocusableActor(Actor currentFocusedActor, Toolkit::Control::KeyboardFocus::Direction direction, bool loopEnabled)
808 {
809   return Actor();
810 }
811
812 void Control::OnKeyboardFocusChangeCommitted(Actor commitedFocusableActor)
813 {
814 }
815
816 Toolkit::Control::KeyEventSignalType& Control::KeyEventSignal()
817 {
818   return mImpl->mKeyEventSignal;
819 }
820
821 Toolkit::Control::KeyInputFocusSignalType& Control:: KeyInputFocusGainedSignal()
822 {
823   return mImpl->mKeyInputFocusGainedSignal;
824 }
825
826 Toolkit::Control::KeyInputFocusSignalType& Control:: KeyInputFocusLostSignal()
827 {
828   return mImpl->mKeyInputFocusLostSignal;
829 }
830
831 bool Control::EmitKeyEventSignal( const KeyEvent& event )
832 {
833   // Guard against destruction during signal emission
834   Dali::Toolkit::Control handle( GetOwner() );
835
836   bool consumed = false;
837
838   // signals are allocated dynamically when someone connects
839   if ( !mImpl->mKeyEventSignal.Empty() )
840   {
841     consumed = mImpl->mKeyEventSignal.Emit( handle, event );
842   }
843
844   if (!consumed)
845   {
846     // Notification for derived classes
847     consumed = OnKeyEvent(event);
848   }
849
850   return consumed;
851 }
852
853 Control::Control( ControlBehaviour behaviourFlags )
854 : CustomActorImpl( static_cast< ActorFlags >( behaviourFlags ) ),
855   mImpl(new Impl(*this))
856 {
857   mImpl->mFlags = behaviourFlags;
858 }
859
860 void Control::Initialize()
861 {
862   // Call deriving classes so initialised before styling is applied to them.
863   OnInitialize();
864
865   if( mImpl->mFlags & REQUIRES_STYLE_CHANGE_SIGNALS )
866   {
867     Toolkit::StyleManager styleManager = Toolkit::StyleManager::Get();
868
869     // Register for style changes
870     styleManager.StyleChangeSignal().Connect( this, &Control::OnStyleChange );
871
872     // Apply the current style
873     GetImpl( styleManager ).ApplyThemeStyle( Toolkit::Control( GetOwner() ) );
874   }
875
876   if( mImpl->mFlags & REQUIRES_KEYBOARD_NAVIGATION_SUPPORT )
877   {
878     SetKeyboardNavigationSupport( true );
879   }
880 }
881
882 void Control::OnInitialize()
883 {
884 }
885
886 void Control::OnControlChildAdd( Actor& child )
887 {
888 }
889
890 void Control::OnControlChildRemove( Actor& child )
891 {
892 }
893
894 void Control::OnStyleChange( Toolkit::StyleManager styleManager, StyleChange::Type change )
895 {
896   // By default the control is only interested in theme (not font) changes
897   if( change == StyleChange::THEME_CHANGE )
898   {
899     GetImpl( styleManager ).ApplyThemeStyle( Toolkit::Control( GetOwner() ) );
900   }
901 }
902
903 void Control::OnPinch(const PinchGesture& pinch)
904 {
905   if( !( mImpl->mStartingPinchScale ) )
906   {
907     // lazy allocate
908     mImpl->mStartingPinchScale = new Vector3;
909   }
910
911   if( pinch.state == Gesture::Started )
912   {
913     *( mImpl->mStartingPinchScale ) = Self().GetCurrentScale();
914   }
915
916   Self().SetScale( *( mImpl->mStartingPinchScale ) * pinch.scale );
917 }
918
919 void Control::OnPan( const PanGesture& pan )
920 {
921 }
922
923 void Control::OnTap(const TapGesture& tap)
924 {
925 }
926
927 void Control::OnLongPress( const LongPressGesture& longPress )
928 {
929 }
930
931 void Control::EmitKeyInputFocusSignal( bool focusGained )
932 {
933   Dali::Toolkit::Control handle( GetOwner() );
934
935   if ( focusGained )
936   {
937     // signals are allocated dynamically when someone connects
938     if ( !mImpl->mKeyInputFocusGainedSignal.Empty() )
939     {
940       mImpl->mKeyInputFocusGainedSignal.Emit( handle );
941     }
942   }
943   else
944   {
945     // signals are allocated dynamically when someone connects
946     if ( !mImpl->mKeyInputFocusLostSignal.Empty() )
947     {
948       mImpl->mKeyInputFocusLostSignal.Emit( handle );
949     }
950   }
951 }
952
953 void Control::OnStageConnection( int depth )
954 {
955   unsigned int controlRendererCount = Self().GetRendererCount();
956   for( unsigned int i(0); i<controlRendererCount; ++i )
957   {
958     Renderer controlRenderer = Self().GetRendererAt(i);
959     if( controlRenderer )
960     {
961       controlRenderer.SetDepthIndex( CONTENT_DEPTH_INDEX+depth );
962     }
963   }
964
965   if( mImpl->mBackground )
966   {
967     if(mImpl->mBackground->actor.GetRendererCount() > 0 )
968     {
969       Renderer backgroundRenderer = mImpl->mBackground->actor.GetRendererAt( 0 );
970       if(backgroundRenderer)
971       {
972         backgroundRenderer.SetDepthIndex( BACKGROUND_DEPTH_INDEX+depth );
973       }
974     }
975     else
976     {
977
978       ImageActor imageActor = ImageActor::DownCast( mImpl->mBackground->actor );
979       if ( imageActor )
980       {
981         imageActor.SetSortModifier( BACKGROUND_DEPTH_INDEX+depth );
982       }
983     }
984   }
985 }
986
987 void Control::OnStageDisconnection()
988 {
989 }
990
991 void Control::OnKeyInputFocusGained()
992 {
993   EmitKeyInputFocusSignal( true );
994 }
995
996 void Control::OnKeyInputFocusLost()
997 {
998   EmitKeyInputFocusSignal( false );
999 }
1000
1001 void Control::OnChildAdd(Actor& child)
1002 {
1003   // If this is the background actor, then we do not want to inform deriving classes
1004   if ( mImpl->mAddRemoveBackgroundChild )
1005   {
1006     return;
1007   }
1008
1009   // Notify derived classes.
1010   OnControlChildAdd( child );
1011 }
1012
1013 void Control::OnChildRemove(Actor& child)
1014 {
1015   // If this is the background actor, then we do not want to inform deriving classes
1016   if ( mImpl->mAddRemoveBackgroundChild )
1017   {
1018     return;
1019   }
1020
1021   // Notify derived classes.
1022   OnControlChildRemove( child );
1023 }
1024
1025 void Control::OnSizeSet(const Vector3& targetSize)
1026 {
1027   // Background is resized through size negotiation
1028 }
1029
1030 void Control::OnSizeAnimation(Animation& animation, const Vector3& targetSize)
1031 {
1032   // @todo size negotiate background to new size, animate as well?
1033 }
1034
1035 bool Control::OnTouchEvent(const TouchEvent& event)
1036 {
1037   return false; // Do not consume
1038 }
1039
1040 bool Control::OnHoverEvent(const HoverEvent& event)
1041 {
1042   return false; // Do not consume
1043 }
1044
1045 bool Control::OnKeyEvent(const KeyEvent& event)
1046 {
1047   return false; // Do not consume
1048 }
1049
1050 bool Control::OnWheelEvent(const WheelEvent& event)
1051 {
1052   return false; // Do not consume
1053 }
1054
1055 void Control::OnRelayout( const Vector2& size, RelayoutContainer& container )
1056 {
1057   for( unsigned int i = 0, numChildren = Self().GetChildCount(); i < numChildren; ++i )
1058   {
1059     container.Add( Self().GetChildAt( i ), size );
1060   }
1061 }
1062
1063 void Control::OnSetResizePolicy( ResizePolicy::Type policy, Dimension::Type dimension )
1064 {
1065 }
1066
1067 Vector3 Control::GetNaturalSize()
1068 {
1069   //Control's natural size is the size of its background image if it has been set, or ZERO otherwise
1070   Vector3 naturalSize = Vector3::ZERO;
1071   if( mImpl->mBackground )
1072   {
1073     if( mImpl->mBackground->actor.GetRendererCount() > 0 )
1074     {
1075       Material backgroundMaterial = mImpl->mBackground->actor.GetRendererAt(0).GetMaterial();
1076       if( backgroundMaterial.GetNumberOfSamplers() > 0 )
1077       {
1078         Image backgroundImage =  backgroundMaterial.GetSamplerAt(0).GetImage();
1079         if( backgroundImage )
1080         {
1081           naturalSize.x = backgroundImage.GetWidth();
1082           naturalSize.y = backgroundImage.GetHeight();
1083         }
1084       }
1085     }
1086     else
1087     {
1088       return mImpl->mBackground->actor.GetNaturalSize();
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