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