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