Change control background to use ImageActor
[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_CONTROL_ACTIVATED = "control-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_CONTROL_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_CONTROL_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 bool Control::OnAccessibilityActivated()
771 {
772   return false; // Accessibility activation is not handled by default
773 }
774
775 bool Control::OnAccessibilityPan(PanGesture gesture)
776 {
777   return false; // Accessibility pan gesture is not handled by default
778 }
779
780 bool Control::OnAccessibilityTouch(const TouchEvent& touchEvent)
781 {
782   return false; // Accessibility touch event is not handled by default
783 }
784
785 bool Control::OnAccessibilityValueChange(bool isIncrease)
786 {
787   return false; // Accessibility value change action is not handled by default
788 }
789
790 Actor Control::GetNextKeyboardFocusableActor(Actor currentFocusedActor, Toolkit::Control::KeyboardFocus::Direction direction, bool loopEnabled)
791 {
792   return Actor();
793 }
794
795 void Control::OnKeyboardFocusChangeCommitted(Actor commitedFocusableActor)
796 {
797 }
798
799 Toolkit::Control::KeyEventSignalType& Control::KeyEventSignal()
800 {
801   return mImpl->mKeyEventSignal;
802 }
803
804 Toolkit::Control::KeyInputFocusSignalType& Control:: KeyInputFocusGainedSignal()
805 {
806   return mImpl->mKeyInputFocusGainedSignal;
807 }
808
809 Toolkit::Control::KeyInputFocusSignalType& Control:: KeyInputFocusLostSignal()
810 {
811   return mImpl->mKeyInputFocusLostSignal;
812 }
813
814 bool Control::EmitKeyEventSignal( const KeyEvent& event )
815 {
816   // Guard against destruction during signal emission
817   Dali::Toolkit::Control handle( GetOwner() );
818
819   bool consumed = false;
820
821   // signals are allocated dynamically when someone connects
822   if ( !mImpl->mKeyEventSignal.Empty() )
823   {
824     consumed = mImpl->mKeyEventSignal.Emit( handle, event );
825   }
826
827   if (!consumed)
828   {
829     // Notification for derived classes
830     consumed = OnKeyEvent(event);
831   }
832
833   return consumed;
834 }
835
836 Control::Control( ControlBehaviour behaviourFlags )
837 : CustomActorImpl( static_cast< ActorFlags >( behaviourFlags ) ),
838   mImpl(new Impl(*this))
839 {
840   mImpl->mFlags = behaviourFlags;
841 }
842
843 void Control::Initialize()
844 {
845   // Call deriving classes so initialised before styling is applied to them.
846   OnInitialize();
847
848   if( mImpl->mFlags & REQUIRES_STYLE_CHANGE_SIGNALS )
849   {
850     Toolkit::StyleManager styleManager = Toolkit::StyleManager::Get();
851
852     // Register for style changes
853     styleManager.StyleChangeSignal().Connect( this, &Control::OnStyleChange );
854
855     // Apply the current style
856     GetImpl( styleManager ).ApplyThemeStyle( Toolkit::Control( GetOwner() ) );
857   }
858
859   if( mImpl->mFlags & REQUIRES_KEYBOARD_NAVIGATION_SUPPORT )
860   {
861     SetKeyboardNavigationSupport( true );
862   }
863 }
864
865 void Control::OnInitialize()
866 {
867 }
868
869 void Control::OnControlChildAdd( Actor& child )
870 {
871 }
872
873 void Control::OnControlChildRemove( Actor& child )
874 {
875 }
876
877 void Control::OnStyleChange( Toolkit::StyleManager styleManager, StyleChange::Type change )
878 {
879   // By default the control is only interested in theme (not font) changes
880   if( change == StyleChange::THEME_CHANGE )
881   {
882     GetImpl( styleManager ).ApplyThemeStyle( Toolkit::Control( GetOwner() ) );
883   }
884 }
885
886 void Control::OnPinch(const PinchGesture& pinch)
887 {
888   if( !( mImpl->mStartingPinchScale ) )
889   {
890     // lazy allocate
891     mImpl->mStartingPinchScale = new Vector3;
892   }
893
894   if( pinch.state == Gesture::Started )
895   {
896     *( mImpl->mStartingPinchScale ) = Self().GetCurrentScale();
897   }
898
899   Self().SetScale( *( mImpl->mStartingPinchScale ) * pinch.scale );
900 }
901
902 void Control::OnPan( const PanGesture& pan )
903 {
904 }
905
906 void Control::OnTap(const TapGesture& tap)
907 {
908 }
909
910 void Control::OnLongPress( const LongPressGesture& longPress )
911 {
912 }
913
914 void Control::EmitKeyInputFocusSignal( bool focusGained )
915 {
916   Dali::Toolkit::Control handle( GetOwner() );
917
918   if ( focusGained )
919   {
920     // signals are allocated dynamically when someone connects
921     if ( !mImpl->mKeyInputFocusGainedSignal.Empty() )
922     {
923       mImpl->mKeyInputFocusGainedSignal.Emit( handle );
924     }
925   }
926   else
927   {
928     // signals are allocated dynamically when someone connects
929     if ( !mImpl->mKeyInputFocusLostSignal.Empty() )
930     {
931       mImpl->mKeyInputFocusLostSignal.Emit( handle );
932     }
933   }
934 }
935
936 void Control::OnStageConnection( unsigned int depth )
937 {
938   unsigned int controlRendererCount = Self().GetRendererCount();
939   for( unsigned int i(0); i<controlRendererCount; ++i )
940   {
941     Renderer controlRenderer = Self().GetRendererAt(i);
942     if( controlRenderer )
943     {
944       controlRenderer.SetDepthIndex( CONTENT_DEPTH_INDEX+depth );
945     }
946   }
947
948   if( mImpl->mBackground )
949   {
950     if(mImpl->mBackground->actor.GetRendererCount() > 0 )
951     {
952       Renderer backgroundRenderer = mImpl->mBackground->actor.GetRendererAt( 0 );
953       if(backgroundRenderer)
954       {
955         backgroundRenderer.SetDepthIndex( BACKGROUND_DEPTH_INDEX+depth );
956       }
957     }
958     else
959     {
960
961       ImageActor imageActor = ImageActor::DownCast( mImpl->mBackground->actor );
962       if ( imageActor )
963       {
964         imageActor.SetSortModifier( BACKGROUND_DEPTH_INDEX+depth );
965       }
966     }
967   }
968 }
969
970 void Control::OnStageDisconnection()
971 {
972 }
973
974 void Control::OnKeyInputFocusGained()
975 {
976   EmitKeyInputFocusSignal( true );
977 }
978
979 void Control::OnKeyInputFocusLost()
980 {
981   EmitKeyInputFocusSignal( false );
982 }
983
984 void Control::OnChildAdd(Actor& child)
985 {
986   // If this is the background actor, then we do not want to inform deriving classes
987   if ( mImpl->mAddRemoveBackgroundChild )
988   {
989     return;
990   }
991
992   // Notify derived classes.
993   OnControlChildAdd( child );
994 }
995
996 void Control::OnChildRemove(Actor& child)
997 {
998   // If this is the background actor, then we do not want to inform deriving classes
999   if ( mImpl->mAddRemoveBackgroundChild )
1000   {
1001     return;
1002   }
1003
1004   // Notify derived classes.
1005   OnControlChildRemove( child );
1006 }
1007
1008 void Control::OnSizeSet(const Vector3& targetSize)
1009 {
1010   // Background is resized through size negotiation
1011 }
1012
1013 void Control::OnSizeAnimation(Animation& animation, const Vector3& targetSize)
1014 {
1015   // @todo size negotiate background to new size, animate as well?
1016 }
1017
1018 bool Control::OnTouchEvent(const TouchEvent& event)
1019 {
1020   return false; // Do not consume
1021 }
1022
1023 bool Control::OnHoverEvent(const HoverEvent& event)
1024 {
1025   return false; // Do not consume
1026 }
1027
1028 bool Control::OnKeyEvent(const KeyEvent& event)
1029 {
1030   return false; // Do not consume
1031 }
1032
1033 bool Control::OnWheelEvent(const WheelEvent& event)
1034 {
1035   return false; // Do not consume
1036 }
1037
1038 void Control::OnRelayout( const Vector2& size, RelayoutContainer& container )
1039 {
1040   for( unsigned int i = 0, numChildren = Self().GetChildCount(); i < numChildren; ++i )
1041   {
1042     container.Add( Self().GetChildAt( i ), size );
1043   }
1044 }
1045
1046 void Control::OnSetResizePolicy( ResizePolicy::Type policy, Dimension::Type dimension )
1047 {
1048 }
1049
1050 Vector3 Control::GetNaturalSize()
1051 {
1052   //Control's natural size is the size of its background image if it has been set, or ZERO otherwise
1053   Vector3 naturalSize = Vector3::ZERO;
1054   if( mImpl->mBackground )
1055   {
1056     if( mImpl->mBackground->actor.GetRendererCount() > 0 )
1057     {
1058       Material backgroundMaterial = mImpl->mBackground->actor.GetRendererAt(0).GetMaterial();
1059       if( backgroundMaterial.GetNumberOfSamplers() > 0 )
1060       {
1061         Image backgroundImage =  backgroundMaterial.GetSamplerAt(0).GetImage();
1062         if( backgroundImage )
1063         {
1064           naturalSize.x = backgroundImage.GetWidth();
1065           naturalSize.y = backgroundImage.GetHeight();
1066         }
1067       }
1068     }
1069     else
1070     {
1071       return mImpl->mBackground->actor.GetNaturalSize();
1072     }
1073   }
1074
1075   return naturalSize;
1076 }
1077
1078 float Control::CalculateChildSize( const Dali::Actor& child, Dimension::Type dimension )
1079 {
1080   return CalculateChildSizeBase( child, dimension );
1081 }
1082
1083 float Control::GetHeightForWidth( float width )
1084 {
1085   if( mImpl->mBackground )
1086   {
1087     Actor actor = mImpl->mBackground->actor;
1088     if( actor )
1089     {
1090       return actor.GetHeightForWidth( width );
1091     }
1092   }
1093   return GetHeightForWidthBase( width );
1094 }
1095
1096 float Control::GetWidthForHeight( float height )
1097 {
1098   if( mImpl->mBackground )
1099   {
1100     Actor actor = mImpl->mBackground->actor;
1101     if( actor )
1102     {
1103       return actor.GetWidthForHeight( height );
1104     }
1105   }
1106   return GetWidthForHeightBase( height );
1107 }
1108
1109 bool Control::RelayoutDependentOnChildren( Dimension::Type dimension )
1110 {
1111   return RelayoutDependentOnChildrenBase( dimension );
1112 }
1113
1114 void Control::OnCalculateRelayoutSize( Dimension::Type dimension )
1115 {
1116 }
1117
1118 void Control::OnLayoutNegotiated( float size, Dimension::Type dimension )
1119 {
1120 }
1121
1122 void Control::SignalConnected( SlotObserver* slotObserver, CallbackBase* callback )
1123 {
1124   mImpl->SignalConnected( slotObserver, callback );
1125 }
1126
1127 void Control::SignalDisconnected( SlotObserver* slotObserver, CallbackBase* callback )
1128 {
1129   mImpl->SignalDisconnected( slotObserver, callback );
1130 }
1131
1132 Control& GetImplementation( Dali::Toolkit::Control& handle )
1133 {
1134   CustomActorImpl& customInterface = handle.GetImplementation();
1135   // downcast to control
1136   Control& impl = dynamic_cast< Internal::Control& >( customInterface );
1137   return impl;
1138 }
1139
1140 const Control& GetImplementation( const Dali::Toolkit::Control& handle )
1141 {
1142   const CustomActorImpl& customInterface = handle.GetImplementation();
1143   // downcast to control
1144   const Control& impl = dynamic_cast< const Internal::Control& >( customInterface );
1145   return impl;
1146 }
1147
1148 } // namespace Internal
1149
1150 } // namespace Toolkit
1151
1152 } // namespace Dali