Control not always rendering background image depending on add order
[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/animation/constraint.h>
26 #include <dali/public-api/animation/constraints.h>
27 #include <dali/public-api/object/type-registry.h>
28 #include <dali/public-api/size-negotiation/relayout-container.h>
29 #include <dali/devel-api/object/type-registry-helper.h>
30 #include <dali/devel-api/rendering/renderer.h>
31 #include <dali/devel-api/scripting/scripting.h>
32 #include <dali/integration-api/debug.h>
33
34 // INTERNAL INCLUDES
35 #include <dali-toolkit/public-api/controls/control-depth-index-ranges.h>
36 #include <dali-toolkit/devel-api/controls/renderer-factory/renderer-factory.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 #include <dali-toolkit/internal/controls/renderers/color/color-renderer.h>
43 #include <dali-toolkit/internal/controls/renderers/image/image-renderer.h>
44
45 namespace Dali
46 {
47
48 namespace Toolkit
49 {
50
51 namespace
52 {
53
54 /**
55  * Creates control through type registry
56  */
57 BaseHandle Create()
58 {
59   return Internal::Control::New();
60 }
61
62 /**
63  * Performs actions as requested using the action name.
64  * @param[in] object The object on which to perform the action.
65  * @param[in] actionName The action to perform.
66  * @param[in] attributes The attributes with which to perfrom this action.
67  * @return true if action has been accepted by this control
68  */
69 const char* ACTION_ACCESSIBILITY_ACTIVATED = "accessibilityActivated";
70 static bool DoAction( BaseObject* object, const std::string& actionName, const Property::Map& attributes )
71 {
72   bool ret = false;
73
74   if( object && ( 0 == strcmp( actionName.c_str(), ACTION_ACCESSIBILITY_ACTIVATED ) ) )
75   {
76     Toolkit::Control control = Toolkit::Control::DownCast( BaseHandle( object ) );
77     if( control )
78     {
79       // if cast succeeds there is an implementation so no need to check
80       ret = Internal::GetImplementation( control ).OnAccessibilityActivated();
81     }
82   }
83
84   return ret;
85 }
86
87 /**
88  * Connects a callback function with the object's signals.
89  * @param[in] object The object providing the signal.
90  * @param[in] tracker Used to disconnect the signal.
91  * @param[in] signalName The signal to connect to.
92  * @param[in] functor A newly allocated FunctorDelegate.
93  * @return True if the signal was connected.
94  * @post If a signal was connected, ownership of functor was passed to CallbackBase. Otherwise the caller is responsible for deleting the unused functor.
95  */
96 const char* SIGNAL_KEY_EVENT = "keyEvent";
97 const char* SIGNAL_KEY_INPUT_FOCUS_GAINED = "keyInputFocusGained";
98 const char* SIGNAL_KEY_INPUT_FOCUS_LOST = "keyInputFocusLost";
99 const char* SIGNAL_TAPPED = "tapped";
100 const char* SIGNAL_PANNED = "panned";
101 const char* SIGNAL_PINCHED = "pinched";
102 const char* SIGNAL_LONG_PRESSED = "longPressed";
103 static bool DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
104 {
105   Dali::BaseHandle handle( object );
106
107   bool connected( false );
108   Toolkit::Control control = Toolkit::Control::DownCast( handle );
109   if ( control )
110   {
111     Internal::Control& controlImpl( Internal::GetImplementation( control ) );
112     connected = true;
113
114     if ( 0 == strcmp( signalName.c_str(), SIGNAL_KEY_EVENT ) )
115     {
116       controlImpl.KeyEventSignal().Connect( tracker, functor );
117     }
118     else if( 0 == strcmp( signalName.c_str(), SIGNAL_KEY_INPUT_FOCUS_GAINED ) )
119     {
120       controlImpl.KeyInputFocusGainedSignal().Connect( tracker, functor );
121     }
122     else if( 0 == strcmp( signalName.c_str(), SIGNAL_KEY_INPUT_FOCUS_LOST ) )
123     {
124       controlImpl.KeyInputFocusLostSignal().Connect( tracker, functor );
125     }
126     else if( 0 == strcmp( signalName.c_str(), SIGNAL_TAPPED ) )
127     {
128       controlImpl.EnableGestureDetection( Gesture::Tap );
129       controlImpl.GetTapGestureDetector().DetectedSignal().Connect( tracker, functor );
130     }
131     else if( 0 == strcmp( signalName.c_str(), SIGNAL_PANNED ) )
132     {
133       controlImpl.EnableGestureDetection( Gesture::Pan );
134       controlImpl.GetPanGestureDetector().DetectedSignal().Connect( tracker, functor );
135     }
136     else if( 0 == strcmp( signalName.c_str(), SIGNAL_PINCHED ) )
137     {
138       controlImpl.EnableGestureDetection( Gesture::Pinch );
139       controlImpl.GetPinchGestureDetector().DetectedSignal().Connect( tracker, functor );
140     }
141     else if( 0 == strcmp( signalName.c_str(), SIGNAL_LONG_PRESSED ) )
142     {
143       controlImpl.EnableGestureDetection( Gesture::LongPress );
144       controlImpl.GetLongPressGestureDetector().DetectedSignal().Connect( tracker, functor );
145     }
146   }
147   return connected;
148 }
149
150 // Setup signals and actions using the type-registry.
151 DALI_TYPE_REGISTRATION_BEGIN( Control, CustomActor, Create );
152
153 // Note: Properties are registered separately below.
154
155 SignalConnectorType registerSignal1( typeRegistration, SIGNAL_KEY_EVENT, &DoConnectSignal );
156 SignalConnectorType registerSignal2( typeRegistration, SIGNAL_KEY_INPUT_FOCUS_GAINED, &DoConnectSignal );
157 SignalConnectorType registerSignal3( typeRegistration, SIGNAL_KEY_INPUT_FOCUS_LOST, &DoConnectSignal );
158 SignalConnectorType registerSignal4( typeRegistration, SIGNAL_TAPPED, &DoConnectSignal );
159 SignalConnectorType registerSignal5( typeRegistration, SIGNAL_PANNED, &DoConnectSignal );
160 SignalConnectorType registerSignal6( typeRegistration, SIGNAL_PINCHED, &DoConnectSignal );
161 SignalConnectorType registerSignal7( typeRegistration, SIGNAL_LONG_PRESSED, &DoConnectSignal );
162
163 TypeAction registerAction( typeRegistration, ACTION_ACCESSIBILITY_ACTIVATED, &DoAction );
164
165 DALI_TYPE_REGISTRATION_END()
166
167 const char * const BACKGROUND_COLOR_NAME("color");
168
169 } // unnamed namespace
170
171 namespace Internal
172 {
173
174 class Control::Impl : public ConnectionTracker
175 {
176 public:
177
178   // Construction & Destruction
179   Impl(Control& controlImpl)
180 : mControlImpl( controlImpl ),
181   mStyleName(""),
182   mBackgroundRenderer(),
183   mStartingPinchScale( NULL ),
184   mKeyEventSignal(),
185   mPinchGestureDetector(),
186   mPanGestureDetector(),
187   mTapGestureDetector(),
188   mLongPressGestureDetector(),
189   mFlags( Control::ControlBehaviour( ACTOR_BEHAVIOUR_NONE ) ),
190   mIsKeyboardNavigationSupported( false ),
191   mIsKeyboardFocusGroup( false ),
192   mAddRemoveBackgroundChild( false )
193 {
194 }
195
196   ~Impl()
197   {
198     // All gesture detectors will be destroyed so no need to disconnect.
199     delete mStartingPinchScale;
200   }
201
202   // Gesture Detection Methods
203
204   void PinchDetected(Actor actor, const PinchGesture& pinch)
205   {
206     mControlImpl.OnPinch(pinch);
207   }
208
209   void PanDetected(Actor actor, const PanGesture& pan)
210   {
211     mControlImpl.OnPan(pan);
212   }
213
214   void TapDetected(Actor actor, const TapGesture& tap)
215   {
216     mControlImpl.OnTap(tap);
217   }
218
219   void LongPressDetected(Actor actor, const LongPressGesture& longPress)
220   {
221     mControlImpl.OnLongPress(longPress);
222   }
223
224   // Properties
225
226   /**
227    * Called when a property of an object of this type is set.
228    * @param[in] object The object whose property is set.
229    * @param[in] index The property index.
230    * @param[in] value The new property value.
231    */
232   static void SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
233   {
234     Toolkit::Control control = Toolkit::Control::DownCast( BaseHandle( object ) );
235
236     if ( control )
237     {
238       Control& controlImpl( GetImplementation( control ) );
239
240       switch ( index )
241       {
242         case Toolkit::Control::Property::STYLE_NAME:
243         {
244           controlImpl.SetStyleName( value.Get< std::string >() );
245           break;
246         }
247         case Toolkit::Control::Property::BACKGROUND:
248         {
249           Image image = Scripting::NewImage( value );
250           if ( image )
251           {
252             controlImpl.SetBackgroundImage( image );
253             break;
254           }
255           const Property::Map* map = value.GetMap();
256           if( map )
257           {
258             controlImpl.SetBackground( *map );
259             break;
260           }
261
262           // The background is neither a valid image nor a property map, so it is no longer required
263           controlImpl.ClearBackground();
264           break;
265         }
266
267         case Toolkit::Control::Property::KEY_INPUT_FOCUS:
268         {
269           if ( value.Get< bool >() )
270           {
271             controlImpl.SetKeyInputFocus();
272           }
273           else
274           {
275             controlImpl.ClearKeyInputFocus();
276           }
277           break;
278         }
279       }
280     }
281   }
282
283   /**
284    * Called to retrieve a property of an object of this type.
285    * @param[in] object The object whose property is to be retrieved.
286    * @param[in] index The property index.
287    * @return The current value of the property.
288    */
289   static Property::Value GetProperty( BaseObject* object, Property::Index index )
290   {
291     Property::Value value;
292
293     Toolkit::Control control = Toolkit::Control::DownCast( BaseHandle( object ) );
294
295     if ( control )
296     {
297       Control& controlImpl( GetImplementation( control ) );
298
299       switch ( index )
300       {
301         case Toolkit::Control::Property::STYLE_NAME:
302         {
303           value = controlImpl.GetStyleName();
304           break;
305         }
306
307         case Toolkit::Control::Property::BACKGROUND:
308         {
309           Property::Map map;
310           if( controlImpl.mImpl->mBackgroundRenderer )
311           {
312             (controlImpl.mImpl->mBackgroundRenderer).CreatePropertyMap( map );
313           }
314
315           value = map;
316           break;
317         }
318
319         case Toolkit::Control::Property::KEY_INPUT_FOCUS:
320         {
321           value = controlImpl.HasKeyInputFocus();
322           break;
323         }
324       }
325     }
326
327     return value;
328   }
329
330   // Data
331
332   Control& mControlImpl;
333   std::string mStyleName;
334   Toolkit::ControlRenderer mBackgroundRenderer;   ///< The control renderer to render the background
335   Vector3* mStartingPinchScale;      ///< The scale when a pinch gesture starts, TODO: consider removing this
336   Toolkit::Control::KeyEventSignalType mKeyEventSignal;
337   Toolkit::Control::KeyInputFocusSignalType mKeyInputFocusGainedSignal;
338   Toolkit::Control::KeyInputFocusSignalType mKeyInputFocusLostSignal;
339
340   // Gesture Detection
341   PinchGestureDetector mPinchGestureDetector;
342   PanGestureDetector mPanGestureDetector;
343   TapGestureDetector mTapGestureDetector;
344   LongPressGestureDetector mLongPressGestureDetector;
345
346   ControlBehaviour mFlags :CONTROL_BEHAVIOUR_FLAG_COUNT;    ///< Flags passed in from constructor.
347   bool mIsKeyboardNavigationSupported :1;  ///< Stores whether keyboard navigation is supported by the control.
348   bool mIsKeyboardFocusGroup :1;           ///< Stores whether the control is a focus group.
349   bool mAddRemoveBackgroundChild:1;        ///< Flag to know when we are adding or removing our own actor to avoid call to OnControlChildAdd
350
351   // Properties - these need to be members of Internal::Control::Impl as they need to function within this class.
352   static PropertyRegistration PROPERTY_1;
353   static PropertyRegistration PROPERTY_2;
354   static PropertyRegistration PROPERTY_3;
355 };
356
357 // Properties registered without macro to use specific member variables.
358 PropertyRegistration Control::Impl::PROPERTY_1( typeRegistration, "styleName",       Toolkit::Control::Property::STYLE_NAME,      Property::STRING,  &Control::Impl::SetProperty, &Control::Impl::GetProperty );
359 PropertyRegistration Control::Impl::PROPERTY_2( typeRegistration, "background",      Toolkit::Control::Property::BACKGROUND,      Property::MAP,     &Control::Impl::SetProperty, &Control::Impl::GetProperty );
360 PropertyRegistration Control::Impl::PROPERTY_3( typeRegistration, "keyInputFocus",   Toolkit::Control::Property::KEY_INPUT_FOCUS, Property::BOOLEAN, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
361
362 Toolkit::Control Control::New()
363 {
364   // Create the implementation, temporarily owned on stack
365   IntrusivePtr<Control> controlImpl = new Control( ControlBehaviour( ACTOR_BEHAVIOUR_NONE ) );
366
367   // Pass ownership to handle
368   Toolkit::Control handle( *controlImpl );
369
370   // Second-phase init of the implementation
371   // This can only be done after the CustomActor connection has been made...
372   controlImpl->Initialize();
373
374   return handle;
375 }
376
377 Control::~Control()
378 {
379   delete mImpl;
380 }
381
382 void Control::SetStyleName( const std::string& styleName )
383 {
384   if( styleName != mImpl->mStyleName )
385   {
386     mImpl->mStyleName = styleName;
387
388     // Apply new style, if stylemanager is available
389     Toolkit::StyleManager styleManager = Toolkit::StyleManager::Get();
390     if( styleManager )
391     {
392       GetImpl( styleManager ).ApplyThemeStyle( Toolkit::Control( GetOwner() ) );
393     }
394   }
395 }
396
397 const std::string& Control::GetStyleName() const
398 {
399   return mImpl->mStyleName;
400 }
401
402 void Control::UpdateBackgroundState()
403 {
404   // Set the depth of the background renderer after creating/modifying it.
405   // We do this regardless of whether or not it is on stage as the index
406   // is relative and still valid if this control is re-parented.
407   if( mImpl->mBackgroundRenderer )
408   {
409     mImpl->mBackgroundRenderer.SetDepthIndex( BACKGROUND_DEPTH_INDEX );
410
411     Actor self( Self() );
412     if( self.OnStage() )
413     {
414       mImpl->mBackgroundRenderer.SetOnStage( self );
415     }
416   }
417 }
418
419 void Control::SetBackgroundColor( const Vector4& color )
420 {
421   Actor self( Self() );
422   Toolkit::RendererFactory factory = Toolkit::RendererFactory::Get();
423
424   if( mImpl->mBackgroundRenderer )
425   {
426     factory.ResetRenderer( mImpl->mBackgroundRenderer, self, color );
427   }
428   else
429   {
430     mImpl->mBackgroundRenderer = factory.GetControlRenderer( color );
431   }
432
433   UpdateBackgroundState();
434 }
435
436 Vector4 Control::GetBackgroundColor() const
437 {
438   return Color::TRANSPARENT;
439 }
440
441 void Control::SetBackground(const Property::Map& map)
442 {
443   const Property::Value* colorValue = map.Find( BACKGROUND_COLOR_NAME );
444   Vector4 color;
445   if( colorValue && colorValue->Get(color))
446   {
447     SetBackgroundColor( color );
448     return;
449   }
450
451   Actor self( Self() );
452   mImpl->mBackgroundRenderer.RemoveAndReset( self );
453
454   Toolkit::RendererFactory factory = Toolkit::RendererFactory::Get();
455   mImpl->mBackgroundRenderer = factory.GetControlRenderer( map );
456
457   UpdateBackgroundState();
458 }
459
460 void Control::SetBackgroundImage( Image image )
461 {
462   Actor self( Self() );
463   Toolkit::RendererFactory factory = Toolkit::RendererFactory::Get();
464
465   if(  mImpl->mBackgroundRenderer  )
466   {
467     factory.ResetRenderer( mImpl->mBackgroundRenderer, self, image );
468   }
469   else
470   {
471     mImpl->mBackgroundRenderer = factory.GetControlRenderer( image );
472   }
473
474   UpdateBackgroundState();
475 }
476
477 void Control::ClearBackground()
478 {
479   Actor self( Self() );
480   mImpl->mBackgroundRenderer.RemoveAndReset( self );
481 }
482
483 void Control::EnableGestureDetection(Gesture::Type type)
484 {
485   if ( (type & Gesture::Pinch) && !mImpl->mPinchGestureDetector )
486   {
487     mImpl->mPinchGestureDetector = PinchGestureDetector::New();
488     mImpl->mPinchGestureDetector.DetectedSignal().Connect(mImpl, &Impl::PinchDetected);
489     mImpl->mPinchGestureDetector.Attach(Self());
490   }
491
492   if ( (type & Gesture::Pan) && !mImpl->mPanGestureDetector )
493   {
494     mImpl->mPanGestureDetector = PanGestureDetector::New();
495     mImpl->mPanGestureDetector.DetectedSignal().Connect(mImpl, &Impl::PanDetected);
496     mImpl->mPanGestureDetector.Attach(Self());
497   }
498
499   if ( (type & Gesture::Tap) && !mImpl->mTapGestureDetector )
500   {
501     mImpl->mTapGestureDetector = TapGestureDetector::New();
502     mImpl->mTapGestureDetector.DetectedSignal().Connect(mImpl, &Impl::TapDetected);
503     mImpl->mTapGestureDetector.Attach(Self());
504   }
505
506   if ( (type & Gesture::LongPress) && !mImpl->mLongPressGestureDetector )
507   {
508     mImpl->mLongPressGestureDetector = LongPressGestureDetector::New();
509     mImpl->mLongPressGestureDetector.DetectedSignal().Connect(mImpl, &Impl::LongPressDetected);
510     mImpl->mLongPressGestureDetector.Attach(Self());
511   }
512 }
513
514 void Control::DisableGestureDetection(Gesture::Type type)
515 {
516   if ( (type & Gesture::Pinch) && mImpl->mPinchGestureDetector )
517   {
518     mImpl->mPinchGestureDetector.Detach(Self());
519     mImpl->mPinchGestureDetector.Reset();
520   }
521
522   if ( (type & Gesture::Pan) && mImpl->mPanGestureDetector )
523   {
524     mImpl->mPanGestureDetector.Detach(Self());
525     mImpl->mPanGestureDetector.Reset();
526   }
527
528   if ( (type & Gesture::Tap) && mImpl->mTapGestureDetector )
529   {
530     mImpl->mTapGestureDetector.Detach(Self());
531     mImpl->mTapGestureDetector.Reset();
532   }
533
534   if ( (type & Gesture::LongPress) && mImpl->mLongPressGestureDetector)
535   {
536     mImpl->mLongPressGestureDetector.Detach(Self());
537     mImpl->mLongPressGestureDetector.Reset();
538   }
539 }
540
541 PinchGestureDetector Control::GetPinchGestureDetector() const
542 {
543   return mImpl->mPinchGestureDetector;
544 }
545
546 PanGestureDetector Control::GetPanGestureDetector() const
547 {
548   return mImpl->mPanGestureDetector;
549 }
550
551 TapGestureDetector Control::GetTapGestureDetector() const
552 {
553   return mImpl->mTapGestureDetector;
554 }
555
556 LongPressGestureDetector Control::GetLongPressGestureDetector() const
557 {
558   return mImpl->mLongPressGestureDetector;
559 }
560
561 void Control::SetKeyboardNavigationSupport(bool isSupported)
562 {
563   mImpl->mIsKeyboardNavigationSupported = isSupported;
564 }
565
566 bool Control::IsKeyboardNavigationSupported()
567 {
568   return mImpl->mIsKeyboardNavigationSupported;
569 }
570
571 void Control::SetKeyInputFocus()
572 {
573   if( Self().OnStage() )
574   {
575     Toolkit::KeyInputFocusManager::Get().SetFocus(Toolkit::Control::DownCast(Self()));
576   }
577 }
578
579 bool Control::HasKeyInputFocus()
580 {
581   bool result = false;
582   if( Self().OnStage() )
583   {
584     result = Toolkit::KeyInputFocusManager::Get().IsKeyboardListener(Toolkit::Control::DownCast(Self()));
585   }
586   return result;
587 }
588
589 void Control::ClearKeyInputFocus()
590 {
591   if( Self().OnStage() )
592   {
593     Toolkit::KeyInputFocusManager::Get().RemoveFocus(Toolkit::Control::DownCast(Self()));
594   }
595 }
596
597 void Control::SetAsKeyboardFocusGroup(bool isFocusGroup)
598 {
599   mImpl->mIsKeyboardFocusGroup = isFocusGroup;
600
601   // The following line will be removed when the deprecated API in KeyboardFocusManager is deleted
602   Toolkit::KeyboardFocusManager::Get().SetAsFocusGroup(Self(), isFocusGroup);
603 }
604
605 bool Control::IsKeyboardFocusGroup()
606 {
607   return Toolkit::KeyboardFocusManager::Get().IsFocusGroup(Self());
608 }
609
610 void Control::AccessibilityActivate()
611 {
612   // Inform deriving classes
613   OnAccessibilityActivated();
614 }
615
616 void Control::KeyboardEnter()
617 {
618   // Inform deriving classes
619   OnKeyboardEnter();
620 }
621
622 bool Control::OnAccessibilityActivated()
623 {
624   return false; // Accessibility activation is not handled by default
625 }
626
627 bool Control::OnKeyboardEnter()
628 {
629   return false; // Keyboard enter is not handled by default
630 }
631
632 bool Control::OnAccessibilityPan(PanGesture gesture)
633 {
634   return false; // Accessibility pan gesture is not handled by default
635 }
636
637 bool Control::OnAccessibilityTouch(const TouchEvent& touchEvent)
638 {
639   return false; // Accessibility touch event is not handled by default
640 }
641
642 bool Control::OnAccessibilityValueChange(bool isIncrease)
643 {
644   return false; // Accessibility value change action is not handled by default
645 }
646
647 bool Control::OnAccessibilityZoom()
648 {
649   return false; // Accessibility zoom action is not handled by default
650 }
651
652 Actor Control::GetNextKeyboardFocusableActor(Actor currentFocusedActor, Toolkit::Control::KeyboardFocus::Direction direction, bool loopEnabled)
653 {
654   return Actor();
655 }
656
657 void Control::OnKeyboardFocusChangeCommitted(Actor commitedFocusableActor)
658 {
659 }
660
661 Toolkit::Control::KeyEventSignalType& Control::KeyEventSignal()
662 {
663   return mImpl->mKeyEventSignal;
664 }
665
666 Toolkit::Control::KeyInputFocusSignalType& Control:: KeyInputFocusGainedSignal()
667 {
668   return mImpl->mKeyInputFocusGainedSignal;
669 }
670
671 Toolkit::Control::KeyInputFocusSignalType& Control:: KeyInputFocusLostSignal()
672 {
673   return mImpl->mKeyInputFocusLostSignal;
674 }
675
676 bool Control::EmitKeyEventSignal( const KeyEvent& event )
677 {
678   // Guard against destruction during signal emission
679   Dali::Toolkit::Control handle( GetOwner() );
680
681   bool consumed = false;
682
683   // signals are allocated dynamically when someone connects
684   if ( !mImpl->mKeyEventSignal.Empty() )
685   {
686     consumed = mImpl->mKeyEventSignal.Emit( handle, event );
687   }
688
689   if (!consumed)
690   {
691     // Notification for derived classes
692     consumed = OnKeyEvent(event);
693   }
694
695   return consumed;
696 }
697
698 Control::Control( ControlBehaviour behaviourFlags )
699 : CustomActorImpl( static_cast< ActorFlags >( behaviourFlags ) ),
700   mImpl(new Impl(*this))
701 {
702   mImpl->mFlags = behaviourFlags;
703 }
704
705 void Control::Initialize()
706 {
707   // Call deriving classes so initialised before styling is applied to them.
708   OnInitialize();
709
710   if( mImpl->mFlags & REQUIRES_STYLE_CHANGE_SIGNALS )
711   {
712     Toolkit::StyleManager styleManager = Toolkit::StyleManager::Get();
713     // if stylemanager is available
714     if( styleManager )
715     {
716       // Register for style changes
717       styleManager.StyleChangeSignal().Connect( this, &Control::OnStyleChange );
718
719       // Apply the current style
720       GetImpl( styleManager ).ApplyThemeStyleAtInit( Toolkit::Control( GetOwner() ) );
721     }
722   }
723
724   if( mImpl->mFlags & REQUIRES_KEYBOARD_NAVIGATION_SUPPORT )
725   {
726     SetKeyboardNavigationSupport( true );
727   }
728 }
729
730 void Control::OnInitialize()
731 {
732 }
733
734 void Control::OnControlChildAdd( Actor& child )
735 {
736 }
737
738 void Control::OnControlChildRemove( Actor& child )
739 {
740 }
741
742 void Control::OnStyleChange( Toolkit::StyleManager styleManager, StyleChange::Type change )
743 {
744   // By default the control is only interested in theme (not font) changes
745   if( styleManager && change == StyleChange::THEME_CHANGE )
746   {
747     GetImpl( styleManager ).ApplyThemeStyle( Toolkit::Control( GetOwner() ) );
748   }
749 }
750
751 void Control::OnPinch(const PinchGesture& pinch)
752 {
753   if( !( mImpl->mStartingPinchScale ) )
754   {
755     // lazy allocate
756     mImpl->mStartingPinchScale = new Vector3;
757   }
758
759   if( pinch.state == Gesture::Started )
760   {
761     *( mImpl->mStartingPinchScale ) = Self().GetCurrentScale();
762   }
763
764   Self().SetScale( *( mImpl->mStartingPinchScale ) * pinch.scale );
765 }
766
767 void Control::OnPan( const PanGesture& pan )
768 {
769 }
770
771 void Control::OnTap(const TapGesture& tap)
772 {
773 }
774
775 void Control::OnLongPress( const LongPressGesture& longPress )
776 {
777 }
778
779 void Control::EmitKeyInputFocusSignal( bool focusGained )
780 {
781   Dali::Toolkit::Control handle( GetOwner() );
782
783   if ( focusGained )
784   {
785     // signals are allocated dynamically when someone connects
786     if ( !mImpl->mKeyInputFocusGainedSignal.Empty() )
787     {
788       mImpl->mKeyInputFocusGainedSignal.Emit( handle );
789     }
790   }
791   else
792   {
793     // signals are allocated dynamically when someone connects
794     if ( !mImpl->mKeyInputFocusLostSignal.Empty() )
795     {
796       mImpl->mKeyInputFocusLostSignal.Emit( handle );
797     }
798   }
799 }
800
801 void Control::OnStageConnection( int depth )
802 {
803   if( mImpl->mBackgroundRenderer)
804   {
805     Actor self( Self() );
806     mImpl->mBackgroundRenderer.SetOnStage( self );
807   }
808 }
809
810 void Control::OnStageDisconnection()
811 {
812   if( mImpl->mBackgroundRenderer )
813   {
814     Actor self( Self() );
815     mImpl->mBackgroundRenderer.SetOffStage( self );
816   }
817 }
818
819 void Control::OnKeyInputFocusGained()
820 {
821   EmitKeyInputFocusSignal( true );
822 }
823
824 void Control::OnKeyInputFocusLost()
825 {
826   EmitKeyInputFocusSignal( false );
827 }
828
829 void Control::OnChildAdd(Actor& child)
830 {
831   // If this is the background actor, then we do not want to inform deriving classes
832   if ( mImpl->mAddRemoveBackgroundChild )
833   {
834     return;
835   }
836
837   // Notify derived classes.
838   OnControlChildAdd( child );
839 }
840
841 void Control::OnChildRemove(Actor& child)
842 {
843   // If this is the background actor, then we do not want to inform deriving classes
844   if ( mImpl->mAddRemoveBackgroundChild )
845   {
846     return;
847   }
848
849   // Notify derived classes.
850   OnControlChildRemove( child );
851 }
852
853 void Control::OnSizeSet(const Vector3& targetSize)
854 {
855   // Background is resized through size negotiation
856 }
857
858 void Control::OnSizeAnimation(Animation& animation, const Vector3& targetSize)
859 {
860   // @todo size negotiate background to new size, animate as well?
861 }
862
863 bool Control::OnTouchEvent(const TouchEvent& event)
864 {
865   return false; // Do not consume
866 }
867
868 bool Control::OnHoverEvent(const HoverEvent& event)
869 {
870   return false; // Do not consume
871 }
872
873 bool Control::OnKeyEvent(const KeyEvent& event)
874 {
875   return false; // Do not consume
876 }
877
878 bool Control::OnWheelEvent(const WheelEvent& event)
879 {
880   return false; // Do not consume
881 }
882
883 void Control::OnRelayout( const Vector2& size, RelayoutContainer& container )
884 {
885   for( unsigned int i = 0, numChildren = Self().GetChildCount(); i < numChildren; ++i )
886   {
887     container.Add( Self().GetChildAt( i ), size );
888   }
889 }
890
891 void Control::OnSetResizePolicy( ResizePolicy::Type policy, Dimension::Type dimension )
892 {
893 }
894
895 Vector3 Control::GetNaturalSize()
896 {
897   if( mImpl->mBackgroundRenderer )
898   {
899     Vector2 naturalSize;
900     mImpl->mBackgroundRenderer.GetNaturalSize(naturalSize);
901     return Vector3(naturalSize);
902   }
903   return Vector3::ZERO;
904 }
905
906 float Control::CalculateChildSize( const Dali::Actor& child, Dimension::Type dimension )
907 {
908   return CalculateChildSizeBase( child, dimension );
909 }
910
911 float Control::GetHeightForWidth( float width )
912 {
913   return GetHeightForWidthBase( width );
914 }
915
916 float Control::GetWidthForHeight( float height )
917 {
918   return GetWidthForHeightBase( height );
919 }
920
921 bool Control::RelayoutDependentOnChildren( Dimension::Type dimension )
922 {
923   return RelayoutDependentOnChildrenBase( dimension );
924 }
925
926 void Control::OnCalculateRelayoutSize( Dimension::Type dimension )
927 {
928 }
929
930 void Control::OnLayoutNegotiated( float size, Dimension::Type dimension )
931 {
932 }
933
934 void Control::SignalConnected( SlotObserver* slotObserver, CallbackBase* callback )
935 {
936   mImpl->SignalConnected( slotObserver, callback );
937 }
938
939 void Control::SignalDisconnected( SlotObserver* slotObserver, CallbackBase* callback )
940 {
941   mImpl->SignalDisconnected( slotObserver, callback );
942 }
943
944 Control& GetImplementation( Dali::Toolkit::Control& handle )
945 {
946   CustomActorImpl& customInterface = handle.GetImplementation();
947   // downcast to control
948   Control& impl = dynamic_cast< Internal::Control& >( customInterface );
949   return impl;
950 }
951
952 const Control& GetImplementation( const Dali::Toolkit::Control& handle )
953 {
954   const CustomActorImpl& customInterface = handle.GetImplementation();
955   // downcast to control
956   const Control& impl = dynamic_cast< const Internal::Control& >( customInterface );
957   return impl;
958 }
959
960 } // namespace Internal
961
962 } // namespace Toolkit
963
964 } // namespace Dali