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