Merge "Fix doc and comment for Native API Reference page" into devel/master
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / controls / control / control-data-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 "control-data-impl.h"
20
21 // EXTERNAL INCLUDES
22 #include <dali/public-api/common/dali-common.h>
23 #include <dali/integration-api/debug.h>
24 #include <dali/devel-api/object/handle-devel.h>
25 #include <dali/devel-api/scripting/enum-helper.h>
26 #include <dali/devel-api/scripting/scripting.h>
27 #include <dali/integration-api/debug.h>
28 #include <dali/public-api/object/type-registry-helper.h>
29 #include <cstring>
30 #include <limits>
31
32 // INTERNAL INCLUDES
33 #include <dali-toolkit/internal/visuals/visual-base-impl.h>
34 #include <dali-toolkit/devel-api/controls/control-depth-index-ranges.h>
35 #include <dali-toolkit/internal/styling/style-manager-impl.h>
36 #include <dali-toolkit/public-api/visuals/image-visual-properties.h>
37 #include <dali-toolkit/public-api/visuals/visual-properties.h>
38 #include <dali-toolkit/internal/visuals/visual-string-constants.h>
39 #include <dali-toolkit/devel-api/controls/control-devel.h>
40 #include <dali-toolkit/devel-api/controls/control-wrapper-impl.h>
41
42 namespace Dali
43 {
44
45 namespace Toolkit
46 {
47
48 namespace Internal
49 {
50
51 extern const Dali::Scripting::StringEnum ControlStateTable[];
52 extern const unsigned int ControlStateTableCount;
53
54
55 // Not static or anonymous - shared with other translation units
56 const Scripting::StringEnum ControlStateTable[] = {
57   { "NORMAL",   Toolkit::DevelControl::NORMAL   },
58   { "FOCUSED",  Toolkit::DevelControl::FOCUSED  },
59   { "DISABLED", Toolkit::DevelControl::DISABLED },
60 };
61 const unsigned int ControlStateTableCount = sizeof( ControlStateTable ) / sizeof( ControlStateTable[0] );
62
63
64
65 namespace
66 {
67
68 #if defined(DEBUG_ENABLED)
69 Debug::Filter* gLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_CONTROL_VISUALS");
70 #endif
71
72
73 template<typename T>
74 void Remove( Dictionary<T>& keyValues, const std::string& name )
75 {
76   keyValues.Remove(name);
77 }
78
79 void Remove( DictionaryKeys& keys, const std::string& name )
80 {
81   DictionaryKeys::iterator iter = std::find( keys.begin(), keys.end(), name );
82   if( iter != keys.end())
83   {
84     keys.erase(iter);
85   }
86 }
87
88 Toolkit::Visual::Type GetVisualTypeFromMap( const Property::Map& map )
89 {
90   Property::Value* typeValue = map.Find( Toolkit::Visual::Property::TYPE, VISUAL_TYPE  );
91   Toolkit::Visual::Type type = Toolkit::Visual::IMAGE;
92   if( typeValue )
93   {
94     Scripting::GetEnumerationProperty( *typeValue, VISUAL_TYPE_TABLE, VISUAL_TYPE_TABLE_COUNT, type );
95   }
96   return type;
97 }
98
99 /**
100  *  Finds visual in given array, returning true if found along with the iterator for that visual as a out parameter
101  */
102 bool FindVisual( Property::Index targetIndex, const RegisteredVisualContainer& visuals, RegisteredVisualContainer::Iterator& iter )
103 {
104   for ( iter = visuals.Begin(); iter != visuals.End(); iter++ )
105   {
106     if ( (*iter)->index ==  targetIndex )
107     {
108       return true;
109     }
110   }
111   return false;
112 }
113
114 void FindChangableVisuals( Dictionary<Property::Map>& stateVisualsToAdd,
115                            Dictionary<Property::Map>& stateVisualsToChange,
116                            DictionaryKeys& stateVisualsToRemove)
117 {
118   DictionaryKeys copyOfStateVisualsToRemove = stateVisualsToRemove;
119
120   for( DictionaryKeys::iterator iter = copyOfStateVisualsToRemove.begin();
121        iter != copyOfStateVisualsToRemove.end(); ++iter )
122   {
123     const std::string& visualName = (*iter);
124     Property::Map* toMap = stateVisualsToAdd.Find( visualName );
125     if( toMap )
126     {
127       stateVisualsToChange.Add( visualName, *toMap );
128       stateVisualsToAdd.Remove( visualName );
129       Remove( stateVisualsToRemove, visualName );
130     }
131   }
132 }
133
134 Toolkit::Visual::Base GetVisualByName(
135   const RegisteredVisualContainer& visuals,
136   const std::string& visualName )
137 {
138   Toolkit::Visual::Base visualHandle;
139
140   RegisteredVisualContainer::Iterator iter;
141   for ( iter = visuals.Begin(); iter != visuals.End(); iter++ )
142   {
143     Toolkit::Visual::Base visual = (*iter)->visual;
144     if( visual && visual.GetName() == visualName )
145     {
146       visualHandle = visual;
147       break;
148     }
149   }
150   return visualHandle;
151 }
152
153 /**
154  * Move visual from source to destination container
155  */
156 void MoveVisual( RegisteredVisualContainer::Iterator sourceIter, RegisteredVisualContainer& source, RegisteredVisualContainer& destination )
157 {
158    Toolkit::Visual::Base visual = (*sourceIter)->visual;
159    if( visual )
160    {
161      RegisteredVisual* rv = source.Release( sourceIter );
162      destination.PushBack( rv );
163    }
164 }
165
166 /**
167  * Performs actions as requested using the action name.
168  * @param[in] object The object on which to perform the action.
169  * @param[in] actionName The action to perform.
170  * @param[in] attributes The attributes with which to perfrom this action.
171  * @return true if action has been accepted by this control
172  */
173 const char* ACTION_ACCESSIBILITY_ACTIVATED = "accessibilityActivated";
174 static bool DoAction( BaseObject* object, const std::string& actionName, const Property::Map& attributes )
175 {
176   bool ret = false;
177
178   if( object && ( 0 == strcmp( actionName.c_str(), ACTION_ACCESSIBILITY_ACTIVATED ) ) )
179   {
180     Toolkit::Control control = Toolkit::Control::DownCast( BaseHandle( object ) );
181     if( control )
182     {
183       // if cast succeeds there is an implementation so no need to check
184       ret = Internal::GetImplementation( control ).OnAccessibilityActivated();
185     }
186   }
187
188   return ret;
189 }
190
191 /**
192  * Connects a callback function with the object's signals.
193  * @param[in] object The object providing the signal.
194  * @param[in] tracker Used to disconnect the signal.
195  * @param[in] signalName The signal to connect to.
196  * @param[in] functor A newly allocated FunctorDelegate.
197  * @return True if the signal was connected.
198  * @post If a signal was connected, ownership of functor was passed to CallbackBase. Otherwise the caller is responsible for deleting the unused functor.
199  */
200 const char* SIGNAL_KEY_EVENT = "keyEvent";
201 const char* SIGNAL_KEY_INPUT_FOCUS_GAINED = "keyInputFocusGained";
202 const char* SIGNAL_KEY_INPUT_FOCUS_LOST = "keyInputFocusLost";
203 const char* SIGNAL_TAPPED = "tapped";
204 const char* SIGNAL_PANNED = "panned";
205 const char* SIGNAL_PINCHED = "pinched";
206 const char* SIGNAL_LONG_PRESSED = "longPressed";
207 static bool DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
208 {
209   Dali::BaseHandle handle( object );
210
211   bool connected( false );
212   Toolkit::Control control = Toolkit::Control::DownCast( handle );
213   if ( control )
214   {
215     Internal::Control& controlImpl( Internal::GetImplementation( control ) );
216     connected = true;
217
218     if ( 0 == strcmp( signalName.c_str(), SIGNAL_KEY_EVENT ) )
219     {
220       controlImpl.KeyEventSignal().Connect( tracker, functor );
221     }
222     else if( 0 == strcmp( signalName.c_str(), SIGNAL_KEY_INPUT_FOCUS_GAINED ) )
223     {
224       controlImpl.KeyInputFocusGainedSignal().Connect( tracker, functor );
225     }
226     else if( 0 == strcmp( signalName.c_str(), SIGNAL_KEY_INPUT_FOCUS_LOST ) )
227     {
228       controlImpl.KeyInputFocusLostSignal().Connect( tracker, functor );
229     }
230     else if( 0 == strcmp( signalName.c_str(), SIGNAL_TAPPED ) )
231     {
232       controlImpl.EnableGestureDetection( Gesture::Tap );
233       controlImpl.GetTapGestureDetector().DetectedSignal().Connect( tracker, functor );
234     }
235     else if( 0 == strcmp( signalName.c_str(), SIGNAL_PANNED ) )
236     {
237       controlImpl.EnableGestureDetection( Gesture::Pan );
238       controlImpl.GetPanGestureDetector().DetectedSignal().Connect( tracker, functor );
239     }
240     else if( 0 == strcmp( signalName.c_str(), SIGNAL_PINCHED ) )
241     {
242       controlImpl.EnableGestureDetection( Gesture::Pinch );
243       controlImpl.GetPinchGestureDetector().DetectedSignal().Connect( tracker, functor );
244     }
245     else if( 0 == strcmp( signalName.c_str(), SIGNAL_LONG_PRESSED ) )
246     {
247       controlImpl.EnableGestureDetection( Gesture::LongPress );
248       controlImpl.GetLongPressGestureDetector().DetectedSignal().Connect( tracker, functor );
249     }
250   }
251   return connected;
252 }
253
254 /**
255  * Creates control through type registry
256  */
257 BaseHandle Create()
258 {
259   return Internal::Control::New();
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 /**
279  * @brief Iterate through given container and setOffStage any visual found
280  *
281  * @param[in] container Container of visuals
282  * @param[in] parent Parent actor to remove visuals from
283  */
284 void SetVisualsOffStage( const RegisteredVisualContainer& container, Actor parent )
285 {
286   for( auto iter = container.Begin(), end = container.End() ; iter!= end; iter++)
287   {
288     if( (*iter)->visual )
289     {
290       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::SetOffStage Setting visual(%d) off stage\n", (*iter)->index );
291       Toolkit::GetImplementation((*iter)->visual).SetOffStage( parent );
292     }
293   }
294 }
295
296 } // unnamed namespace
297
298
299 // Properties registered without macro to use specific member variables.
300 const PropertyRegistration Control::Impl::PROPERTY_1( typeRegistration, "styleName",              Toolkit::Control::Property::STYLE_NAME,                   Property::STRING,  &Control::Impl::SetProperty, &Control::Impl::GetProperty );
301 const PropertyRegistration Control::Impl::PROPERTY_2( typeRegistration, "backgroundColor",        Toolkit::Control::Property::BACKGROUND_COLOR,             Property::VECTOR4, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
302 const PropertyRegistration Control::Impl::PROPERTY_3( typeRegistration, "backgroundImage",        Toolkit::Control::Property::BACKGROUND_IMAGE,             Property::MAP,     &Control::Impl::SetProperty, &Control::Impl::GetProperty );
303 const PropertyRegistration Control::Impl::PROPERTY_4( typeRegistration, "keyInputFocus",          Toolkit::Control::Property::KEY_INPUT_FOCUS,              Property::BOOLEAN, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
304 const PropertyRegistration Control::Impl::PROPERTY_5( typeRegistration, "background",             Toolkit::Control::Property::BACKGROUND,                   Property::MAP,     &Control::Impl::SetProperty, &Control::Impl::GetProperty );
305 const PropertyRegistration Control::Impl::PROPERTY_6( typeRegistration, "margin",                 Toolkit::Control::Property::MARGIN,                       Property::EXTENTS, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
306 const PropertyRegistration Control::Impl::PROPERTY_7( typeRegistration, "padding",                Toolkit::Control::Property::PADDING,                      Property::EXTENTS, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
307 const PropertyRegistration Control::Impl::PROPERTY_8( typeRegistration, "tooltip",                Toolkit::DevelControl::Property::TOOLTIP,                 Property::MAP,     &Control::Impl::SetProperty, &Control::Impl::GetProperty );
308 const PropertyRegistration Control::Impl::PROPERTY_9( typeRegistration, "state",                  Toolkit::DevelControl::Property::STATE,                   Property::STRING,  &Control::Impl::SetProperty, &Control::Impl::GetProperty );
309 const PropertyRegistration Control::Impl::PROPERTY_10( typeRegistration, "subState",               Toolkit::DevelControl::Property::SUB_STATE,               Property::STRING,  &Control::Impl::SetProperty, &Control::Impl::GetProperty );
310 const PropertyRegistration Control::Impl::PROPERTY_11( typeRegistration, "leftFocusableActorId",   Toolkit::DevelControl::Property::LEFT_FOCUSABLE_ACTOR_ID, Property::INTEGER, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
311 const PropertyRegistration Control::Impl::PROPERTY_12( typeRegistration, "rightFocusableActorId", Toolkit::DevelControl::Property::RIGHT_FOCUSABLE_ACTOR_ID,Property::INTEGER, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
312 const PropertyRegistration Control::Impl::PROPERTY_13( typeRegistration, "upFocusableActorId",    Toolkit::DevelControl::Property::UP_FOCUSABLE_ACTOR_ID,   Property::INTEGER, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
313 const PropertyRegistration Control::Impl::PROPERTY_14( typeRegistration, "downFocusableActorId",  Toolkit::DevelControl::Property::DOWN_FOCUSABLE_ACTOR_ID, Property::INTEGER, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
314
315
316 Control::Impl::Impl( Control& controlImpl )
317 : mControlImpl( controlImpl ),
318   mState( Toolkit::DevelControl::NORMAL ),
319   mSubStateName(""),
320   mLeftFocusableActorId( -1 ),
321   mRightFocusableActorId( -1 ),
322   mUpFocusableActorId( -1 ),
323   mDownFocusableActorId( -1 ),
324   mStyleName(""),
325   mBackgroundColor(Color::TRANSPARENT),
326   mStartingPinchScale( NULL ),
327   mMargin( 0, 0, 0, 0 ),
328   mPadding( 0, 0, 0, 0 ),
329   mKeyEventSignal(),
330   mPinchGestureDetector(),
331   mPanGestureDetector(),
332   mTapGestureDetector(),
333   mLongPressGestureDetector(),
334   mFlags( Control::ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ),
335   mIsKeyboardNavigationSupported( false ),
336   mIsKeyboardFocusGroup( false )
337 {
338
339 }
340
341 Control::Impl::~Impl()
342 {
343   // All gesture detectors will be destroyed so no need to disconnect.
344   delete mStartingPinchScale;
345 }
346
347 Control::Impl& Control::Impl::Get( Internal::Control& internalControl )
348 {
349   return *internalControl.mImpl;
350 }
351
352 const Control::Impl& Control::Impl::Get( const Internal::Control& internalControl )
353 {
354   return *internalControl.mImpl;
355 }
356
357 // Gesture Detection Methods
358 void Control::Impl::PinchDetected(Actor actor, const PinchGesture& pinch)
359 {
360   mControlImpl.OnPinch(pinch);
361 }
362
363 void Control::Impl::PanDetected(Actor actor, const PanGesture& pan)
364 {
365   mControlImpl.OnPan(pan);
366 }
367
368 void Control::Impl::TapDetected(Actor actor, const TapGesture& tap)
369 {
370   mControlImpl.OnTap(tap);
371 }
372
373 void Control::Impl::LongPressDetected(Actor actor, const LongPressGesture& longPress)
374 {
375   mControlImpl.OnLongPress(longPress);
376 }
377
378 void Control::Impl::RegisterVisual( Property::Index index, Toolkit::Visual::Base& visual )
379 {
380   RegisterVisual( index, visual, VisualState::ENABLED, DepthIndexValue::NOT_SET );
381 }
382
383 void Control::Impl::RegisterVisual( Property::Index index, Toolkit::Visual::Base& visual, int depthIndex )
384 {
385   RegisterVisual( index, visual, VisualState::ENABLED, DepthIndexValue::SET, depthIndex );
386 }
387
388 void Control::Impl::RegisterVisual( Property::Index index, Toolkit::Visual::Base& visual, bool enabled )
389 {
390   RegisterVisual( index, visual, ( enabled ? VisualState::ENABLED : VisualState::DISABLED ), DepthIndexValue::NOT_SET );
391 }
392
393 void Control::Impl::RegisterVisual( Property::Index index, Toolkit::Visual::Base& visual, bool enabled, int depthIndex )
394 {
395   RegisterVisual( index, visual, ( enabled ? VisualState::ENABLED : VisualState::DISABLED ), DepthIndexValue::SET, depthIndex );
396 }
397
398 void Control::Impl::RegisterVisual( Property::Index index, Toolkit::Visual::Base& visual, VisualState::Type enabled, DepthIndexValue::Type depthIndexValueSet, int depthIndex )
399 {
400   DALI_LOG_INFO( gLogFilter, Debug::Concise, "RegisterVisual:%d \n", index );
401
402   bool visualReplaced ( false );
403   Actor self = mControlImpl.Self();
404
405   // Set the depth index, if not set by caller this will be either the current visual depth, max depth of all visuals
406   // or zero.
407   int requiredDepthIndex = visual.GetDepthIndex();
408
409   if( depthIndexValueSet == DepthIndexValue::SET )
410   {
411     requiredDepthIndex = depthIndex;
412   }
413
414   // Visual replacement, existing visual should only be removed from stage when replacement ready.
415   if( !mVisuals.Empty() )
416   {
417     RegisteredVisualContainer::Iterator registeredVisualsiter;
418     // Check if visual (index) is already registered, this is the current visual.
419     if( FindVisual( index, mVisuals, registeredVisualsiter ) )
420     {
421       Toolkit::Visual::Base& currentRegisteredVisual = (*registeredVisualsiter)->visual;
422       if( currentRegisteredVisual )
423       {
424         // Store current visual depth index as may need to set the replacement visual to same depth
425         const int currentDepthIndex = (*registeredVisualsiter)->visual.GetDepthIndex();
426
427         // No longer required to know if the replaced visual's resources are ready
428         StopObservingVisual( currentRegisteredVisual );
429
430         // If control staged and visual enabled then visuals will be swapped once ready
431         if(  self.OnStage() && enabled )
432         {
433           // Check if visual is currently in the process of being replaced ( is in removal container )
434           RegisteredVisualContainer::Iterator visualQueuedForRemoval;
435           if ( FindVisual( index, mRemoveVisuals, visualQueuedForRemoval ) )
436           {
437             // Visual with same index is already in removal container so current visual pending
438             // Only the the last requested visual will be displayed so remove current visual which is staged but not ready.
439             Toolkit::GetImplementation( currentRegisteredVisual ).SetOffStage( self );
440             mVisuals.Erase( registeredVisualsiter );
441           }
442           else
443           {
444             // current visual not already in removal container so add now.
445             DALI_LOG_INFO( gLogFilter, Debug::Verbose, "RegisterVisual Move current registered visual to removal Queue: %d \n", index );
446             MoveVisual( registeredVisualsiter, mVisuals, mRemoveVisuals );
447           }
448         }
449         else
450         {
451           // Control not staged or visual disabled so can just erase from registered visuals and new visual will be added later.
452           mVisuals.Erase( registeredVisualsiter );
453         }
454
455         // If we've not set the depth-index value and the new visual does not have a depth index applied to it, then use the previously set depth-index for this index
456         if( ( depthIndexValueSet == DepthIndexValue::NOT_SET ) &&
457             ( visual.GetDepthIndex() == 0 ) )
458         {
459           requiredDepthIndex = currentDepthIndex;
460         }
461       }
462
463       visualReplaced = true;
464     }
465   }
466
467   // If not set, set the name of the visual to the same name as the control's property.
468   // ( If the control has been type registered )
469   if( visual.GetName().empty() )
470   {
471     try
472     {
473       std::string visualName = self.GetPropertyName( index );
474       if( !visualName.empty() )
475       {
476         DALI_LOG_INFO( gLogFilter, Debug::Concise, "Setting visual name for property %d to %s\n",
477                        index, visualName.c_str() );
478         visual.SetName( visualName );
479       }
480     }
481     catch( Dali::DaliException e )
482     {
483       DALI_LOG_WARNING( "Attempting to register visual without a registered property, index: %d\n", index );
484     }
485   }
486
487   if( !visualReplaced ) // New registration entry
488   {
489     // monitor when the visual resources are ready
490     StartObservingVisual( visual );
491
492     // If we've not set the depth-index value, we have more than one visual and the visual does not have a depth index, then set it to be the highest
493     if( ( depthIndexValueSet == DepthIndexValue::NOT_SET ) &&
494         ( mVisuals.Size() > 0 ) &&
495         ( visual.GetDepthIndex() == 0 ) )
496     {
497       int maxDepthIndex = std::numeric_limits< int >::min();
498
499       RegisteredVisualContainer::ConstIterator iter;
500       const RegisteredVisualContainer::ConstIterator endIter = mVisuals.End();
501       for ( iter = mVisuals.Begin(); iter != endIter; iter++ )
502       {
503         const int visualDepthIndex = (*iter)->visual.GetDepthIndex();
504         if ( visualDepthIndex > maxDepthIndex )
505         {
506           maxDepthIndex = visualDepthIndex;
507         }
508       }
509       ++maxDepthIndex; // Add one to the current maximum depth index so that our added visual appears on top
510       requiredDepthIndex = std::max( 0, maxDepthIndex ); // Start at zero if maxDepth index belongs to a background
511     }
512   }
513
514   if( visual )
515   {
516     // Set determined depth index
517     visual.SetDepthIndex( requiredDepthIndex );
518
519     // Monitor when the visual resources are ready
520     StartObservingVisual( visual );
521
522     DALI_LOG_INFO( gLogFilter, Debug::Concise, "New Visual registration index[%d] depth[%d]\n", index, requiredDepthIndex );
523     RegisteredVisual* newRegisteredVisual  = new RegisteredVisual( index, visual,
524                                              ( enabled == VisualState::ENABLED ? true : false ),
525                                              ( visualReplaced && enabled ) ) ;
526     mVisuals.PushBack( newRegisteredVisual );
527
528     // Put on stage if enabled and the control is already on the stage
529     // Visual must be set on stage for the renderer to be created and the ResourceReady triggered.
530     if( ( enabled == VisualState::ENABLED ) && self.OnStage() )
531     {
532       Toolkit::GetImplementation(visual).SetOnStage( self );
533     }
534   }
535
536   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::RegisterVisual() Registered %s(%d), enabled:%s\n",  visual.GetName().c_str(), index, enabled?"true":"false" );
537 }
538
539 void Control::Impl::UnregisterVisual( Property::Index index )
540 {
541    RegisteredVisualContainer::Iterator iter;
542    if ( FindVisual( index, mVisuals, iter ) )
543    {
544      // stop observing visual
545      StopObservingVisual( (*iter)->visual );
546
547      Actor self( mControlImpl.Self() );
548      Toolkit::GetImplementation((*iter)->visual).SetOffStage( self );
549      (*iter)->visual.Reset();
550      mVisuals.Erase( iter );
551    }
552 }
553
554 Toolkit::Visual::Base Control::Impl::GetVisual( Property::Index index ) const
555 {
556   RegisteredVisualContainer::Iterator iter;
557   if ( FindVisual( index, mVisuals, iter ) )
558   {
559     return (*iter)->visual;
560   }
561
562   return Toolkit::Visual::Base();
563 }
564
565 void Control::Impl::EnableVisual( Property::Index index, bool enable )
566 {
567   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::EnableVisual Visual (%d)\n", index);
568
569   RegisteredVisualContainer::Iterator iter;
570   if ( FindVisual( index, mVisuals, iter ) )
571   {
572     if (  (*iter)->enabled == enable )
573     {
574       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::EnableVisual Visual %s(%d) already %s\n", (*iter)->visual.GetName().c_str(), index, enable?"enabled":"disabled");
575       return;
576     }
577
578     (*iter)->enabled = enable;
579     Actor parentActor = mControlImpl.Self();
580     if ( mControlImpl.Self().OnStage() ) // If control not on Stage then Visual will be added when StageConnection is called.
581     {
582       if ( enable )
583       {
584         DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::EnableVisual Setting %s(%d) on stage \n", (*iter)->visual.GetName().c_str(), index );
585         Toolkit::GetImplementation((*iter)->visual).SetOnStage( parentActor );
586       }
587       else
588       {
589         DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::EnableVisual Setting %s(%d) off stage \n", (*iter)->visual.GetName().c_str(), index );
590         Toolkit::GetImplementation((*iter)->visual).SetOffStage( parentActor );  // No need to call if control not staged.
591       }
592     }
593   }
594 }
595
596 bool Control::Impl::IsVisualEnabled( Property::Index index ) const
597 {
598   RegisteredVisualContainer::Iterator iter;
599   if ( FindVisual( index, mVisuals, iter ) )
600   {
601     return (*iter)->enabled;
602   }
603   return false;
604 }
605
606 void Control::Impl::StopObservingVisual( Toolkit::Visual::Base& visual )
607 {
608   Internal::Visual::Base& visualImpl = Toolkit::GetImplementation( visual );
609
610   // Stop observing the visual
611   visualImpl.RemoveResourceObserver( *this );
612 }
613
614 void Control::Impl::StartObservingVisual( Toolkit::Visual::Base& visual)
615 {
616   Internal::Visual::Base& visualImpl = Toolkit::GetImplementation( visual );
617
618   // start observing the visual for resource ready
619   visualImpl.AddResourceObserver( *this );
620 }
621
622 // Called by a Visual when it's resource is ready
623 void Control::Impl::ResourceReady( Visual::Base& object)
624 {
625   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "ResourceReady replacements pending[%d]\n", mRemoveVisuals.Count() );
626
627   Actor self = mControlImpl.Self();
628
629   // A resource is ready, find resource in the registered visuals container and get its index
630   for( auto registeredIter = mVisuals.Begin(),  end = mVisuals.End(); registeredIter != end; ++registeredIter )
631   {
632     Internal::Visual::Base& registeredVisualImpl = Toolkit::GetImplementation( (*registeredIter)->visual );
633
634     if( &object == &registeredVisualImpl )
635     {
636       RegisteredVisualContainer::Iterator visualToRemoveIter;
637       // Find visual with the same index in the removal container
638       // Set if off stage as it's replacement is now ready.
639       // Remove if from removal list as now removed from stage.
640       // Set Pending flag on the ready visual to false as now ready.
641       if( FindVisual( (*registeredIter)->index, mRemoveVisuals, visualToRemoveIter ) )
642       {
643         (*registeredIter)->pending = false;
644         Toolkit::GetImplementation( (*visualToRemoveIter)->visual ).SetOffStage( self );
645         mRemoveVisuals.Erase( visualToRemoveIter );
646       }
647       break;
648     }
649   }
650
651   // A visual is ready so control may need relayouting
652   mControlImpl.RelayoutRequest();
653
654   // Emit signal if all enabled visuals registered by the control are ready.
655   if( IsResourceReady() )
656   {
657     Dali::Toolkit::Control handle( mControlImpl.GetOwner() );
658     mResourceReadySignal.Emit( handle );
659   }
660 }
661
662 bool Control::Impl::IsResourceReady() const
663 {
664   // Iterate through and check all the enabled visuals are ready
665   for( auto visualIter = mVisuals.Begin();
666          visualIter != mVisuals.End(); ++visualIter )
667   {
668     const Toolkit::Visual::Base visual = (*visualIter)->visual;
669     const Internal::Visual::Base& visualImpl = Toolkit::GetImplementation( visual );
670
671     // one of the enabled visuals is not ready
672     if( !visualImpl.IsResourceReady() && (*visualIter)->enabled )
673     {
674       return false;
675     }
676   }
677   return true;
678 }
679
680
681 Dali::Animation Control::Impl::CreateTransition( const Toolkit::TransitionData& handle )
682 {
683   Dali::Animation transition;
684   const Internal::TransitionData& transitionData = Toolkit::GetImplementation( handle );
685
686   if( transitionData.Count() > 0 )
687   {
688     // Setup a Transition from TransitionData.
689     TransitionData::Iterator end = transitionData.End();
690     for( TransitionData::Iterator iter = transitionData.Begin() ;
691          iter != end; ++iter )
692     {
693       TransitionData::Animator* animator = (*iter);
694
695       Toolkit::Visual::Base visual = GetVisualByName( mVisuals, animator->objectName );
696
697       if( visual )
698       {
699 #if defined(DEBUG_ENABLED)
700         Dali::TypeInfo typeInfo;
701         ControlWrapper* controlWrapperImpl = dynamic_cast<ControlWrapper*>(&mControlImpl);
702         if( controlWrapperImpl )
703         {
704           typeInfo = controlWrapperImpl->GetTypeInfo();
705         }
706
707         DALI_LOG_INFO( gLogFilter, Debug::Concise, "CreateTransition: Found %s visual for %s\n",
708                        visual.GetName().c_str(), typeInfo?typeInfo.GetName().c_str():"Unknown" );
709 #endif
710         Internal::Visual::Base& visualImpl = Toolkit::GetImplementation( visual );
711         visualImpl.AnimateProperty( transition, *animator );
712       }
713       else
714       {
715         DALI_LOG_INFO( gLogFilter, Debug::Concise, "CreateTransition: Could not find visual. Trying actors");
716         // Otherwise, try any actor children of control (Including the control)
717         Actor child = mControlImpl.Self().FindChildByName( animator->objectName );
718         if( child )
719         {
720           Property::Index propertyIndex = DevelHandle::GetPropertyIndex( child, animator->propertyKey );
721           if( propertyIndex != Property::INVALID_INDEX )
722           {
723             if( animator->animate == false )
724             {
725               if( animator->targetValue.GetType() != Property::NONE )
726               {
727                 child.SetProperty( propertyIndex, animator->targetValue );
728               }
729             }
730             else // animate the property
731             {
732               if( animator->initialValue.GetType() != Property::NONE )
733               {
734                 child.SetProperty( propertyIndex, animator->initialValue );
735               }
736
737               if( ! transition )
738               {
739                 transition = Dali::Animation::New( 0.1f );
740               }
741
742               transition.AnimateTo( Property( child, propertyIndex ),
743                                     animator->targetValue,
744                                     animator->alphaFunction,
745                                     TimePeriod( animator->timePeriodDelay,
746                                                 animator->timePeriodDuration ) );
747             }
748           }
749         }
750       }
751     }
752   }
753
754   return transition;
755 }
756
757 void Control::Impl::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
758 {
759   Toolkit::Control control = Toolkit::Control::DownCast( BaseHandle( object ) );
760
761   if ( control )
762   {
763     Control& controlImpl( GetImplementation( control ) );
764
765     switch ( index )
766     {
767       case Toolkit::Control::Property::STYLE_NAME:
768       {
769         controlImpl.SetStyleName( value.Get< std::string >() );
770         break;
771       }
772
773       case Toolkit::DevelControl::Property::STATE:
774       {
775         bool withTransitions=true;
776         const Property::Value* valuePtr=&value;
777         Property::Map* map = value.GetMap();
778         if(map)
779         {
780           Property::Value* value2 = map->Find("withTransitions");
781           if( value2 )
782           {
783             withTransitions = value2->Get<bool>();
784           }
785
786           valuePtr = map->Find("state");
787         }
788
789         if( valuePtr )
790         {
791           Toolkit::DevelControl::State state( controlImpl.mImpl->mState );
792           if( Scripting::GetEnumerationProperty< Toolkit::DevelControl::State >( *valuePtr, ControlStateTable, ControlStateTableCount, state ) )
793           {
794             controlImpl.mImpl->SetState( state, withTransitions );
795           }
796         }
797       }
798       break;
799
800       case Toolkit::DevelControl::Property::SUB_STATE:
801       {
802         std::string subState;
803         if( value.Get( subState ) )
804         {
805           controlImpl.mImpl->SetSubState( subState );
806         }
807       }
808       break;
809
810       case Toolkit::DevelControl::Property::LEFT_FOCUSABLE_ACTOR_ID:
811       {
812         int focusId;
813         if( value.Get( focusId ) )
814         {
815           controlImpl.mImpl->mLeftFocusableActorId = focusId;
816         }
817       }
818       break;
819
820       case Toolkit::DevelControl::Property::RIGHT_FOCUSABLE_ACTOR_ID:
821       {
822         int focusId;
823         if( value.Get( focusId ) )
824         {
825           controlImpl.mImpl->mRightFocusableActorId = focusId;
826         }
827       }
828       break;
829
830       case Toolkit::DevelControl::Property::UP_FOCUSABLE_ACTOR_ID:
831       {
832         int focusId;
833         if( value.Get( focusId ) )
834         {
835           controlImpl.mImpl->mUpFocusableActorId = focusId;
836         }
837       }
838       break;
839
840       case Toolkit::DevelControl::Property::DOWN_FOCUSABLE_ACTOR_ID:
841       {
842         int focusId;
843         if( value.Get( focusId ) )
844         {
845           controlImpl.mImpl->mDownFocusableActorId = focusId;
846         }
847       }
848       break;
849
850       case Toolkit::Control::Property::BACKGROUND_COLOR:
851       {
852         DALI_LOG_WARNING( "BACKGROUND_COLOR property is deprecated. Use BACKGROUND property instead\n" );
853         controlImpl.SetBackgroundColor( value.Get< Vector4 >() );
854         break;
855       }
856
857       case Toolkit::Control::Property::BACKGROUND_IMAGE:
858       {
859         DALI_LOG_WARNING( "BACKGROUND_IMAGE property is deprecated. Use BACKGROUND property instead\n" );
860         Image image = Scripting::NewImage( value );
861         if ( image )
862         {
863           controlImpl.SetBackgroundImage( image );
864         }
865         else
866         {
867           // An empty image means the background is no longer required
868           controlImpl.ClearBackground();
869         }
870         break;
871       }
872
873       case Toolkit::Control::Property::KEY_INPUT_FOCUS:
874       {
875         if ( value.Get< bool >() )
876         {
877           controlImpl.SetKeyInputFocus();
878         }
879         else
880         {
881           controlImpl.ClearKeyInputFocus();
882         }
883         break;
884       }
885
886       case Toolkit::Control::Property::BACKGROUND:
887       {
888         std::string url;
889         Vector4 color;
890         const Property::Map* map = value.GetMap();
891         if( map && !map->Empty() )
892         {
893           controlImpl.SetBackground( *map );
894         }
895         else if( value.Get( url ) )
896         {
897           // don't know the size to load
898           Toolkit::Visual::Base visual = Toolkit::VisualFactory::Get().CreateVisual( url, ImageDimensions() );
899           if( visual )
900           {
901             controlImpl.mImpl->RegisterVisual( Toolkit::Control::Property::BACKGROUND, visual, DepthIndex::BACKGROUND );
902           }
903         }
904         else if( value.Get( color ) )
905         {
906           controlImpl.SetBackgroundColor(color);
907         }
908         else
909         {
910           // The background is an empty property map, so we should clear the background
911           controlImpl.ClearBackground();
912         }
913         break;
914       }
915
916       case Toolkit::Control::Property::MARGIN:
917       {
918         Extents margin;
919         if( value.Get( margin ) )
920         {
921           controlImpl.mImpl->SetMargin( margin );
922         }
923         break;
924       }
925
926       case Toolkit::Control::Property::PADDING:
927       {
928         Extents padding;
929         if( value.Get( padding ) )
930         {
931           controlImpl.mImpl->SetPadding( padding );
932         }
933         break;
934       }
935
936       case Toolkit::DevelControl::Property::TOOLTIP:
937       {
938         TooltipPtr& tooltipPtr = controlImpl.mImpl->mTooltip;
939         if( ! tooltipPtr )
940         {
941           tooltipPtr = Tooltip::New( control );
942         }
943         tooltipPtr->SetProperties( value );
944         break;
945       }
946
947     }
948   }
949 }
950
951 Property::Value Control::Impl::GetProperty( BaseObject* object, Property::Index index )
952 {
953   Property::Value value;
954
955   Toolkit::Control control = Toolkit::Control::DownCast( BaseHandle( object ) );
956
957   if ( control )
958   {
959     Control& controlImpl( GetImplementation( control ) );
960
961     switch ( index )
962     {
963       case Toolkit::Control::Property::STYLE_NAME:
964       {
965         value = controlImpl.GetStyleName();
966         break;
967       }
968
969       case Toolkit::DevelControl::Property::STATE:
970       {
971         value = controlImpl.mImpl->mState;
972         break;
973       }
974
975       case Toolkit::DevelControl::Property::SUB_STATE:
976       {
977         value = controlImpl.mImpl->mSubStateName;
978         break;
979       }
980
981       case Toolkit::DevelControl::Property::LEFT_FOCUSABLE_ACTOR_ID:
982       {
983         value = controlImpl.mImpl->mLeftFocusableActorId;
984         break;
985       }
986
987       case Toolkit::DevelControl::Property::RIGHT_FOCUSABLE_ACTOR_ID:
988       {
989         value = controlImpl.mImpl->mRightFocusableActorId;
990         break;
991       }
992
993       case Toolkit::DevelControl::Property::UP_FOCUSABLE_ACTOR_ID:
994       {
995         value = controlImpl.mImpl->mUpFocusableActorId;
996         break;
997       }
998
999       case Toolkit::DevelControl::Property::DOWN_FOCUSABLE_ACTOR_ID:
1000       {
1001         value = controlImpl.mImpl->mDownFocusableActorId;
1002         break;
1003       }
1004
1005       case Toolkit::Control::Property::BACKGROUND_COLOR:
1006       {
1007         DALI_LOG_WARNING( "BACKGROUND_COLOR property is deprecated. Use BACKGROUND property instead\n" );
1008         value = controlImpl.GetBackgroundColor();
1009         break;
1010       }
1011
1012       case Toolkit::Control::Property::BACKGROUND_IMAGE:
1013       {
1014         DALI_LOG_WARNING( "BACKGROUND_IMAGE property is deprecated. Use BACKGROUND property instead\n" );
1015         Property::Map map;
1016         Toolkit::Visual::Base visual = controlImpl.mImpl->GetVisual( Toolkit::Control::Property::BACKGROUND );
1017         if( visual )
1018         {
1019           visual.CreatePropertyMap( map );
1020         }
1021         value = map;
1022         break;
1023       }
1024
1025       case Toolkit::Control::Property::KEY_INPUT_FOCUS:
1026       {
1027         value = controlImpl.HasKeyInputFocus();
1028         break;
1029       }
1030
1031       case Toolkit::Control::Property::BACKGROUND:
1032       {
1033         Property::Map map;
1034         Toolkit::Visual::Base visual = controlImpl.mImpl->GetVisual( Toolkit::Control::Property::BACKGROUND );
1035         if( visual )
1036         {
1037           visual.CreatePropertyMap( map );
1038         }
1039
1040         value = map;
1041         break;
1042       }
1043
1044       case Toolkit::Control::Property::MARGIN:
1045       {
1046         value = controlImpl.mImpl->GetMargin();
1047         break;
1048       }
1049
1050       case Toolkit::Control::Property::PADDING:
1051       {
1052         value = controlImpl.mImpl->GetPadding();
1053         break;
1054       }
1055
1056       case Toolkit::DevelControl::Property::TOOLTIP:
1057       {
1058         Property::Map map;
1059         if( controlImpl.mImpl->mTooltip )
1060         {
1061           controlImpl.mImpl->mTooltip->CreatePropertyMap( map );
1062         }
1063         value = map;
1064         break;
1065       }
1066     }
1067   }
1068
1069   return value;
1070 }
1071
1072
1073 void  Control::Impl::CopyInstancedProperties( RegisteredVisualContainer& visuals, Dictionary<Property::Map>& instancedProperties )
1074 {
1075   for(RegisteredVisualContainer::Iterator iter = visuals.Begin(); iter!= visuals.End(); iter++)
1076   {
1077     if( (*iter)->visual )
1078     {
1079       Property::Map instanceMap;
1080       Toolkit::GetImplementation((*iter)->visual).CreateInstancePropertyMap(instanceMap);
1081       instancedProperties.Add( (*iter)->visual.GetName(), instanceMap );
1082     }
1083   }
1084 }
1085
1086
1087 void Control::Impl::RemoveVisual( RegisteredVisualContainer& visuals, const std::string& visualName )
1088 {
1089   Actor self( mControlImpl.Self() );
1090
1091   for ( RegisteredVisualContainer::Iterator visualIter = visuals.Begin();
1092         visualIter != visuals.End(); ++visualIter )
1093   {
1094     Toolkit::Visual::Base visual = (*visualIter)->visual;
1095     if( visual && visual.GetName() == visualName )
1096     {
1097       Toolkit::GetImplementation(visual).SetOffStage( self );
1098       (*visualIter)->visual.Reset();
1099       visuals.Erase( visualIter );
1100       break;
1101     }
1102   }
1103 }
1104
1105 void Control::Impl::RemoveVisuals( RegisteredVisualContainer& visuals, DictionaryKeys& removeVisuals )
1106 {
1107   Actor self( mControlImpl.Self() );
1108   for( DictionaryKeys::iterator iter = removeVisuals.begin(); iter != removeVisuals.end(); ++iter )
1109   {
1110     const std::string visualName = *iter;
1111     RemoveVisual( visuals, visualName );
1112   }
1113 }
1114
1115 void Control::Impl::RecreateChangedVisuals( Dictionary<Property::Map>& stateVisualsToChange,
1116                              Dictionary<Property::Map>& instancedProperties )
1117 {
1118   Dali::CustomActor handle( mControlImpl.GetOwner() );
1119   for( Dictionary<Property::Map>::iterator iter = stateVisualsToChange.Begin();
1120        iter != stateVisualsToChange.End(); ++iter )
1121   {
1122     const std::string& visualName = (*iter).key;
1123     const Property::Map& toMap = (*iter).entry;
1124
1125     // is it a candidate for re-creation?
1126     bool recreate = false;
1127
1128     Toolkit::Visual::Base visual = GetVisualByName( mVisuals, visualName );
1129     if( visual )
1130     {
1131       Property::Map fromMap;
1132       visual.CreatePropertyMap( fromMap );
1133
1134       Toolkit::Visual::Type fromType = GetVisualTypeFromMap( fromMap );
1135       Toolkit::Visual::Type toType = GetVisualTypeFromMap( toMap );
1136
1137       if( fromType != toType )
1138       {
1139         recreate = true;
1140       }
1141       else
1142       {
1143         if( fromType == Toolkit::Visual::IMAGE || fromType == Toolkit::Visual::N_PATCH
1144             || fromType == Toolkit::Visual::SVG || fromType == Toolkit::Visual::ANIMATED_IMAGE )
1145         {
1146           Property::Value* fromUrl = fromMap.Find( Toolkit::ImageVisual::Property::URL, IMAGE_URL_NAME );
1147           Property::Value* toUrl = toMap.Find( Toolkit::ImageVisual::Property::URL, IMAGE_URL_NAME );
1148
1149           if( fromUrl && toUrl )
1150           {
1151             std::string fromUrlString;
1152             std::string toUrlString;
1153             fromUrl->Get(fromUrlString);
1154             toUrl->Get(toUrlString);
1155
1156             if( fromUrlString != toUrlString )
1157             {
1158               recreate = true;
1159             }
1160           }
1161         }
1162       }
1163
1164       const Property::Map* instancedMap = instancedProperties.FindConst( visualName );
1165       if( recreate || instancedMap )
1166       {
1167         RemoveVisual( mVisuals, visualName );
1168         Style::ApplyVisual( handle, visualName, toMap, instancedMap );
1169       }
1170       else
1171       {
1172         // @todo check to see if we can apply toMap without recreating the visual
1173         // e.g. by setting only animatable properties
1174         // For now, recreate all visuals, but merge in instance data.
1175         RemoveVisual( mVisuals, visualName );
1176         Style::ApplyVisual( handle, visualName, toMap, instancedMap );
1177       }
1178     }
1179   }
1180 }
1181
1182 void Control::Impl::ReplaceStateVisualsAndProperties( const StylePtr oldState, const StylePtr newState, const std::string& subState )
1183 {
1184   // Collect all old visual names
1185   DictionaryKeys stateVisualsToRemove;
1186   if( oldState )
1187   {
1188     oldState->visuals.GetKeys( stateVisualsToRemove );
1189     if( ! subState.empty() )
1190     {
1191       const StylePtr* oldSubState = oldState->subStates.FindConst(subState);
1192       if( oldSubState )
1193       {
1194         DictionaryKeys subStateVisualsToRemove;
1195         (*oldSubState)->visuals.GetKeys( subStateVisualsToRemove );
1196         Merge( stateVisualsToRemove, subStateVisualsToRemove );
1197       }
1198     }
1199   }
1200
1201   // Collect all new visual properties
1202   Dictionary<Property::Map> stateVisualsToAdd;
1203   if( newState )
1204   {
1205     stateVisualsToAdd = newState->visuals;
1206     if( ! subState.empty() )
1207     {
1208       const StylePtr* newSubState = newState->subStates.FindConst(subState);
1209       if( newSubState )
1210       {
1211         stateVisualsToAdd.Merge( (*newSubState)->visuals );
1212       }
1213     }
1214   }
1215
1216   // If a name is in both add/remove, move it to change list.
1217   Dictionary<Property::Map> stateVisualsToChange;
1218   FindChangableVisuals( stateVisualsToAdd, stateVisualsToChange, stateVisualsToRemove);
1219
1220   // Copy instanced properties (e.g. text label) of current visuals
1221   Dictionary<Property::Map> instancedProperties;
1222   CopyInstancedProperties( mVisuals, instancedProperties );
1223
1224   // For each visual in remove list, remove from mVisuals
1225   RemoveVisuals( mVisuals, stateVisualsToRemove );
1226
1227   // For each visual in add list, create and add to mVisuals
1228   Dali::CustomActor handle( mControlImpl.GetOwner() );
1229   Style::ApplyVisuals( handle, stateVisualsToAdd, instancedProperties );
1230
1231   // For each visual in change list, if it requires a new visual,
1232   // remove old visual, create and add to mVisuals
1233   RecreateChangedVisuals( stateVisualsToChange, instancedProperties );
1234 }
1235
1236 void Control::Impl::SetState( DevelControl::State newState, bool withTransitions )
1237 {
1238   DevelControl::State oldState = mState;
1239   Dali::CustomActor handle( mControlImpl.GetOwner() );
1240   DALI_LOG_INFO(gLogFilter, Debug::Concise, "Control::Impl::SetState: %s\n",
1241                 (mState == DevelControl::NORMAL ? "NORMAL" :(
1242                   mState == DevelControl::FOCUSED ?"FOCUSED" : (
1243                     mState == DevelControl::DISABLED?"DISABLED":"NONE" ))));
1244
1245   if( mState != newState )
1246   {
1247     // If mState was Disabled, and new state is Focused, should probably
1248     // store that fact, e.g. in another property that FocusManager can access.
1249     mState = newState;
1250
1251     // Trigger state change and transitions
1252     // Apply new style, if stylemanager is available
1253     Toolkit::StyleManager styleManager = Toolkit::StyleManager::Get();
1254     if( styleManager )
1255     {
1256       const StylePtr stylePtr = GetImpl( styleManager ).GetRecordedStyle( Toolkit::Control( mControlImpl.GetOwner() ) );
1257
1258       if( stylePtr )
1259       {
1260         std::string oldStateName = Scripting::GetEnumerationName< Toolkit::DevelControl::State >( oldState, ControlStateTable, ControlStateTableCount );
1261         std::string newStateName = Scripting::GetEnumerationName< Toolkit::DevelControl::State >( newState, ControlStateTable, ControlStateTableCount );
1262
1263         const StylePtr* newStateStyle = stylePtr->subStates.Find( newStateName );
1264         const StylePtr* oldStateStyle = stylePtr->subStates.Find( oldStateName );
1265         if( oldStateStyle && newStateStyle )
1266         {
1267           // Only change if both state styles exist
1268           ReplaceStateVisualsAndProperties( *oldStateStyle, *newStateStyle, mSubStateName );
1269         }
1270       }
1271     }
1272   }
1273 }
1274
1275 void Control::Impl::SetSubState( const std::string& subStateName, bool withTransitions )
1276 {
1277   if( mSubStateName != subStateName )
1278   {
1279     // Get existing sub-state visuals, and unregister them
1280     Dali::CustomActor handle( mControlImpl.GetOwner() );
1281
1282     Toolkit::StyleManager styleManager = Toolkit::StyleManager::Get();
1283     if( styleManager )
1284     {
1285       const StylePtr stylePtr = GetImpl( styleManager ).GetRecordedStyle( Toolkit::Control( mControlImpl.GetOwner() ) );
1286       if( stylePtr )
1287       {
1288         // Stringify state
1289         std::string stateName = Scripting::GetEnumerationName< Toolkit::DevelControl::State >( mState, ControlStateTable, ControlStateTableCount );
1290
1291         const StylePtr* state = stylePtr->subStates.Find( stateName );
1292         if( state )
1293         {
1294           StylePtr stateStyle(*state);
1295
1296           const StylePtr* newStateStyle = stateStyle->subStates.Find( subStateName );
1297           const StylePtr* oldStateStyle = stateStyle->subStates.Find( mSubStateName );
1298           if( oldStateStyle && newStateStyle )
1299           {
1300             std::string empty;
1301             ReplaceStateVisualsAndProperties( *oldStateStyle, *newStateStyle, empty );
1302           }
1303         }
1304       }
1305     }
1306
1307     mSubStateName = subStateName;
1308   }
1309 }
1310
1311 void Control::Impl::OnStageDisconnection()
1312 {
1313   Actor self = mControlImpl.Self();
1314
1315   // Any visuals set for replacement but not yet ready should still be registered.
1316   // Reason: If a request was made to register a new visual but the control removed from stage before visual was ready
1317   // then when this control appears back on stage it should use that new visual.
1318
1319   // Iterate through all registered visuals and set off stage
1320   SetVisualsOffStage( mVisuals, self );
1321
1322   // Visuals pending replacement can now be taken out of the removal list and set off stage
1323   // Iterate through all replacement visuals and add to a move queue then set off stage
1324   for( auto removalIter = mRemoveVisuals.Begin(), end = mRemoveVisuals.End(); removalIter != end; removalIter++ )
1325   {
1326     Toolkit::GetImplementation((*removalIter)->visual).SetOffStage( self );
1327   }
1328
1329   for( auto replacedIter = mVisuals.Begin(), end = mVisuals.End(); replacedIter != end; replacedIter++ )
1330   {
1331     (*replacedIter)->pending = false;
1332   }
1333
1334   mRemoveVisuals.Clear();
1335 }
1336
1337 void Control::Impl::SetMargin( Extents margin )
1338 {
1339   mControlImpl.mImpl->mMargin = margin;
1340 }
1341
1342 Extents Control::Impl::GetMargin() const
1343 {
1344   return mControlImpl.mImpl->mMargin;
1345 }
1346
1347 void Control::Impl::SetPadding( Extents padding )
1348 {
1349   mControlImpl.mImpl->mPadding = padding;
1350 }
1351
1352 Extents Control::Impl::GetPadding() const
1353 {
1354   return mControlImpl.mImpl->mPadding;
1355 }
1356
1357 } // namespace Internal
1358
1359 } // namespace Toolkit
1360
1361 } // namespace Dali