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