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