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