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