Visual bases checks if visual already staged before adding to stage
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / public-api / controls / control-impl.cpp
1 /*
2  * Copyright (c) 2016 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/object/type-registry-helper.h>
29 #include <dali/public-api/rendering/renderer.h>
30 #include <dali/public-api/size-negotiation/relayout-container.h>
31 #include <dali/devel-api/common/owner-container.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/focus-manager/keyboard-focus-manager.h>
37 #include <dali-toolkit/public-api/controls/control.h>
38 #include <dali-toolkit/public-api/styling/style-manager.h>
39 #include <dali-toolkit/public-api/visuals/color-visual-properties.h>
40 #include <dali-toolkit/devel-api/controls/control-depth-index-ranges.h>
41 #include <dali-toolkit/devel-api/visual-factory/devel-visual-properties.h>
42 #include <dali-toolkit/devel-api/visual-factory/visual-factory.h>
43 #include <dali-toolkit/devel-api/focus-manager/keyinput-focus-manager.h>
44 #include <dali-toolkit/internal/styling/style-manager-impl.h>
45 #include <dali-toolkit/internal/visuals/color/color-visual.h>
46 #include <dali-toolkit/internal/visuals/transition-data-impl.h>
47
48 namespace Dali
49 {
50
51 namespace Toolkit
52 {
53
54 namespace
55 {
56
57 #if defined(DEBUG_ENABLED)
58 Debug::Filter* gLogFilter = Debug::Filter::New( Debug::General, false, "LOG_CONTROL_VISUALS");
59 #endif
60
61 /**
62  * Struct used to store Visual within the control, index is a unique key for each visual.
63  */
64 struct RegisteredVisual
65 {
66   Property::Index index;
67   Toolkit::Visual::Base visual;
68   bool enabled;
69
70   RegisteredVisual( Property::Index aIndex, Toolkit::Visual::Base &aVisual, bool aEnabled) :
71                    index(aIndex), visual(aVisual), enabled(aEnabled) {}
72 };
73
74 struct HandleIndex
75 {
76   Handle handle; ///< a handle to the target object
77   Property::Index index; ///< The index of a property provided by the referenced object
78
79   HandleIndex( )
80   : handle(),
81     index( Property::INVALID_INDEX )
82   {
83   }
84
85   HandleIndex( Handle& handle, Property::Index index )
86   : handle( handle ),
87     index( index )
88   {
89   }
90 };
91
92
93 typedef Dali::OwnerContainer< RegisteredVisual* > RegisteredVisualContainer;
94
95 /**
96  *  Finds visual in given array, returning true if found along with the iterator for that visual as a out parameter
97  */
98 bool FindVisual( Property::Index targetIndex, RegisteredVisualContainer& visuals, RegisteredVisualContainer::Iterator& iter )
99 {
100   for ( iter = visuals.Begin(); iter != visuals.End(); iter++ )
101   {
102     if ( (*iter)->index ==  targetIndex )
103     {
104       return true;
105     }
106   }
107   return false;
108 }
109
110 HandleIndex GetVisualProperty(
111   Internal::Control& controlImpl,
112   RegisteredVisualContainer& visuals,
113   const std::string& visualName,
114   Property::Key propertyKey )
115 {
116 #if defined(DEBUG_ENABLED)
117   std::ostringstream oss;
118   oss << "Control::GetHandleIndex(" << visualName << ", " << propertyKey << ")" << std::endl;
119   DALI_LOG_INFO( gLogFilter, Debug::General, oss.str().c_str() );
120 #endif
121
122   // Find visualName in the control
123   RegisteredVisualContainer::Iterator iter;
124   for ( iter = visuals.Begin(); iter != visuals.End(); iter++ )
125   {
126     if ( (*iter)->visual.GetName() == visualName )
127     {
128       break;
129     }
130   }
131
132   // Does it's renderer have an associated property?
133   if( iter != visuals.End() )
134   {
135     Actor self = controlImpl.Self();
136     Property::Index index = self.GetPropertyIndex( propertyKey );
137     if( index != Property::INVALID_INDEX )
138     {
139       // It's an actor property:
140       return HandleIndex( self, index );
141     }
142     else
143     {
144       // Check if it is a renderer property:
145       if( self.GetRendererCount() > 0 )
146       {
147         // @todo Need to use correct renderer index
148         Renderer renderer = self.GetRendererAt(0);
149         Property::Index index = renderer.GetPropertyIndex( propertyKey );
150         if( index != Property::INVALID_INDEX )
151         {
152           // It's a renderer property:
153           return HandleIndex( renderer, index );
154         }
155       }
156       else
157       {
158         std::ostringstream oss;
159         oss << propertyKey;
160         DALI_LOG_WARNING( "Control::GetHandleIndex(%s, %s) No renderers\n", visualName.c_str(), oss.str().c_str() );
161       }
162     }
163   }
164   Handle handle;
165   return HandleIndex( handle, Property::INVALID_INDEX );
166 }
167
168
169 /**
170  * Creates control through type registry
171  */
172 BaseHandle Create()
173 {
174   return Internal::Control::New();
175 }
176
177 /**
178  * Performs actions as requested using the action name.
179  * @param[in] object The object on which to perform the action.
180  * @param[in] actionName The action to perform.
181  * @param[in] attributes The attributes with which to perfrom this action.
182  * @return true if action has been accepted by this control
183  */
184 const char* ACTION_ACCESSIBILITY_ACTIVATED = "accessibilityActivated";
185 static bool DoAction( BaseObject* object, const std::string& actionName, const Property::Map& attributes )
186 {
187   bool ret = false;
188
189   if( object && ( 0 == strcmp( actionName.c_str(), ACTION_ACCESSIBILITY_ACTIVATED ) ) )
190   {
191     Toolkit::Control control = Toolkit::Control::DownCast( BaseHandle( object ) );
192     if( control )
193     {
194       // if cast succeeds there is an implementation so no need to check
195       ret = Internal::GetImplementation( control ).OnAccessibilityActivated();
196     }
197   }
198
199   return ret;
200 }
201
202 /**
203  * Connects a callback function with the object's signals.
204  * @param[in] object The object providing the signal.
205  * @param[in] tracker Used to disconnect the signal.
206  * @param[in] signalName The signal to connect to.
207  * @param[in] functor A newly allocated FunctorDelegate.
208  * @return True if the signal was connected.
209  * @post If a signal was connected, ownership of functor was passed to CallbackBase. Otherwise the caller is responsible for deleting the unused functor.
210  */
211 const char* SIGNAL_KEY_EVENT = "keyEvent";
212 const char* SIGNAL_KEY_INPUT_FOCUS_GAINED = "keyInputFocusGained";
213 const char* SIGNAL_KEY_INPUT_FOCUS_LOST = "keyInputFocusLost";
214 const char* SIGNAL_TAPPED = "tapped";
215 const char* SIGNAL_PANNED = "panned";
216 const char* SIGNAL_PINCHED = "pinched";
217 const char* SIGNAL_LONG_PRESSED = "longPressed";
218 static bool DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
219 {
220   Dali::BaseHandle handle( object );
221
222   bool connected( false );
223   Toolkit::Control control = Toolkit::Control::DownCast( handle );
224   if ( control )
225   {
226     Internal::Control& controlImpl( Internal::GetImplementation( control ) );
227     connected = true;
228
229     if ( 0 == strcmp( signalName.c_str(), SIGNAL_KEY_EVENT ) )
230     {
231       controlImpl.KeyEventSignal().Connect( tracker, functor );
232     }
233     else if( 0 == strcmp( signalName.c_str(), SIGNAL_KEY_INPUT_FOCUS_GAINED ) )
234     {
235       controlImpl.KeyInputFocusGainedSignal().Connect( tracker, functor );
236     }
237     else if( 0 == strcmp( signalName.c_str(), SIGNAL_KEY_INPUT_FOCUS_LOST ) )
238     {
239       controlImpl.KeyInputFocusLostSignal().Connect( tracker, functor );
240     }
241     else if( 0 == strcmp( signalName.c_str(), SIGNAL_TAPPED ) )
242     {
243       controlImpl.EnableGestureDetection( Gesture::Tap );
244       controlImpl.GetTapGestureDetector().DetectedSignal().Connect( tracker, functor );
245     }
246     else if( 0 == strcmp( signalName.c_str(), SIGNAL_PANNED ) )
247     {
248       controlImpl.EnableGestureDetection( Gesture::Pan );
249       controlImpl.GetPanGestureDetector().DetectedSignal().Connect( tracker, functor );
250     }
251     else if( 0 == strcmp( signalName.c_str(), SIGNAL_PINCHED ) )
252     {
253       controlImpl.EnableGestureDetection( Gesture::Pinch );
254       controlImpl.GetPinchGestureDetector().DetectedSignal().Connect( tracker, functor );
255     }
256     else if( 0 == strcmp( signalName.c_str(), SIGNAL_LONG_PRESSED ) )
257     {
258       controlImpl.EnableGestureDetection( Gesture::LongPress );
259       controlImpl.GetLongPressGestureDetector().DetectedSignal().Connect( tracker, functor );
260     }
261   }
262   return connected;
263 }
264
265 // Setup signals and actions using the type-registry.
266 DALI_TYPE_REGISTRATION_BEGIN( Control, CustomActor, Create );
267
268 // Note: Properties are registered separately below.
269
270 SignalConnectorType registerSignal1( typeRegistration, SIGNAL_KEY_EVENT, &DoConnectSignal );
271 SignalConnectorType registerSignal2( typeRegistration, SIGNAL_KEY_INPUT_FOCUS_GAINED, &DoConnectSignal );
272 SignalConnectorType registerSignal3( typeRegistration, SIGNAL_KEY_INPUT_FOCUS_LOST, &DoConnectSignal );
273 SignalConnectorType registerSignal4( typeRegistration, SIGNAL_TAPPED, &DoConnectSignal );
274 SignalConnectorType registerSignal5( typeRegistration, SIGNAL_PANNED, &DoConnectSignal );
275 SignalConnectorType registerSignal6( typeRegistration, SIGNAL_PINCHED, &DoConnectSignal );
276 SignalConnectorType registerSignal7( typeRegistration, SIGNAL_LONG_PRESSED, &DoConnectSignal );
277
278 TypeAction registerAction( typeRegistration, ACTION_ACCESSIBILITY_ACTIVATED, &DoAction );
279
280 DALI_TYPE_REGISTRATION_END()
281
282 } // unnamed namespace
283
284 namespace Internal
285 {
286
287 class Control::Impl : public ConnectionTracker
288 {
289 public:
290
291   // Construction & Destruction
292   Impl(Control& controlImpl)
293   : mControlImpl( controlImpl ),
294     mStyleName(""),
295     mBackgroundColor(Color::TRANSPARENT),
296     mStartingPinchScale( NULL ),
297     mKeyEventSignal(),
298     mPinchGestureDetector(),
299     mPanGestureDetector(),
300     mTapGestureDetector(),
301     mLongPressGestureDetector(),
302     mFlags( Control::ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ),
303     mIsKeyboardNavigationSupported( false ),
304     mIsKeyboardFocusGroup( false )
305   {
306   }
307
308   ~Impl()
309   {
310     // All gesture detectors will be destroyed so no need to disconnect.
311     delete mStartingPinchScale;
312   }
313
314   // Gesture Detection Methods
315
316   void PinchDetected(Actor actor, const PinchGesture& pinch)
317   {
318     mControlImpl.OnPinch(pinch);
319   }
320
321   void PanDetected(Actor actor, const PanGesture& pan)
322   {
323     mControlImpl.OnPan(pan);
324   }
325
326   void TapDetected(Actor actor, const TapGesture& tap)
327   {
328     mControlImpl.OnTap(tap);
329   }
330
331   void LongPressDetected(Actor actor, const LongPressGesture& longPress)
332   {
333     mControlImpl.OnLongPress(longPress);
334   }
335
336   // Properties
337
338   /**
339    * Called when a property of an object of this type is set.
340    * @param[in] object The object whose property is set.
341    * @param[in] index The property index.
342    * @param[in] value The new property value.
343    */
344   static void SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
345   {
346     Toolkit::Control control = Toolkit::Control::DownCast( BaseHandle( object ) );
347
348     if ( control )
349     {
350       Control& controlImpl( GetImplementation( control ) );
351
352       switch ( index )
353       {
354         case Toolkit::Control::Property::STYLE_NAME:
355         {
356           controlImpl.SetStyleName( value.Get< std::string >() );
357           break;
358         }
359
360         case Toolkit::Control::Property::BACKGROUND_COLOR:
361         {
362           DALI_LOG_WARNING( "BACKGROUND_COLOR property is deprecated. Use BACKGROUND property instead\n" );
363           controlImpl.SetBackgroundColor( value.Get< Vector4 >() );
364           break;
365         }
366
367         case Toolkit::Control::Property::BACKGROUND_IMAGE:
368         {
369           DALI_LOG_WARNING( "BACKGROUND_IMAGE property is deprecated. Use BACKGROUND property instead\n" );
370           Image image = Scripting::NewImage( value );
371           if ( image )
372           {
373             controlImpl.SetBackgroundImage( image );
374           }
375           else
376           {
377             // An empty image means the background is no longer required
378             controlImpl.ClearBackground();
379           }
380           break;
381         }
382
383         case Toolkit::Control::Property::KEY_INPUT_FOCUS:
384         {
385           if ( value.Get< bool >() )
386           {
387             controlImpl.SetKeyInputFocus();
388           }
389           else
390           {
391             controlImpl.ClearKeyInputFocus();
392           }
393           break;
394         }
395
396         case Toolkit::Control::Property::BACKGROUND:
397         {
398           const Property::Map* map = value.GetMap();
399           if( map && !map->Empty() )
400           {
401             controlImpl.SetBackground( *map );
402           }
403           else
404           {
405             // The background is an empty property map, so we should clear the background
406             controlImpl.ClearBackground();
407           }
408           break;
409         }
410       }
411     }
412   }
413
414   /**
415    * Called to retrieve a property of an object of this type.
416    * @param[in] object The object whose property is to be retrieved.
417    * @param[in] index The property index.
418    * @return The current value of the property.
419    */
420   static Property::Value GetProperty( BaseObject* object, Property::Index index )
421   {
422     Property::Value value;
423
424     Toolkit::Control control = Toolkit::Control::DownCast( BaseHandle( object ) );
425
426     if ( control )
427     {
428       Control& controlImpl( GetImplementation( control ) );
429
430       switch ( index )
431       {
432         case Toolkit::Control::Property::STYLE_NAME:
433         {
434           value = controlImpl.GetStyleName();
435           break;
436         }
437
438         case Toolkit::Control::Property::BACKGROUND_COLOR:
439         {
440           DALI_LOG_WARNING( "BACKGROUND_COLOR property is deprecated. Use BACKGROUND property instead\n" );
441           value = controlImpl.GetBackgroundColor();
442           break;
443         }
444
445         case Toolkit::Control::Property::BACKGROUND_IMAGE:
446         {
447           DALI_LOG_WARNING( "BACKGROUND_IMAGE property is deprecated. Use BACKGROUND property instead\n" );
448           Property::Map map;
449           Toolkit::Visual::Base visual = controlImpl.GetVisual( Toolkit::Control::Property::BACKGROUND );
450           if( visual )
451           {
452             visual.CreatePropertyMap( map );
453           }
454           value = map;
455           break;
456         }
457
458         case Toolkit::Control::Property::KEY_INPUT_FOCUS:
459         {
460           value = controlImpl.HasKeyInputFocus();
461           break;
462         }
463
464         case Toolkit::Control::Property::BACKGROUND:
465         {
466           Property::Map map;
467           Toolkit::Visual::Base visual = controlImpl.GetVisual( Toolkit::Control::Property::BACKGROUND );
468           if( visual )
469           {
470             visual.CreatePropertyMap( map );
471           }
472
473           value = map;
474           break;
475         }
476
477       }
478     }
479
480     return value;
481   }
482
483   // Data
484
485   Control& mControlImpl;
486   RegisteredVisualContainer mVisuals; // Stores visuals needed by the control, non trivial type so std::vector used.
487   std::string mStyleName;
488   Vector4 mBackgroundColor;                       ///< The color of the background visual
489   Vector3* mStartingPinchScale;      ///< The scale when a pinch gesture starts, TODO: consider removing this
490   Toolkit::Control::KeyEventSignalType mKeyEventSignal;
491   Toolkit::Control::KeyInputFocusSignalType mKeyInputFocusGainedSignal;
492   Toolkit::Control::KeyInputFocusSignalType mKeyInputFocusLostSignal;
493
494   // Gesture Detection
495   PinchGestureDetector mPinchGestureDetector;
496   PanGestureDetector mPanGestureDetector;
497   TapGestureDetector mTapGestureDetector;
498   LongPressGestureDetector mLongPressGestureDetector;
499
500   ControlBehaviour mFlags : CONTROL_BEHAVIOUR_FLAG_COUNT;    ///< Flags passed in from constructor.
501   bool mIsKeyboardNavigationSupported :1;  ///< Stores whether keyboard navigation is supported by the control.
502   bool mIsKeyboardFocusGroup :1;           ///< Stores whether the control is a focus group.
503
504   // Properties - these need to be members of Internal::Control::Impl as they need to function within this class.
505   static const PropertyRegistration PROPERTY_1;
506   static const PropertyRegistration PROPERTY_2;
507   static const PropertyRegistration PROPERTY_3;
508   static const PropertyRegistration PROPERTY_4;
509   static const PropertyRegistration PROPERTY_5;
510 };
511
512 // Properties registered without macro to use specific member variables.
513 const PropertyRegistration Control::Impl::PROPERTY_1( typeRegistration, "styleName",       Toolkit::Control::Property::STYLE_NAME,       Property::STRING,  &Control::Impl::SetProperty, &Control::Impl::GetProperty );
514 const PropertyRegistration Control::Impl::PROPERTY_2( typeRegistration, "backgroundColor", Toolkit::Control::Property::BACKGROUND_COLOR, Property::VECTOR4, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
515 const PropertyRegistration Control::Impl::PROPERTY_3( typeRegistration, "backgroundImage", Toolkit::Control::Property::BACKGROUND_IMAGE, Property::MAP,     &Control::Impl::SetProperty, &Control::Impl::GetProperty );
516 const PropertyRegistration Control::Impl::PROPERTY_4( typeRegistration, "keyInputFocus",   Toolkit::Control::Property::KEY_INPUT_FOCUS,  Property::BOOLEAN, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
517 const PropertyRegistration Control::Impl::PROPERTY_5( typeRegistration, "background",      Toolkit::Control::Property::BACKGROUND,       Property::MAP,     &Control::Impl::SetProperty, &Control::Impl::GetProperty );
518
519 Toolkit::Control Control::New()
520 {
521   // Create the implementation, temporarily owned on stack
522   IntrusivePtr<Control> controlImpl = new Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) );
523
524   // Pass ownership to handle
525   Toolkit::Control handle( *controlImpl );
526
527   // Second-phase init of the implementation
528   // This can only be done after the CustomActor connection has been made...
529   controlImpl->Initialize();
530
531   return handle;
532 }
533
534 Control::~Control()
535 {
536   delete mImpl;
537 }
538
539 void Control::SetStyleName( const std::string& styleName )
540 {
541   if( styleName != mImpl->mStyleName )
542   {
543     mImpl->mStyleName = styleName;
544
545     // Apply new style, if stylemanager is available
546     Toolkit::StyleManager styleManager = Toolkit::StyleManager::Get();
547     if( styleManager )
548     {
549       GetImpl( styleManager ).ApplyThemeStyle( Toolkit::Control( GetOwner() ) );
550     }
551   }
552 }
553
554 const std::string& Control::GetStyleName() const
555 {
556   return mImpl->mStyleName;
557 }
558
559 void Control::SetBackgroundColor( const Vector4& color )
560 {
561   mImpl->mBackgroundColor = color;
562   Property::Map map;
563   map[ Toolkit::VisualProperty::TYPE ] = Toolkit::Visual::COLOR;
564   map[ Toolkit::ColorVisual::Property::MIX_COLOR ] = color;
565
566   SetBackground( map );
567 }
568
569 Vector4 Control::GetBackgroundColor() const
570 {
571   return mImpl->mBackgroundColor;
572 }
573
574 void Control::SetBackground( const Property::Map& map )
575 {
576   Toolkit::Visual::Base visual = Toolkit::VisualFactory::Get().CreateVisual( map );
577   if( visual )
578   {
579     RegisterVisual( Toolkit::Control::Property::BACKGROUND, visual );
580     visual.SetDepthIndex( DepthIndex::BACKGROUND );
581   }
582 }
583
584 void Control::SetBackgroundImage( Image image )
585 {
586   DALI_LOG_WARNING( "SetBackgroundImage is for the depreciated Property::BACKGROUND_IMAGE use SetBackground( const Property::Map& map )\n" );
587   Toolkit::Visual::Base visual = Toolkit::VisualFactory::Get().CreateVisual( image );
588   if( visual )
589   {
590     RegisterVisual( Toolkit::Control::Property::BACKGROUND, visual );
591     visual.SetDepthIndex( DepthIndex::BACKGROUND );
592   }
593 }
594
595 void Control::ClearBackground()
596 {
597    UnregisterVisual( Toolkit::Control::Property::BACKGROUND );
598    mImpl->mBackgroundColor = Color::TRANSPARENT;
599 }
600
601 void Control::EnableGestureDetection(Gesture::Type type)
602 {
603   if ( (type & Gesture::Pinch) && !mImpl->mPinchGestureDetector )
604   {
605     mImpl->mPinchGestureDetector = PinchGestureDetector::New();
606     mImpl->mPinchGestureDetector.DetectedSignal().Connect(mImpl, &Impl::PinchDetected);
607     mImpl->mPinchGestureDetector.Attach(Self());
608   }
609
610   if ( (type & Gesture::Pan) && !mImpl->mPanGestureDetector )
611   {
612     mImpl->mPanGestureDetector = PanGestureDetector::New();
613     mImpl->mPanGestureDetector.DetectedSignal().Connect(mImpl, &Impl::PanDetected);
614     mImpl->mPanGestureDetector.Attach(Self());
615   }
616
617   if ( (type & Gesture::Tap) && !mImpl->mTapGestureDetector )
618   {
619     mImpl->mTapGestureDetector = TapGestureDetector::New();
620     mImpl->mTapGestureDetector.DetectedSignal().Connect(mImpl, &Impl::TapDetected);
621     mImpl->mTapGestureDetector.Attach(Self());
622   }
623
624   if ( (type & Gesture::LongPress) && !mImpl->mLongPressGestureDetector )
625   {
626     mImpl->mLongPressGestureDetector = LongPressGestureDetector::New();
627     mImpl->mLongPressGestureDetector.DetectedSignal().Connect(mImpl, &Impl::LongPressDetected);
628     mImpl->mLongPressGestureDetector.Attach(Self());
629   }
630 }
631
632 void Control::DisableGestureDetection(Gesture::Type type)
633 {
634   if ( (type & Gesture::Pinch) && mImpl->mPinchGestureDetector )
635   {
636     mImpl->mPinchGestureDetector.Detach(Self());
637     mImpl->mPinchGestureDetector.Reset();
638   }
639
640   if ( (type & Gesture::Pan) && mImpl->mPanGestureDetector )
641   {
642     mImpl->mPanGestureDetector.Detach(Self());
643     mImpl->mPanGestureDetector.Reset();
644   }
645
646   if ( (type & Gesture::Tap) && mImpl->mTapGestureDetector )
647   {
648     mImpl->mTapGestureDetector.Detach(Self());
649     mImpl->mTapGestureDetector.Reset();
650   }
651
652   if ( (type & Gesture::LongPress) && mImpl->mLongPressGestureDetector)
653   {
654     mImpl->mLongPressGestureDetector.Detach(Self());
655     mImpl->mLongPressGestureDetector.Reset();
656   }
657 }
658
659 PinchGestureDetector Control::GetPinchGestureDetector() const
660 {
661   return mImpl->mPinchGestureDetector;
662 }
663
664 PanGestureDetector Control::GetPanGestureDetector() const
665 {
666   return mImpl->mPanGestureDetector;
667 }
668
669 TapGestureDetector Control::GetTapGestureDetector() const
670 {
671   return mImpl->mTapGestureDetector;
672 }
673
674 LongPressGestureDetector Control::GetLongPressGestureDetector() const
675 {
676   return mImpl->mLongPressGestureDetector;
677 }
678
679 void Control::SetKeyboardNavigationSupport(bool isSupported)
680 {
681   mImpl->mIsKeyboardNavigationSupported = isSupported;
682 }
683
684 bool Control::IsKeyboardNavigationSupported()
685 {
686   return mImpl->mIsKeyboardNavigationSupported;
687 }
688
689 void Control::SetKeyInputFocus()
690 {
691   if( Self().OnStage() )
692   {
693     Toolkit::KeyInputFocusManager::Get().SetFocus(Toolkit::Control::DownCast(Self()));
694   }
695 }
696
697 bool Control::HasKeyInputFocus()
698 {
699   bool result = false;
700   if( Self().OnStage() )
701   {
702     result = Toolkit::KeyInputFocusManager::Get().IsKeyboardListener(Toolkit::Control::DownCast(Self()));
703   }
704   return result;
705 }
706
707 void Control::ClearKeyInputFocus()
708 {
709   if( Self().OnStage() )
710   {
711     Toolkit::KeyInputFocusManager::Get().RemoveFocus(Toolkit::Control::DownCast(Self()));
712   }
713 }
714
715 void Control::SetAsKeyboardFocusGroup(bool isFocusGroup)
716 {
717   mImpl->mIsKeyboardFocusGroup = isFocusGroup;
718
719   // The following line will be removed when the deprecated API in KeyboardFocusManager is deleted
720   Toolkit::KeyboardFocusManager::Get().SetAsFocusGroup(Self(), isFocusGroup);
721 }
722
723 bool Control::IsKeyboardFocusGroup()
724 {
725   return Toolkit::KeyboardFocusManager::Get().IsFocusGroup(Self());
726 }
727
728 void Control::AccessibilityActivate()
729 {
730   // Inform deriving classes
731   OnAccessibilityActivated();
732 }
733
734 void Control::KeyboardEnter()
735 {
736   // Inform deriving classes
737   OnKeyboardEnter();
738 }
739
740 void Control::RegisterVisual( Property::Index index, Toolkit::Visual::Base& visual )
741 {
742   RegisterVisual( index, visual, true );
743 }
744
745 void Control::RegisterVisual( Property::Index index, Toolkit::Visual::Base& visual, bool enabled )
746 {
747   bool visualReplaced ( false );
748   Actor self = Self();
749
750   if ( !mImpl->mVisuals.Empty() )
751   {
752       RegisteredVisualContainer::Iterator iter;
753       // Check if visual (index) is already registered.  Replace if so.
754       if ( FindVisual( index, mImpl->mVisuals, iter ) )
755       {
756         if( (*iter)->visual && self.OnStage() )
757         {
758           Toolkit::GetImplementation((*iter)->visual).SetOffStage( self );
759         }
760         (*iter)->visual = visual;
761         visualReplaced = true;
762       }
763   }
764
765   if ( !visualReplaced ) // New registration entry
766   {
767     mImpl->mVisuals.PushBack( new RegisteredVisual( index, visual, enabled ) );
768   }
769
770   if( visual && self.OnStage() && enabled )
771   {
772     Toolkit::GetImplementation(visual).SetOnStage( self );
773   }
774 }
775
776 void Control::UnregisterVisual( Property::Index index )
777 {
778    RegisteredVisualContainer::Iterator iter;
779    if ( FindVisual( index, mImpl->mVisuals, iter ) )
780    {
781      Actor self( Self() );
782      Toolkit::GetImplementation((*iter)->visual).SetOffStage( self );
783      (*iter)->visual.Reset();
784      mImpl->mVisuals.Erase( iter );
785    }
786 }
787
788 Toolkit::Visual::Base Control::GetVisual( Property::Index index ) const
789 {
790   RegisteredVisualContainer::Iterator iter;
791   if ( FindVisual( index, mImpl->mVisuals, iter ) )
792   {
793     return (*iter)->visual;
794   }
795
796   return Toolkit::Visual::Base();
797 }
798
799 void Control::EnableVisual( Property::Index index, bool enable )
800 {
801   RegisteredVisualContainer::Iterator iter;
802   if ( FindVisual( index, mImpl->mVisuals, iter ) )
803   {
804     if (  (*iter)->enabled == enable )
805     {
806       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::EnableVisual Visual Already enabled set (%s) \n", enable?"enabled":"disabled");
807       return;
808     }
809
810     (*iter)->enabled = enable;
811     Actor parentActor = Self();
812     if ( Self().OnStage() ) // If control not on Stage then Visual will be added when StageConnection is called.
813     {
814       if ( enable )
815       {
816         DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::EnableVisual Setting Visual(%d) on stage \n", index );
817         Toolkit::GetImplementation((*iter)->visual).SetOnStage( parentActor );
818       }
819       else
820       {
821         DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::EnableVisual Setting Visual(%d) off stage \n", index );
822         Toolkit::GetImplementation((*iter)->visual).SetOffStage( parentActor );  // No need to call if control not staged.
823       }
824     }
825   }
826 }
827
828 bool Control::IsVisualEnabled( Property::Index index ) const
829 {
830   RegisteredVisualContainer::Iterator iter;
831   if ( FindVisual( index, mImpl->mVisuals, iter ) )
832   {
833     return (*iter)->enabled;
834   }
835   return false;
836 }
837
838 Dali::Animation Control::CreateTransition( const Toolkit::TransitionData& handle )
839 {
840   Dali::Animation transition;
841   const Internal::TransitionData& transitionData = Toolkit::GetImplementation( handle );
842
843   if( transitionData.Count() > 0 )
844   {
845     // Setup a Transition from TransitionData.
846     TransitionData::Iterator end = transitionData.End();
847     for( TransitionData::Iterator iter = transitionData.Begin() ;
848          iter != end; ++iter )
849     {
850       TransitionData::Animator* animator = (*iter);
851       HandleIndex handleIndex;
852
853       // Attempt to find the object name as a child actor
854       Actor child = Self().FindChildByName( animator->objectName );
855       if( child )
856       {
857         Property::Index propertyIndex = child.GetPropertyIndex( animator->propertyKey );
858         handleIndex = HandleIndex( child, propertyIndex );
859       }
860       else
861       {
862         handleIndex = GetVisualProperty( *this, mImpl->mVisuals,
863                                             animator->objectName,
864                                             animator->propertyKey );
865       }
866
867       if( handleIndex.handle && handleIndex.index != Property::INVALID_INDEX )
868       {
869         if( animator->animate == false )
870         {
871           if( animator->targetValue.GetType() != Property::NONE )
872           {
873             handleIndex.handle.SetProperty( handleIndex.index, animator->targetValue );
874           }
875         }
876         else
877         {
878           if( animator->initialValue.GetType() != Property::NONE )
879           {
880             handleIndex.handle.SetProperty( handleIndex.index, animator->initialValue );
881           }
882
883           if( ! transition )
884           {
885             // Create an animation with a default .1 second duration - the animators
886             // will automatically force it to the 'right' duration.
887             transition = Dali::Animation::New( 0.1f );
888           }
889
890           transition.AnimateTo( Property( handleIndex.handle, handleIndex.index ),
891                                 animator->targetValue,
892                                 animator->alphaFunction,
893                                 TimePeriod( animator->timePeriodDelay,
894                                             animator->timePeriodDuration ) );
895         }
896       }
897     }
898   }
899
900   return transition;
901 }
902
903 bool Control::OnAccessibilityActivated()
904 {
905   return false; // Accessibility activation is not handled by default
906 }
907
908 bool Control::OnKeyboardEnter()
909 {
910   return false; // Keyboard enter is not handled by default
911 }
912
913 bool Control::OnAccessibilityPan(PanGesture gesture)
914 {
915   return false; // Accessibility pan gesture is not handled by default
916 }
917
918 bool Control::OnAccessibilityTouch(const TouchEvent& touchEvent)
919 {
920   return false; // Accessibility touch event is not handled by default
921 }
922
923 bool Control::OnAccessibilityValueChange(bool isIncrease)
924 {
925   return false; // Accessibility value change action is not handled by default
926 }
927
928 bool Control::OnAccessibilityZoom()
929 {
930   return false; // Accessibility zoom action is not handled by default
931 }
932
933 Actor Control::GetNextKeyboardFocusableActor(Actor currentFocusedActor, Toolkit::Control::KeyboardFocus::Direction direction, bool loopEnabled)
934 {
935   return Actor();
936 }
937
938 void Control::OnKeyboardFocusChangeCommitted(Actor commitedFocusableActor)
939 {
940 }
941
942 Toolkit::Control::KeyEventSignalType& Control::KeyEventSignal()
943 {
944   return mImpl->mKeyEventSignal;
945 }
946
947 Toolkit::Control::KeyInputFocusSignalType& Control::KeyInputFocusGainedSignal()
948 {
949   return mImpl->mKeyInputFocusGainedSignal;
950 }
951
952 Toolkit::Control::KeyInputFocusSignalType& Control::KeyInputFocusLostSignal()
953 {
954   return mImpl->mKeyInputFocusLostSignal;
955 }
956
957 bool Control::EmitKeyEventSignal( const KeyEvent& event )
958 {
959   // Guard against destruction during signal emission
960   Dali::Toolkit::Control handle( GetOwner() );
961
962   bool consumed = false;
963
964   // signals are allocated dynamically when someone connects
965   if ( !mImpl->mKeyEventSignal.Empty() )
966   {
967     consumed = mImpl->mKeyEventSignal.Emit( handle, event );
968   }
969
970   if (!consumed)
971   {
972     // Notification for derived classes
973     consumed = OnKeyEvent(event);
974   }
975
976   return consumed;
977 }
978
979 Control::Control( ControlBehaviour behaviourFlags )
980 : CustomActorImpl( static_cast< ActorFlags >( behaviourFlags ) ),
981   mImpl(new Impl(*this))
982 {
983   mImpl->mFlags = behaviourFlags;
984 }
985
986 void Control::Initialize()
987 {
988   // Call deriving classes so initialised before styling is applied to them.
989   OnInitialize();
990
991   if( (mImpl->mFlags & REQUIRES_STYLE_CHANGE_SIGNALS) ||
992       !(mImpl->mFlags & DISABLE_STYLE_CHANGE_SIGNALS) )
993   {
994     Toolkit::StyleManager styleManager = StyleManager::Get();
995
996     // if stylemanager is available
997     if( styleManager )
998     {
999       StyleManager& styleManagerImpl = GetImpl( styleManager );
1000
1001       // Register for style changes
1002       styleManagerImpl.ControlStyleChangeSignal().Connect( this, &Control::OnStyleChange );
1003
1004       // Apply the current style
1005       styleManagerImpl.ApplyThemeStyleAtInit( Toolkit::Control( GetOwner() ) );
1006     }
1007   }
1008
1009   if( mImpl->mFlags & REQUIRES_KEYBOARD_NAVIGATION_SUPPORT )
1010   {
1011     SetKeyboardNavigationSupport( true );
1012   }
1013 }
1014
1015 void Control::OnInitialize()
1016 {
1017 }
1018
1019 void Control::OnControlChildAdd( Actor& child )
1020 {
1021 }
1022
1023 void Control::OnControlChildRemove( Actor& child )
1024 {
1025 }
1026
1027 void Control::OnStyleChange( Toolkit::StyleManager styleManager, StyleChange::Type change )
1028 {
1029   // By default the control is only interested in theme (not font) changes
1030   if( styleManager && change == StyleChange::THEME_CHANGE )
1031   {
1032     GetImpl( styleManager ).ApplyThemeStyle( Toolkit::Control( GetOwner() ) );
1033   }
1034   RelayoutRequest();
1035 }
1036
1037 void Control::OnPinch(const PinchGesture& pinch)
1038 {
1039   if( !( mImpl->mStartingPinchScale ) )
1040   {
1041     // lazy allocate
1042     mImpl->mStartingPinchScale = new Vector3;
1043   }
1044
1045   if( pinch.state == Gesture::Started )
1046   {
1047     *( mImpl->mStartingPinchScale ) = Self().GetCurrentScale();
1048   }
1049
1050   Self().SetScale( *( mImpl->mStartingPinchScale ) * pinch.scale );
1051 }
1052
1053 void Control::OnPan( const PanGesture& pan )
1054 {
1055 }
1056
1057 void Control::OnTap(const TapGesture& tap)
1058 {
1059 }
1060
1061 void Control::OnLongPress( const LongPressGesture& longPress )
1062 {
1063 }
1064
1065 void Control::EmitKeyInputFocusSignal( bool focusGained )
1066 {
1067   Dali::Toolkit::Control handle( GetOwner() );
1068
1069   if ( focusGained )
1070   {
1071     // signals are allocated dynamically when someone connects
1072     if ( !mImpl->mKeyInputFocusGainedSignal.Empty() )
1073     {
1074       mImpl->mKeyInputFocusGainedSignal.Emit( handle );
1075     }
1076   }
1077   else
1078   {
1079     // signals are allocated dynamically when someone connects
1080     if ( !mImpl->mKeyInputFocusLostSignal.Empty() )
1081     {
1082       mImpl->mKeyInputFocusLostSignal.Emit( handle );
1083     }
1084   }
1085 }
1086
1087 void Control::OnStageConnection( int depth )
1088 {
1089   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::OnStageConnection number of registered visuals(%d)\n",  mImpl->mVisuals.Size() );
1090
1091   for(RegisteredVisualContainer::Iterator iter = mImpl->mVisuals.Begin(); iter!= mImpl->mVisuals.End(); iter++)
1092   {
1093     // Check whether the visual is empty and enabled
1094     if( (*iter)->visual && (*iter)->enabled )
1095     {
1096       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::OnStageConnection Setting visual(%d) on stage\n", (*iter)->index );
1097       Actor self( Self() );
1098       Toolkit::GetImplementation((*iter)->visual).SetOnStage( self );
1099     }
1100   }
1101 }
1102
1103 void Control::OnStageDisconnection()
1104 {
1105   for(RegisteredVisualContainer::Iterator iter = mImpl->mVisuals.Begin(); iter!= mImpl->mVisuals.End(); iter++)
1106   {
1107     // Check whether the visual is empty
1108     if( (*iter)->visual )
1109     {
1110       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::OnStageDisconnection Setting visual(%d) off stage\n", (*iter)->index );
1111       Actor self( Self() );
1112       Toolkit::GetImplementation((*iter)->visual).SetOffStage( self );
1113     }
1114   }
1115 }
1116
1117 void Control::OnKeyInputFocusGained()
1118 {
1119   EmitKeyInputFocusSignal( true );
1120 }
1121
1122 void Control::OnKeyInputFocusLost()
1123 {
1124   EmitKeyInputFocusSignal( false );
1125 }
1126
1127 void Control::OnChildAdd(Actor& child)
1128 {
1129   // Notify derived classes.
1130   OnControlChildAdd( child );
1131 }
1132
1133 void Control::OnChildRemove(Actor& child)
1134 {
1135   // Notify derived classes.
1136   OnControlChildRemove( child );
1137 }
1138
1139 void Control::OnSizeSet(const Vector3& targetSize)
1140 {
1141   Toolkit::Visual::Base visual = GetVisual( Toolkit::Control::Property::BACKGROUND );
1142   if( visual )
1143   {
1144     Vector2 size( targetSize );
1145     visual.SetSize( size );
1146   }
1147 }
1148
1149 void Control::OnSizeAnimation(Animation& animation, const Vector3& targetSize)
1150 {
1151   // @todo size negotiate background to new size, animate as well?
1152 }
1153
1154 bool Control::OnTouchEvent(const TouchEvent& event)
1155 {
1156   return false; // Do not consume
1157 }
1158
1159 bool Control::OnHoverEvent(const HoverEvent& event)
1160 {
1161   return false; // Do not consume
1162 }
1163
1164 bool Control::OnKeyEvent(const KeyEvent& event)
1165 {
1166   return false; // Do not consume
1167 }
1168
1169 bool Control::OnWheelEvent(const WheelEvent& event)
1170 {
1171   return false; // Do not consume
1172 }
1173
1174 void Control::OnRelayout( const Vector2& size, RelayoutContainer& container )
1175 {
1176   for( unsigned int i = 0, numChildren = Self().GetChildCount(); i < numChildren; ++i )
1177   {
1178     container.Add( Self().GetChildAt( i ), size );
1179   }
1180 }
1181
1182 void Control::OnSetResizePolicy( ResizePolicy::Type policy, Dimension::Type dimension )
1183 {
1184 }
1185
1186 Vector3 Control::GetNaturalSize()
1187 {
1188   Toolkit::Visual::Base visual = GetVisual( Toolkit::Control::Property::BACKGROUND );
1189   if( visual )
1190   {
1191     Vector2 naturalSize;
1192     visual.GetNaturalSize( naturalSize );
1193     return Vector3( naturalSize );
1194   }
1195   return Vector3::ZERO;
1196 }
1197
1198 float Control::CalculateChildSize( const Dali::Actor& child, Dimension::Type dimension )
1199 {
1200   return CalculateChildSizeBase( child, dimension );
1201 }
1202
1203 float Control::GetHeightForWidth( float width )
1204 {
1205   return GetHeightForWidthBase( width );
1206 }
1207
1208 float Control::GetWidthForHeight( float height )
1209 {
1210   return GetWidthForHeightBase( height );
1211 }
1212
1213 bool Control::RelayoutDependentOnChildren( Dimension::Type dimension )
1214 {
1215   return RelayoutDependentOnChildrenBase( dimension );
1216 }
1217
1218 void Control::OnCalculateRelayoutSize( Dimension::Type dimension )
1219 {
1220 }
1221
1222 void Control::OnLayoutNegotiated( float size, Dimension::Type dimension )
1223 {
1224 }
1225
1226 void Control::SignalConnected( SlotObserver* slotObserver, CallbackBase* callback )
1227 {
1228   mImpl->SignalConnected( slotObserver, callback );
1229 }
1230
1231 void Control::SignalDisconnected( SlotObserver* slotObserver, CallbackBase* callback )
1232 {
1233   mImpl->SignalDisconnected( slotObserver, callback );
1234 }
1235
1236 Control& GetImplementation( Dali::Toolkit::Control& handle )
1237 {
1238   CustomActorImpl& customInterface = handle.GetImplementation();
1239   // downcast to control
1240   Control& impl = dynamic_cast< Internal::Control& >( customInterface );
1241   return impl;
1242 }
1243
1244 const Control& GetImplementation( const Dali::Toolkit::Control& handle )
1245 {
1246   const CustomActorImpl& customInterface = handle.GetImplementation();
1247   // downcast to control
1248   const Control& impl = dynamic_cast< const Internal::Control& >( customInterface );
1249   return impl;
1250 }
1251
1252 } // namespace Internal
1253
1254 } // namespace Toolkit
1255
1256 } // namespace Dali