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