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