Visual replacements logic updated
[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/devel-api/visuals/visual-properties-devel.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::DevelVisual::Type GetVisualTypeFromMap( const Property::Map& map )
89 {
90   Property::Value* typeValue = map.Find( Toolkit::DevelVisual::Property::TYPE, VISUAL_TYPE  );
91   Toolkit::DevelVisual::Type type = Toolkit::DevelVisual::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, "tooltip",                Toolkit::DevelControl::Property::TOOLTIP,                 Property::MAP,     &Control::Impl::SetProperty, &Control::Impl::GetProperty );
306 const PropertyRegistration Control::Impl::PROPERTY_7( typeRegistration, "state",                  Toolkit::DevelControl::Property::STATE,                   Property::STRING,  &Control::Impl::SetProperty, &Control::Impl::GetProperty );
307 const PropertyRegistration Control::Impl::PROPERTY_8( typeRegistration, "subState",               Toolkit::DevelControl::Property::SUB_STATE,               Property::STRING,  &Control::Impl::SetProperty, &Control::Impl::GetProperty );
308 const PropertyRegistration Control::Impl::PROPERTY_9( typeRegistration, "leftFocusableActorId",   Toolkit::DevelControl::Property::LEFT_FOCUSABLE_ACTOR_ID, Property::INTEGER, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
309 const PropertyRegistration Control::Impl::PROPERTY_10( typeRegistration, "rightFocusableActorId", Toolkit::DevelControl::Property::RIGHT_FOCUSABLE_ACTOR_ID,Property::INTEGER, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
310 const PropertyRegistration Control::Impl::PROPERTY_11( typeRegistration, "upFocusableActorId",    Toolkit::DevelControl::Property::UP_FOCUSABLE_ACTOR_ID,   Property::INTEGER, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
311 const PropertyRegistration Control::Impl::PROPERTY_12( typeRegistration, "downFocusableActorId",  Toolkit::DevelControl::Property::DOWN_FOCUSABLE_ACTOR_ID, Property::INTEGER, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
312
313
314
315 Control::Impl::Impl( Control& controlImpl )
316 : mControlImpl( controlImpl ),
317   mState( Toolkit::DevelControl::NORMAL ),
318   mSubStateName(""),
319   mLeftFocusableActorId( -1 ),
320   mRightFocusableActorId( -1 ),
321   mUpFocusableActorId( -1 ),
322   mDownFocusableActorId( -1 ),
323   mStyleName(""),
324   mBackgroundColor(Color::TRANSPARENT),
325   mStartingPinchScale( NULL ),
326   mKeyEventSignal(),
327   mPinchGestureDetector(),
328   mPanGestureDetector(),
329   mTapGestureDetector(),
330   mLongPressGestureDetector(),
331   mFlags( Control::ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ),
332   mIsKeyboardNavigationSupported( false ),
333   mIsKeyboardFocusGroup( false )
334 {
335
336 }
337
338 Control::Impl::~Impl()
339 {
340   // All gesture detectors will be destroyed so no need to disconnect.
341   delete mStartingPinchScale;
342 }
343
344 Control::Impl& Control::Impl::Get( Internal::Control& internalControl )
345 {
346   return *internalControl.mImpl;
347 }
348
349 const Control::Impl& Control::Impl::Get( const Internal::Control& internalControl )
350 {
351   return *internalControl.mImpl;
352 }
353
354 // Gesture Detection Methods
355 void Control::Impl::PinchDetected(Actor actor, const PinchGesture& pinch)
356 {
357   mControlImpl.OnPinch(pinch);
358 }
359
360 void Control::Impl::PanDetected(Actor actor, const PanGesture& pan)
361 {
362   mControlImpl.OnPan(pan);
363 }
364
365 void Control::Impl::TapDetected(Actor actor, const TapGesture& tap)
366 {
367   mControlImpl.OnTap(tap);
368 }
369
370 void Control::Impl::LongPressDetected(Actor actor, const LongPressGesture& longPress)
371 {
372   mControlImpl.OnLongPress(longPress);
373 }
374
375 void Control::Impl::RegisterVisual( Property::Index index, Toolkit::Visual::Base& visual )
376 {
377   RegisterVisual( index, visual, VisualState::ENABLED, DepthIndexValue::NOT_SET );
378 }
379
380 void Control::Impl::RegisterVisual( Property::Index index, Toolkit::Visual::Base& visual, int depthIndex )
381 {
382   RegisterVisual( index, visual, VisualState::ENABLED, DepthIndexValue::SET, depthIndex );
383 }
384
385 void Control::Impl::RegisterVisual( Property::Index index, Toolkit::Visual::Base& visual, bool enabled )
386 {
387   RegisterVisual( index, visual, ( enabled ? VisualState::ENABLED : VisualState::DISABLED ), DepthIndexValue::NOT_SET );
388 }
389
390 void Control::Impl::RegisterVisual( Property::Index index, Toolkit::Visual::Base& visual, bool enabled, int depthIndex )
391 {
392   RegisterVisual( index, visual, ( enabled ? VisualState::ENABLED : VisualState::DISABLED ), DepthIndexValue::SET, depthIndex );
393 }
394
395 void Control::Impl::RegisterVisual( Property::Index index, Toolkit::Visual::Base& visual, VisualState::Type enabled, DepthIndexValue::Type depthIndexValueSet, int depthIndex )
396 {
397   DALI_LOG_INFO( gLogFilter, Debug::Concise, "RegisterVisual:%d \n", index );
398
399   bool visualReplaced ( false );
400   Actor self = mControlImpl.Self();
401
402   // Set the depth index, if not set by caller this will be either the current visual depth, max depth of all visuals
403   // or zero.
404   int requiredDepthIndex = visual.GetDepthIndex();
405
406   if( depthIndexValueSet == DepthIndexValue::SET )
407   {
408     requiredDepthIndex = depthIndex;
409   }
410
411   // Visual replacement, existing visual should only be removed from stage when replacement ready.
412   if( !mVisuals.Empty() )
413   {
414     RegisteredVisualContainer::Iterator registeredVisualsiter;
415     // Check if visual (index) is already registered, this is the current visual.
416     if( FindVisual( index, mVisuals, registeredVisualsiter ) )
417     {
418       Toolkit::Visual::Base& currentRegisteredVisual = (*registeredVisualsiter)->visual;
419       if( currentRegisteredVisual )
420       {
421         // Store current visual depth index as may need to set the replacement visual to same depth
422         const int currentDepthIndex = (*registeredVisualsiter)->visual.GetDepthIndex();
423
424         // No longer required to know if the replaced visual's resources are ready
425         StopObservingVisual( currentRegisteredVisual );
426
427         // If control staged and visual enabled then visuals will be swapped once ready
428         if(  self.OnStage() && enabled )
429         {
430           // Check if visual is currently in the process of being replaced ( is in removal container )
431           RegisteredVisualContainer::Iterator visualQueuedForRemoval;
432           if ( FindVisual( index, mRemoveVisuals, visualQueuedForRemoval ) )
433           {
434             // Visual with same index is already in removal container so current visual pending
435             // Only the the last requested visual will be displayed so remove current visual which is staged but not ready.
436             Toolkit::GetImplementation( currentRegisteredVisual ).SetOffStage( self );
437             mVisuals.Erase( registeredVisualsiter );
438           }
439           else
440           {
441             // current visual not already in removal container so add now.
442             DALI_LOG_INFO( gLogFilter, Debug::Verbose, "RegisterVisual Move current registered visual to removal Queue: %d \n", index );
443             MoveVisual( registeredVisualsiter, mVisuals, mRemoveVisuals );
444           }
445         }
446         else
447         {
448           // Control not staged or visual disabled so can just erase from registered visuals and new visual will be added later.
449           mVisuals.Erase( registeredVisualsiter );
450         }
451
452         // 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
453         if( ( depthIndexValueSet == DepthIndexValue::NOT_SET ) &&
454             ( visual.GetDepthIndex() == 0 ) )
455         {
456           requiredDepthIndex = currentDepthIndex;
457         }
458       }
459
460       visualReplaced = true;
461     }
462   }
463
464   // If not set, set the name of the visual to the same name as the control's property.
465   // ( If the control has been type registered )
466   if( visual.GetName().empty() )
467   {
468     try
469     {
470       std::string visualName = self.GetPropertyName( index );
471       if( !visualName.empty() )
472       {
473         DALI_LOG_INFO( gLogFilter, Debug::Concise, "Setting visual name for property %d to %s\n",
474                        index, visualName.c_str() );
475         visual.SetName( visualName );
476       }
477     }
478     catch( Dali::DaliException e )
479     {
480       DALI_LOG_WARNING( "Attempting to register visual without a registered property, index: %d\n", index );
481     }
482   }
483
484   if( !visualReplaced ) // New registration entry
485   {
486     // monitor when the visual resources are ready
487     StartObservingVisual( visual );
488
489     // 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
490     if( ( depthIndexValueSet == DepthIndexValue::NOT_SET ) &&
491         ( mVisuals.Size() > 0 ) &&
492         ( visual.GetDepthIndex() == 0 ) )
493     {
494       int maxDepthIndex = std::numeric_limits< int >::min();
495
496       RegisteredVisualContainer::ConstIterator iter;
497       const RegisteredVisualContainer::ConstIterator endIter = mVisuals.End();
498       for ( iter = mVisuals.Begin(); iter != endIter; iter++ )
499       {
500         const int visualDepthIndex = (*iter)->visual.GetDepthIndex();
501         if ( visualDepthIndex > maxDepthIndex )
502         {
503           maxDepthIndex = visualDepthIndex;
504         }
505       }
506       ++maxDepthIndex; // Add one to the current maximum depth index so that our added visual appears on top
507       requiredDepthIndex = std::max( 0, maxDepthIndex ); // Start at zero if maxDepth index belongs to a background
508     }
509   }
510
511   if( visual )
512   {
513     // Set determined depth index
514     visual.SetDepthIndex( requiredDepthIndex );
515
516     // Monitor when the visual resources are ready
517     StartObservingVisual( visual );
518
519     DALI_LOG_INFO( gLogFilter, Debug::Concise, "New Visual registration index[%d] depth[%d]\n", index, requiredDepthIndex );
520     RegisteredVisual* newRegisteredVisual  = new RegisteredVisual( index, visual,
521                                              ( enabled == VisualState::ENABLED ? true : false ),
522                                              ( visualReplaced && enabled ) ) ;
523     mVisuals.PushBack( newRegisteredVisual );
524
525     // Put on stage if enabled and the control is already on the stage
526     // Visual must be set on stage for the renderer to be created and the ResourceReady triggered.
527     if( ( enabled == VisualState::ENABLED ) && self.OnStage() )
528     {
529       Toolkit::GetImplementation(visual).SetOnStage( self );
530     }
531   }
532
533   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::RegisterVisual() Registered %s(%d), enabled:%s\n",  visual.GetName().c_str(), index, enabled?"true":"false" );
534 }
535
536 void Control::Impl::UnregisterVisual( Property::Index index )
537 {
538    RegisteredVisualContainer::Iterator iter;
539    if ( FindVisual( index, mVisuals, iter ) )
540    {
541      // stop observing visual
542      StopObservingVisual( (*iter)->visual );
543
544      Actor self( mControlImpl.Self() );
545      Toolkit::GetImplementation((*iter)->visual).SetOffStage( self );
546      (*iter)->visual.Reset();
547      mVisuals.Erase( iter );
548    }
549 }
550
551 Toolkit::Visual::Base Control::Impl::GetVisual( Property::Index index ) const
552 {
553   RegisteredVisualContainer::Iterator iter;
554   if ( FindVisual( index, mVisuals, iter ) )
555   {
556     return (*iter)->visual;
557   }
558
559   return Toolkit::Visual::Base();
560 }
561
562 void Control::Impl::EnableVisual( Property::Index index, bool enable )
563 {
564   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::EnableVisual Visual (%d)\n", index);
565
566   RegisteredVisualContainer::Iterator iter;
567   if ( FindVisual( index, mVisuals, iter ) )
568   {
569     if (  (*iter)->enabled == enable )
570     {
571       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::EnableVisual Visual %s(%d) already %s\n", (*iter)->visual.GetName().c_str(), index, enable?"enabled":"disabled");
572       return;
573     }
574
575     (*iter)->enabled = enable;
576     Actor parentActor = mControlImpl.Self();
577     if ( mControlImpl.Self().OnStage() ) // If control not on Stage then Visual will be added when StageConnection is called.
578     {
579       if ( enable )
580       {
581         DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::EnableVisual Setting %s(%d) on stage \n", (*iter)->visual.GetName().c_str(), index );
582         Toolkit::GetImplementation((*iter)->visual).SetOnStage( parentActor );
583       }
584       else
585       {
586         DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::EnableVisual Setting %s(%d) off stage \n", (*iter)->visual.GetName().c_str(), index );
587         Toolkit::GetImplementation((*iter)->visual).SetOffStage( parentActor );  // No need to call if control not staged.
588       }
589     }
590   }
591 }
592
593 bool Control::Impl::IsVisualEnabled( Property::Index index ) const
594 {
595   RegisteredVisualContainer::Iterator iter;
596   if ( FindVisual( index, mVisuals, iter ) )
597   {
598     return (*iter)->enabled;
599   }
600   return false;
601 }
602
603 void Control::Impl::StopObservingVisual( Toolkit::Visual::Base& visual )
604 {
605   Internal::Visual::Base& visualImpl = Toolkit::GetImplementation( visual );
606
607   // Stop observing the visual
608   visualImpl.RemoveResourceObserver( *this );
609 }
610
611 void Control::Impl::StartObservingVisual( Toolkit::Visual::Base& visual)
612 {
613   Internal::Visual::Base& visualImpl = Toolkit::GetImplementation( visual );
614
615   // start observing the visual for resource ready
616   visualImpl.AddResourceObserver( *this );
617 }
618
619 // Called by a Visual when it's resource is ready
620 void Control::Impl::ResourceReady( Visual::Base& object)
621 {
622   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "ResourceReady replacements pending[%d]\n", mRemoveVisuals.Count() );
623
624   Actor self = mControlImpl.Self();
625
626   // A resource is ready, find resource in the registered visuals container and get its index
627   for( auto registeredIter = mVisuals.Begin(),  end = mVisuals.End(); registeredIter != end; ++registeredIter )
628   {
629     Internal::Visual::Base& registeredVisualImpl = Toolkit::GetImplementation( (*registeredIter)->visual );
630
631     if( &object == &registeredVisualImpl )
632     {
633       RegisteredVisualContainer::Iterator visualToRemoveIter;
634       // Find visual with the same index in the removal container
635       // Set if off stage as it's replacement is now ready.
636       // Remove if from removal list as now removed from stage.
637       // Set Pending flag on the ready visual to false as now ready.
638       if( FindVisual( (*registeredIter)->index, mRemoveVisuals, visualToRemoveIter ) )
639       {
640         (*registeredIter)->pending = false;
641         Toolkit::GetImplementation( (*visualToRemoveIter)->visual ).SetOffStage( self );
642         mRemoveVisuals.Erase( visualToRemoveIter );
643       }
644       break;
645     }
646   }
647
648   // A visual is ready so control may need relayouting
649   mControlImpl.RelayoutRequest();
650
651   // Emit signal if all enabled visuals registered by the control are ready.
652   if( IsResourceReady() )
653   {
654     Dali::Toolkit::Control handle( mControlImpl.GetOwner() );
655     mResourceReadySignal.Emit( handle );
656   }
657 }
658
659 bool Control::Impl::IsResourceReady() const
660 {
661   // Iterate through and check all the enabled visuals are ready
662   for( auto visualIter = mVisuals.Begin();
663          visualIter != mVisuals.End(); ++visualIter )
664   {
665     const Toolkit::Visual::Base visual = (*visualIter)->visual;
666     const Internal::Visual::Base& visualImpl = Toolkit::GetImplementation( visual );
667
668     // one of the enabled visuals is not ready
669     if( !visualImpl.IsResourceReady() && (*visualIter)->enabled )
670     {
671       return false;
672     }
673   }
674   return true;
675 }
676
677
678 Dali::Animation Control::Impl::CreateTransition( const Toolkit::TransitionData& handle )
679 {
680   Dali::Animation transition;
681   const Internal::TransitionData& transitionData = Toolkit::GetImplementation( handle );
682
683   if( transitionData.Count() > 0 )
684   {
685     // Setup a Transition from TransitionData.
686     TransitionData::Iterator end = transitionData.End();
687     for( TransitionData::Iterator iter = transitionData.Begin() ;
688          iter != end; ++iter )
689     {
690       TransitionData::Animator* animator = (*iter);
691
692       Toolkit::Visual::Base visual = GetVisualByName( mVisuals, animator->objectName );
693
694       if( visual )
695       {
696 #if defined(DEBUG_ENABLED)
697         Dali::TypeInfo typeInfo;
698         ControlWrapper* controlWrapperImpl = dynamic_cast<ControlWrapper*>(&mControlImpl);
699         if( controlWrapperImpl )
700         {
701           typeInfo = controlWrapperImpl->GetTypeInfo();
702         }
703
704         DALI_LOG_INFO( gLogFilter, Debug::Concise, "CreateTransition: Found %s visual for %s\n",
705                        visual.GetName().c_str(), typeInfo?typeInfo.GetName().c_str():"Unknown" );
706 #endif
707         Internal::Visual::Base& visualImpl = Toolkit::GetImplementation( visual );
708         visualImpl.AnimateProperty( transition, *animator );
709       }
710       else
711       {
712         DALI_LOG_INFO( gLogFilter, Debug::Concise, "CreateTransition: Could not find visual. Trying actors");
713         // Otherwise, try any actor children of control (Including the control)
714         Actor child = mControlImpl.Self().FindChildByName( animator->objectName );
715         if( child )
716         {
717           Property::Index propertyIndex = DevelHandle::GetPropertyIndex( child, animator->propertyKey );
718           if( propertyIndex != Property::INVALID_INDEX )
719           {
720             if( animator->animate == false )
721             {
722               if( animator->targetValue.GetType() != Property::NONE )
723               {
724                 child.SetProperty( propertyIndex, animator->targetValue );
725               }
726             }
727             else // animate the property
728             {
729               if( animator->initialValue.GetType() != Property::NONE )
730               {
731                 child.SetProperty( propertyIndex, animator->initialValue );
732               }
733
734               if( ! transition )
735               {
736                 transition = Dali::Animation::New( 0.1f );
737               }
738
739               transition.AnimateTo( Property( child, propertyIndex ),
740                                     animator->targetValue,
741                                     animator->alphaFunction,
742                                     TimePeriod( animator->timePeriodDelay,
743                                                 animator->timePeriodDuration ) );
744             }
745           }
746         }
747       }
748     }
749   }
750
751   return transition;
752 }
753
754 void Control::Impl::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
755 {
756   Toolkit::Control control = Toolkit::Control::DownCast( BaseHandle( object ) );
757
758   if ( control )
759   {
760     Control& controlImpl( GetImplementation( control ) );
761
762     switch ( index )
763     {
764       case Toolkit::Control::Property::STYLE_NAME:
765       {
766         controlImpl.SetStyleName( value.Get< std::string >() );
767         break;
768       }
769
770       case Toolkit::DevelControl::Property::STATE:
771       {
772         bool withTransitions=true;
773         const Property::Value* valuePtr=&value;
774         Property::Map* map = value.GetMap();
775         if(map)
776         {
777           Property::Value* value2 = map->Find("withTransitions");
778           if( value2 )
779           {
780             withTransitions = value2->Get<bool>();
781           }
782
783           valuePtr = map->Find("state");
784         }
785
786         if( valuePtr )
787         {
788           Toolkit::DevelControl::State state( controlImpl.mImpl->mState );
789           if( Scripting::GetEnumerationProperty< Toolkit::DevelControl::State >( *valuePtr, ControlStateTable, ControlStateTableCount, state ) )
790           {
791             controlImpl.mImpl->SetState( state, withTransitions );
792           }
793         }
794       }
795       break;
796
797       case Toolkit::DevelControl::Property::SUB_STATE:
798       {
799         std::string subState;
800         if( value.Get( subState ) )
801         {
802           controlImpl.mImpl->SetSubState( subState );
803         }
804       }
805       break;
806
807       case Toolkit::DevelControl::Property::LEFT_FOCUSABLE_ACTOR_ID:
808       {
809         int focusId;
810         if( value.Get( focusId ) )
811         {
812           controlImpl.mImpl->mLeftFocusableActorId = focusId;
813         }
814       }
815       break;
816
817       case Toolkit::DevelControl::Property::RIGHT_FOCUSABLE_ACTOR_ID:
818       {
819         int focusId;
820         if( value.Get( focusId ) )
821         {
822           controlImpl.mImpl->mRightFocusableActorId = focusId;
823         }
824       }
825       break;
826
827       case Toolkit::DevelControl::Property::UP_FOCUSABLE_ACTOR_ID:
828       {
829         int focusId;
830         if( value.Get( focusId ) )
831         {
832           controlImpl.mImpl->mUpFocusableActorId = focusId;
833         }
834       }
835       break;
836
837       case Toolkit::DevelControl::Property::DOWN_FOCUSABLE_ACTOR_ID:
838       {
839         int focusId;
840         if( value.Get( focusId ) )
841         {
842           controlImpl.mImpl->mDownFocusableActorId = focusId;
843         }
844       }
845       break;
846
847       case Toolkit::Control::Property::BACKGROUND_COLOR:
848       {
849         DALI_LOG_WARNING( "BACKGROUND_COLOR property is deprecated. Use BACKGROUND property instead\n" );
850         controlImpl.SetBackgroundColor( value.Get< Vector4 >() );
851         break;
852       }
853
854       case Toolkit::Control::Property::BACKGROUND_IMAGE:
855       {
856         DALI_LOG_WARNING( "BACKGROUND_IMAGE property is deprecated. Use BACKGROUND property instead\n" );
857         Image image = Scripting::NewImage( value );
858         if ( image )
859         {
860           controlImpl.SetBackgroundImage( image );
861         }
862         else
863         {
864           // An empty image means the background is no longer required
865           controlImpl.ClearBackground();
866         }
867         break;
868       }
869
870       case Toolkit::Control::Property::KEY_INPUT_FOCUS:
871       {
872         if ( value.Get< bool >() )
873         {
874           controlImpl.SetKeyInputFocus();
875         }
876         else
877         {
878           controlImpl.ClearKeyInputFocus();
879         }
880         break;
881       }
882
883       case Toolkit::Control::Property::BACKGROUND:
884       {
885         std::string url;
886         Vector4 color;
887         const Property::Map* map = value.GetMap();
888         if( map && !map->Empty() )
889         {
890           controlImpl.SetBackground( *map );
891         }
892         else if( value.Get( url ) )
893         {
894           // don't know the size to load
895           Toolkit::Visual::Base visual = Toolkit::VisualFactory::Get().CreateVisual( url, ImageDimensions() );
896           if( visual )
897           {
898             controlImpl.mImpl->RegisterVisual( Toolkit::Control::Property::BACKGROUND, visual, DepthIndex::BACKGROUND );
899           }
900         }
901         else if( value.Get( color ) )
902         {
903           controlImpl.SetBackgroundColor(color);
904         }
905         else
906         {
907           // The background is an empty property map, so we should clear the background
908           controlImpl.ClearBackground();
909         }
910         break;
911       }
912
913       case Toolkit::DevelControl::Property::TOOLTIP:
914       {
915         TooltipPtr& tooltipPtr = controlImpl.mImpl->mTooltip;
916         if( ! tooltipPtr )
917         {
918           tooltipPtr = Tooltip::New( control );
919         }
920         tooltipPtr->SetProperties( value );
921       }
922     }
923   }
924 }
925
926 Property::Value Control::Impl::GetProperty( BaseObject* object, Property::Index index )
927 {
928   Property::Value value;
929
930   Toolkit::Control control = Toolkit::Control::DownCast( BaseHandle( object ) );
931
932   if ( control )
933   {
934     Control& controlImpl( GetImplementation( control ) );
935
936     switch ( index )
937     {
938       case Toolkit::Control::Property::STYLE_NAME:
939       {
940         value = controlImpl.GetStyleName();
941         break;
942       }
943
944       case Toolkit::DevelControl::Property::STATE:
945       {
946         value = controlImpl.mImpl->mState;
947         break;
948       }
949
950       case Toolkit::DevelControl::Property::SUB_STATE:
951       {
952         value = controlImpl.mImpl->mSubStateName;
953         break;
954       }
955
956       case Toolkit::DevelControl::Property::LEFT_FOCUSABLE_ACTOR_ID:
957       {
958         value = controlImpl.mImpl->mLeftFocusableActorId;
959         break;
960       }
961
962       case Toolkit::DevelControl::Property::RIGHT_FOCUSABLE_ACTOR_ID:
963       {
964         value = controlImpl.mImpl->mRightFocusableActorId;
965         break;
966       }
967
968       case Toolkit::DevelControl::Property::UP_FOCUSABLE_ACTOR_ID:
969       {
970         value = controlImpl.mImpl->mUpFocusableActorId;
971         break;
972       }
973
974       case Toolkit::DevelControl::Property::DOWN_FOCUSABLE_ACTOR_ID:
975       {
976         value = controlImpl.mImpl->mDownFocusableActorId;
977         break;
978       }
979
980       case Toolkit::Control::Property::BACKGROUND_COLOR:
981       {
982         DALI_LOG_WARNING( "BACKGROUND_COLOR property is deprecated. Use BACKGROUND property instead\n" );
983         value = controlImpl.GetBackgroundColor();
984         break;
985       }
986
987       case Toolkit::Control::Property::BACKGROUND_IMAGE:
988       {
989         DALI_LOG_WARNING( "BACKGROUND_IMAGE property is deprecated. Use BACKGROUND property instead\n" );
990         Property::Map map;
991         Toolkit::Visual::Base visual = controlImpl.mImpl->GetVisual( Toolkit::Control::Property::BACKGROUND );
992         if( visual )
993         {
994           visual.CreatePropertyMap( map );
995         }
996         value = map;
997         break;
998       }
999
1000       case Toolkit::Control::Property::KEY_INPUT_FOCUS:
1001       {
1002         value = controlImpl.HasKeyInputFocus();
1003         break;
1004       }
1005
1006       case Toolkit::Control::Property::BACKGROUND:
1007       {
1008         Property::Map map;
1009         Toolkit::Visual::Base visual = controlImpl.mImpl->GetVisual( Toolkit::Control::Property::BACKGROUND );
1010         if( visual )
1011         {
1012           visual.CreatePropertyMap( map );
1013         }
1014
1015         value = map;
1016         break;
1017       }
1018
1019       case Toolkit::DevelControl::Property::TOOLTIP:
1020       {
1021         Property::Map map;
1022         if( controlImpl.mImpl->mTooltip )
1023         {
1024           controlImpl.mImpl->mTooltip->CreatePropertyMap( map );
1025         }
1026         value = map;
1027         break;
1028       }
1029
1030     }
1031   }
1032
1033   return value;
1034 }
1035
1036
1037 void  Control::Impl::CopyInstancedProperties( RegisteredVisualContainer& visuals, Dictionary<Property::Map>& instancedProperties )
1038 {
1039   for(RegisteredVisualContainer::Iterator iter = visuals.Begin(); iter!= visuals.End(); iter++)
1040   {
1041     if( (*iter)->visual )
1042     {
1043       Property::Map instanceMap;
1044       Toolkit::GetImplementation((*iter)->visual).CreateInstancePropertyMap(instanceMap);
1045       instancedProperties.Add( (*iter)->visual.GetName(), instanceMap );
1046     }
1047   }
1048 }
1049
1050
1051 void Control::Impl::RemoveVisual( RegisteredVisualContainer& visuals, const std::string& visualName )
1052 {
1053   Actor self( mControlImpl.Self() );
1054
1055   for ( RegisteredVisualContainer::Iterator visualIter = visuals.Begin();
1056         visualIter != visuals.End(); ++visualIter )
1057   {
1058     Toolkit::Visual::Base visual = (*visualIter)->visual;
1059     if( visual && visual.GetName() == visualName )
1060     {
1061       Toolkit::GetImplementation(visual).SetOffStage( self );
1062       (*visualIter)->visual.Reset();
1063       visuals.Erase( visualIter );
1064       break;
1065     }
1066   }
1067 }
1068
1069 void Control::Impl::RemoveVisuals( RegisteredVisualContainer& visuals, DictionaryKeys& removeVisuals )
1070 {
1071   Actor self( mControlImpl.Self() );
1072   for( DictionaryKeys::iterator iter = removeVisuals.begin(); iter != removeVisuals.end(); ++iter )
1073   {
1074     const std::string visualName = *iter;
1075     RemoveVisual( visuals, visualName );
1076   }
1077 }
1078
1079 void Control::Impl::RecreateChangedVisuals( Dictionary<Property::Map>& stateVisualsToChange,
1080                              Dictionary<Property::Map>& instancedProperties )
1081 {
1082   Dali::CustomActor handle( mControlImpl.GetOwner() );
1083   for( Dictionary<Property::Map>::iterator iter = stateVisualsToChange.Begin();
1084        iter != stateVisualsToChange.End(); ++iter )
1085   {
1086     const std::string& visualName = (*iter).key;
1087     const Property::Map& toMap = (*iter).entry;
1088
1089     // is it a candidate for re-creation?
1090     bool recreate = false;
1091
1092     Toolkit::Visual::Base visual = GetVisualByName( mVisuals, visualName );
1093     if( visual )
1094     {
1095       Property::Map fromMap;
1096       visual.CreatePropertyMap( fromMap );
1097
1098       Toolkit::DevelVisual::Type fromType = GetVisualTypeFromMap( fromMap );
1099       Toolkit::DevelVisual::Type toType = GetVisualTypeFromMap( toMap );
1100
1101       if( fromType != toType )
1102       {
1103         recreate = true;
1104       }
1105       else
1106       {
1107         if( fromType == Toolkit::DevelVisual::IMAGE || fromType == Toolkit::DevelVisual::N_PATCH
1108             || fromType == Toolkit::DevelVisual::SVG || fromType == Toolkit::DevelVisual::ANIMATED_IMAGE )
1109         {
1110           Property::Value* fromUrl = fromMap.Find( Toolkit::ImageVisual::Property::URL, IMAGE_URL_NAME );
1111           Property::Value* toUrl = toMap.Find( Toolkit::ImageVisual::Property::URL, IMAGE_URL_NAME );
1112
1113           if( fromUrl && toUrl )
1114           {
1115             std::string fromUrlString;
1116             std::string toUrlString;
1117             fromUrl->Get(fromUrlString);
1118             toUrl->Get(toUrlString);
1119
1120             if( fromUrlString != toUrlString )
1121             {
1122               recreate = true;
1123             }
1124           }
1125         }
1126       }
1127
1128       const Property::Map* instancedMap = instancedProperties.FindConst( visualName );
1129       if( recreate || instancedMap )
1130       {
1131         RemoveVisual( mVisuals, visualName );
1132         Style::ApplyVisual( handle, visualName, toMap, instancedMap );
1133       }
1134       else
1135       {
1136         // @todo check to see if we can apply toMap without recreating the visual
1137         // e.g. by setting only animatable properties
1138         // For now, recreate all visuals, but merge in instance data.
1139         RemoveVisual( mVisuals, visualName );
1140         Style::ApplyVisual( handle, visualName, toMap, instancedMap );
1141       }
1142     }
1143   }
1144 }
1145
1146 void Control::Impl::ReplaceStateVisualsAndProperties( const StylePtr oldState, const StylePtr newState, const std::string& subState )
1147 {
1148   // Collect all old visual names
1149   DictionaryKeys stateVisualsToRemove;
1150   if( oldState )
1151   {
1152     oldState->visuals.GetKeys( stateVisualsToRemove );
1153     if( ! subState.empty() )
1154     {
1155       const StylePtr* oldSubState = oldState->subStates.FindConst(subState);
1156       if( oldSubState )
1157       {
1158         DictionaryKeys subStateVisualsToRemove;
1159         (*oldSubState)->visuals.GetKeys( subStateVisualsToRemove );
1160         Merge( stateVisualsToRemove, subStateVisualsToRemove );
1161       }
1162     }
1163   }
1164
1165   // Collect all new visual properties
1166   Dictionary<Property::Map> stateVisualsToAdd;
1167   if( newState )
1168   {
1169     stateVisualsToAdd = newState->visuals;
1170     if( ! subState.empty() )
1171     {
1172       const StylePtr* newSubState = newState->subStates.FindConst(subState);
1173       if( newSubState )
1174       {
1175         stateVisualsToAdd.Merge( (*newSubState)->visuals );
1176       }
1177     }
1178   }
1179
1180   // If a name is in both add/remove, move it to change list.
1181   Dictionary<Property::Map> stateVisualsToChange;
1182   FindChangableVisuals( stateVisualsToAdd, stateVisualsToChange, stateVisualsToRemove);
1183
1184   // Copy instanced properties (e.g. text label) of current visuals
1185   Dictionary<Property::Map> instancedProperties;
1186   CopyInstancedProperties( mVisuals, instancedProperties );
1187
1188   // For each visual in remove list, remove from mVisuals
1189   RemoveVisuals( mVisuals, stateVisualsToRemove );
1190
1191   // For each visual in add list, create and add to mVisuals
1192   Dali::CustomActor handle( mControlImpl.GetOwner() );
1193   Style::ApplyVisuals( handle, stateVisualsToAdd, instancedProperties );
1194
1195   // For each visual in change list, if it requires a new visual,
1196   // remove old visual, create and add to mVisuals
1197   RecreateChangedVisuals( stateVisualsToChange, instancedProperties );
1198 }
1199
1200 void Control::Impl::SetState( DevelControl::State newState, bool withTransitions )
1201 {
1202   DevelControl::State oldState = mState;
1203   Dali::CustomActor handle( mControlImpl.GetOwner() );
1204   DALI_LOG_INFO(gLogFilter, Debug::Concise, "Control::Impl::SetState: %s\n",
1205                 (mState == DevelControl::NORMAL ? "NORMAL" :(
1206                   mState == DevelControl::FOCUSED ?"FOCUSED" : (
1207                     mState == DevelControl::DISABLED?"DISABLED":"NONE" ))));
1208
1209   if( mState != newState )
1210   {
1211     // If mState was Disabled, and new state is Focused, should probably
1212     // store that fact, e.g. in another property that FocusManager can access.
1213     mState = newState;
1214
1215     // Trigger state change and transitions
1216     // Apply new style, if stylemanager is available
1217     Toolkit::StyleManager styleManager = Toolkit::StyleManager::Get();
1218     if( styleManager )
1219     {
1220       const StylePtr stylePtr = GetImpl( styleManager ).GetRecordedStyle( Toolkit::Control( mControlImpl.GetOwner() ) );
1221
1222       if( stylePtr )
1223       {
1224         std::string oldStateName = Scripting::GetEnumerationName< Toolkit::DevelControl::State >( oldState, ControlStateTable, ControlStateTableCount );
1225         std::string newStateName = Scripting::GetEnumerationName< Toolkit::DevelControl::State >( newState, ControlStateTable, ControlStateTableCount );
1226
1227         const StylePtr* newStateStyle = stylePtr->subStates.Find( newStateName );
1228         const StylePtr* oldStateStyle = stylePtr->subStates.Find( oldStateName );
1229         if( oldStateStyle && newStateStyle )
1230         {
1231           // Only change if both state styles exist
1232           ReplaceStateVisualsAndProperties( *oldStateStyle, *newStateStyle, mSubStateName );
1233         }
1234       }
1235     }
1236   }
1237 }
1238
1239 void Control::Impl::SetSubState( const std::string& subStateName, bool withTransitions )
1240 {
1241   if( mSubStateName != subStateName )
1242   {
1243     // Get existing sub-state visuals, and unregister them
1244     Dali::CustomActor handle( mControlImpl.GetOwner() );
1245
1246     Toolkit::StyleManager styleManager = Toolkit::StyleManager::Get();
1247     if( styleManager )
1248     {
1249       const StylePtr stylePtr = GetImpl( styleManager ).GetRecordedStyle( Toolkit::Control( mControlImpl.GetOwner() ) );
1250       if( stylePtr )
1251       {
1252         // Stringify state
1253         std::string stateName = Scripting::GetEnumerationName< Toolkit::DevelControl::State >( mState, ControlStateTable, ControlStateTableCount );
1254
1255         const StylePtr* state = stylePtr->subStates.Find( stateName );
1256         if( state )
1257         {
1258           StylePtr stateStyle(*state);
1259
1260           const StylePtr* newStateStyle = stateStyle->subStates.Find( subStateName );
1261           const StylePtr* oldStateStyle = stateStyle->subStates.Find( mSubStateName );
1262           if( oldStateStyle && newStateStyle )
1263           {
1264             std::string empty;
1265             ReplaceStateVisualsAndProperties( *oldStateStyle, *newStateStyle, empty );
1266           }
1267         }
1268       }
1269     }
1270
1271     mSubStateName = subStateName;
1272   }
1273 }
1274
1275 void Control::Impl::OnStageDisconnection()
1276 {
1277   Actor self = mControlImpl.Self();
1278
1279   // Any visuals set for replacement but not yet ready should still be registered.
1280   // Reason: If a request was made to register a new visual but the control removed from stage before visual was ready
1281   // then when this control appears back on stage it should use that new visual.
1282
1283   // Iterate through all registered visuals and set off stage
1284   SetVisualsOffStage( mVisuals, self );
1285
1286   // Visuals pending replacement can now be taken out of the removal list and set off stage
1287   // Iterate through all replacement visuals and add to a move queue then set off stage
1288   for( auto removalIter = mRemoveVisuals.Begin(), end = mRemoveVisuals.End(); removalIter != end; removalIter++ )
1289   {
1290     Toolkit::GetImplementation((*removalIter)->visual).SetOffStage( self );
1291   }
1292
1293   for( auto replacedIter = mVisuals.Begin(), end = mVisuals.End(); replacedIter != end; replacedIter++ )
1294   {
1295     (*replacedIter)->pending = false;
1296   }
1297
1298   mRemoveVisuals.Clear();
1299 }
1300
1301 } // namespace Internal
1302
1303 } // namespace Toolkit
1304
1305 } // namespace Dali