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