a8387ee9c556e54516256975ced90b57b15fa275
[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     try
481     {
482       std::string visualName = self.GetPropertyName( index );
483       if( !visualName.empty() )
484       {
485         DALI_LOG_INFO( gLogFilter, Debug::Concise, "Setting visual name for property %d to %s\n",
486                        index, visualName.c_str() );
487         visual.SetName( visualName );
488       }
489     }
490     catch( Dali::DaliException e )
491     {
492       DALI_LOG_WARNING( "Attempting to register visual without a registered property, index: %d\n", index );
493     }
494   }
495
496   if( !visualReplaced ) // New registration entry
497   {
498     // 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
499     if( ( depthIndexValueSet == DepthIndexValue::NOT_SET ) &&
500         ( mVisuals.Size() > 0 ) &&
501         ( visual.GetDepthIndex() == 0 ) )
502     {
503       int maxDepthIndex = std::numeric_limits< int >::min();
504
505       RegisteredVisualContainer::ConstIterator iter;
506       const RegisteredVisualContainer::ConstIterator endIter = mVisuals.End();
507       for ( iter = mVisuals.Begin(); iter != endIter; iter++ )
508       {
509         const int visualDepthIndex = (*iter)->visual.GetDepthIndex();
510         if ( visualDepthIndex > maxDepthIndex )
511         {
512           maxDepthIndex = visualDepthIndex;
513         }
514       }
515       ++maxDepthIndex; // Add one to the current maximum depth index so that our added visual appears on top
516       requiredDepthIndex = std::max( 0, maxDepthIndex ); // Start at zero if maxDepth index belongs to a background
517     }
518   }
519
520   if( visual )
521   {
522     // Set determined depth index
523     visual.SetDepthIndex( requiredDepthIndex );
524
525     // Monitor when the visual resources are ready
526     StartObservingVisual( visual );
527
528     DALI_LOG_INFO( gLogFilter, Debug::Concise, "New Visual registration index[%d] depth[%d]\n", index, requiredDepthIndex );
529     RegisteredVisual* newRegisteredVisual  = new RegisteredVisual( index, visual,
530                                              ( enabled == VisualState::ENABLED ? true : false ),
531                                              ( visualReplaced && enabled ) ) ;
532     mVisuals.PushBack( newRegisteredVisual );
533
534     Internal::Visual::Base& visualImpl = Toolkit::GetImplementation( visual );
535     // Put on stage if enabled and the control is already on the stage
536     if( ( enabled == VisualState::ENABLED ) && self.OnStage() )
537     {
538       visualImpl.SetOnStage( self );
539     }
540     else if( visualImpl.IsResourceReady() ) // When not being staged, check if visual already 'ResourceReady' before it was Registered. ( Resource may have been loaded already )
541     {
542       ResourceReady( visualImpl );
543     }
544
545   }
546
547   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::RegisterVisual() Registered %s(%d), enabled:%s\n",  visual.GetName().c_str(), index, enabled?"true":"false" );
548 }
549
550 void Control::Impl::UnregisterVisual( Property::Index index )
551 {
552   RegisteredVisualContainer::Iterator iter;
553   if ( FindVisual( index, mVisuals, iter ) )
554   {
555     // stop observing visual
556     StopObservingVisual( (*iter)->visual );
557
558     Actor self( mControlImpl.Self() );
559     Toolkit::GetImplementation((*iter)->visual).SetOffStage( self );
560     (*iter)->visual.Reset();
561     mVisuals.Erase( iter );
562   }
563
564   if( FindVisual( index, mRemoveVisuals, iter ) )
565   {
566     Actor self( mControlImpl.Self() );
567     Toolkit::GetImplementation( (*iter)->visual ).SetOffStage( self );
568     (*iter)->pending = false;
569     (*iter)->visual.Reset();
570     mRemoveVisuals.Erase( iter );
571   }
572 }
573
574 Toolkit::Visual::Base Control::Impl::GetVisual( Property::Index index ) const
575 {
576   RegisteredVisualContainer::Iterator iter;
577   if ( FindVisual( index, mVisuals, iter ) )
578   {
579     return (*iter)->visual;
580   }
581
582   return Toolkit::Visual::Base();
583 }
584
585 void Control::Impl::EnableVisual( Property::Index index, bool enable )
586 {
587   DALI_LOG_INFO( gLogFilter, Debug::General, "Control::EnableVisual(%d, %s)\n", index, enable?"T":"F");
588
589   RegisteredVisualContainer::Iterator iter;
590   if ( FindVisual( index, mVisuals, iter ) )
591   {
592     if (  (*iter)->enabled == enable )
593     {
594       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::EnableVisual Visual %s(%d) already %s\n", (*iter)->visual.GetName().c_str(), index, enable?"enabled":"disabled");
595       return;
596     }
597
598     (*iter)->enabled = enable;
599     Actor parentActor = mControlImpl.Self();
600     if ( mControlImpl.Self().OnStage() ) // If control not on Stage then Visual will be added when StageConnection is called.
601     {
602       if ( enable )
603       {
604         DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::EnableVisual Setting %s(%d) on stage \n", (*iter)->visual.GetName().c_str(), index );
605         Toolkit::GetImplementation((*iter)->visual).SetOnStage( parentActor );
606       }
607       else
608       {
609         DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::EnableVisual Setting %s(%d) off stage \n", (*iter)->visual.GetName().c_str(), index );
610         Toolkit::GetImplementation((*iter)->visual).SetOffStage( parentActor );  // No need to call if control not staged.
611       }
612     }
613   }
614   else
615   {
616     DALI_LOG_WARNING( "Control::EnableVisual(%d, %s) FAILED - NO SUCH VISUAL\n", index, enable?"T":"F" );
617   }
618 }
619
620 bool Control::Impl::IsVisualEnabled( Property::Index index ) const
621 {
622   RegisteredVisualContainer::Iterator iter;
623   if ( FindVisual( index, mVisuals, iter ) )
624   {
625     return (*iter)->enabled;
626   }
627   return false;
628 }
629
630 void Control::Impl::StopObservingVisual( Toolkit::Visual::Base& visual )
631 {
632   Internal::Visual::Base& visualImpl = Toolkit::GetImplementation( visual );
633
634   // Stop observing the visual
635   visualImpl.RemoveResourceObserver( *this );
636 }
637
638 void Control::Impl::StartObservingVisual( Toolkit::Visual::Base& visual)
639 {
640   Internal::Visual::Base& visualImpl = Toolkit::GetImplementation( visual );
641
642   // start observing the visual for resource ready
643   visualImpl.AddResourceObserver( *this );
644 }
645
646 // Called by a Visual when it's resource is ready
647 void Control::Impl::ResourceReady( Visual::Base& object)
648 {
649   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::Impl::ResourceReady() replacements pending[%d]\n", mRemoveVisuals.Count() );
650
651   Actor self = mControlImpl.Self();
652
653   // A resource is ready, find resource in the registered visuals container and get its index
654   for( auto registeredIter = mVisuals.Begin(),  end = mVisuals.End(); registeredIter != end; ++registeredIter )
655   {
656     Internal::Visual::Base& registeredVisualImpl = Toolkit::GetImplementation( (*registeredIter)->visual );
657
658     if( &object == &registeredVisualImpl )
659     {
660       RegisteredVisualContainer::Iterator visualToRemoveIter;
661       // Find visual with the same index in the removal container
662       // Set if off stage as it's replacement is now ready.
663       // Remove if from removal list as now removed from stage.
664       // Set Pending flag on the ready visual to false as now ready.
665       if( FindVisual( (*registeredIter)->index, mRemoveVisuals, visualToRemoveIter ) )
666       {
667         (*registeredIter)->pending = false;
668         Toolkit::GetImplementation( (*visualToRemoveIter)->visual ).SetOffStage( self );
669         mRemoveVisuals.Erase( visualToRemoveIter );
670       }
671       break;
672     }
673   }
674
675   // A visual is ready so control may need relayouting if staged
676   if ( self.OnStage() )
677   {
678     mControlImpl.RelayoutRequest();
679   }
680
681   // Emit signal if all enabled visuals registered by the control are ready.
682   if( IsResourceReady() )
683   {
684     Dali::Toolkit::Control handle( mControlImpl.GetOwner() );
685     mResourceReadySignal.Emit( handle );
686   }
687 }
688
689 bool Control::Impl::IsResourceReady() const
690 {
691   // Iterate through and check all the enabled visuals are ready
692   for( auto visualIter = mVisuals.Begin();
693          visualIter != mVisuals.End(); ++visualIter )
694   {
695     const Toolkit::Visual::Base visual = (*visualIter)->visual;
696     const Internal::Visual::Base& visualImpl = Toolkit::GetImplementation( visual );
697
698     // one of the enabled visuals is not ready
699     if( !visualImpl.IsResourceReady() && (*visualIter)->enabled )
700     {
701       return false;
702     }
703   }
704   return true;
705 }
706
707 Toolkit::Visual::ResourceStatus Control::Impl::GetVisualResourceStatus( Property::Index index ) const
708 {
709   RegisteredVisualContainer::Iterator iter;
710   if ( FindVisual( index, mVisuals, iter ) )
711   {
712     const Toolkit::Visual::Base visual = (*iter)->visual;
713     const Internal::Visual::Base& visualImpl = Toolkit::GetImplementation( visual );
714     return visualImpl.GetResourceStatus( );
715   }
716
717   return Toolkit::Visual::ResourceStatus::PREPARING;
718 }
719
720
721
722 void Control::Impl::AddTransitions( Dali::Animation& animation,
723                                     const Toolkit::TransitionData& handle,
724                                     bool createAnimation )
725 {
726   // Setup a Transition from TransitionData.
727   const Internal::TransitionData& transitionData = Toolkit::GetImplementation( handle );
728   TransitionData::Iterator end = transitionData.End();
729   for( TransitionData::Iterator iter = transitionData.Begin() ;
730        iter != end; ++iter )
731   {
732     TransitionData::Animator* animator = (*iter);
733
734     Toolkit::Visual::Base visual = GetVisualByName( mVisuals, animator->objectName );
735
736     if( visual )
737     {
738 #if defined(DEBUG_ENABLED)
739       Dali::TypeInfo typeInfo;
740       ControlWrapper* controlWrapperImpl = dynamic_cast<ControlWrapper*>(&mControlImpl);
741       if( controlWrapperImpl )
742       {
743         typeInfo = controlWrapperImpl->GetTypeInfo();
744       }
745
746       DALI_LOG_INFO( gLogFilter, Debug::Concise, "CreateTransition: Found %s visual for %s\n",
747                      visual.GetName().c_str(), typeInfo?typeInfo.GetName().c_str():"Unknown" );
748 #endif
749       Internal::Visual::Base& visualImpl = Toolkit::GetImplementation( visual );
750       visualImpl.AnimateProperty( animation, *animator );
751     }
752     else
753     {
754       DALI_LOG_INFO( gLogFilter, Debug::Concise, "CreateTransition: Could not find visual. Trying actors");
755       // Otherwise, try any actor children of control (Including the control)
756       Actor child = mControlImpl.Self().FindChildByName( animator->objectName );
757       if( child )
758       {
759         Property::Index propertyIndex = DevelHandle::GetPropertyIndex( child, animator->propertyKey );
760         if( propertyIndex != Property::INVALID_INDEX )
761         {
762           if( animator->animate == false )
763           {
764             if( animator->targetValue.GetType() != Property::NONE )
765             {
766               child.SetProperty( propertyIndex, animator->targetValue );
767             }
768           }
769           else // animate the property
770           {
771             if( animator->initialValue.GetType() != Property::NONE )
772             {
773               child.SetProperty( propertyIndex, animator->initialValue );
774             }
775
776             if( createAnimation && !animation )
777             {
778               animation = Dali::Animation::New( 0.1f );
779             }
780
781             animation.AnimateTo( Property( child, propertyIndex ),
782                                  animator->targetValue,
783                                  animator->alphaFunction,
784                                  TimePeriod( animator->timePeriodDelay,
785                                              animator->timePeriodDuration ) );
786           }
787         }
788       }
789     }
790   }
791 }
792
793 Dali::Animation Control::Impl::CreateTransition( const Toolkit::TransitionData& transitionData )
794 {
795   Dali::Animation transition;
796
797   if( transitionData.Count() > 0 )
798   {
799     AddTransitions( transition, transitionData, true );
800   }
801   return transition;
802 }
803
804
805
806 void Control::Impl::DoAction( Dali::Property::Index visualIndex, Dali::Property::Index actionId, const Dali::Property::Value attributes )
807 {
808   RegisteredVisualContainer::Iterator iter;
809   if ( FindVisual( visualIndex, mVisuals, iter ) )
810   {
811     Toolkit::GetImplementation((*iter)->visual).DoAction( actionId, attributes );
812   }
813 }
814
815 void Control::Impl::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
816 {
817   Toolkit::Control control = Toolkit::Control::DownCast( BaseHandle( object ) );
818
819   if ( control )
820   {
821     Control& controlImpl( GetImplementation( control ) );
822
823     switch ( index )
824     {
825       case Toolkit::Control::Property::STYLE_NAME:
826       {
827         controlImpl.SetStyleName( value.Get< std::string >() );
828         break;
829       }
830
831       case Toolkit::DevelControl::Property::STATE:
832       {
833         bool withTransitions=true;
834         const Property::Value* valuePtr=&value;
835         Property::Map* map = value.GetMap();
836         if(map)
837         {
838           Property::Value* value2 = map->Find("withTransitions");
839           if( value2 )
840           {
841             withTransitions = value2->Get<bool>();
842           }
843
844           valuePtr = map->Find("state");
845         }
846
847         if( valuePtr )
848         {
849           Toolkit::DevelControl::State state( controlImpl.mImpl->mState );
850           if( Scripting::GetEnumerationProperty< Toolkit::DevelControl::State >( *valuePtr, ControlStateTable, ControlStateTableCount, state ) )
851           {
852             controlImpl.mImpl->SetState( state, withTransitions );
853           }
854         }
855       }
856       break;
857
858       case Toolkit::DevelControl::Property::SUB_STATE:
859       {
860         std::string subState;
861         if( value.Get( subState ) )
862         {
863           controlImpl.mImpl->SetSubState( subState );
864         }
865       }
866       break;
867
868       case Toolkit::DevelControl::Property::LEFT_FOCUSABLE_ACTOR_ID:
869       {
870         int focusId;
871         if( value.Get( focusId ) )
872         {
873           controlImpl.mImpl->mLeftFocusableActorId = focusId;
874         }
875       }
876       break;
877
878       case Toolkit::DevelControl::Property::RIGHT_FOCUSABLE_ACTOR_ID:
879       {
880         int focusId;
881         if( value.Get( focusId ) )
882         {
883           controlImpl.mImpl->mRightFocusableActorId = focusId;
884         }
885       }
886       break;
887
888       case Toolkit::DevelControl::Property::UP_FOCUSABLE_ACTOR_ID:
889       {
890         int focusId;
891         if( value.Get( focusId ) )
892         {
893           controlImpl.mImpl->mUpFocusableActorId = focusId;
894         }
895       }
896       break;
897
898       case Toolkit::DevelControl::Property::DOWN_FOCUSABLE_ACTOR_ID:
899       {
900         int focusId;
901         if( value.Get( focusId ) )
902         {
903           controlImpl.mImpl->mDownFocusableActorId = focusId;
904         }
905       }
906       break;
907
908       case Toolkit::Control::Property::BACKGROUND_COLOR:
909       {
910         DALI_LOG_WARNING( "BACKGROUND_COLOR property is deprecated. Use BACKGROUND property instead\n" );
911         controlImpl.SetBackgroundColor( value.Get< Vector4 >() );
912         break;
913       }
914
915       case Toolkit::Control::Property::BACKGROUND_IMAGE:
916       {
917         DALI_LOG_WARNING( "BACKGROUND_IMAGE property is deprecated. Use BACKGROUND property instead\n" );
918         Image image = Scripting::NewImage( value );
919         if ( image )
920         {
921           controlImpl.SetBackgroundImage( image );
922         }
923         else
924         {
925           // An empty image means the background is no longer required
926           controlImpl.ClearBackground();
927         }
928         break;
929       }
930
931       case Toolkit::Control::Property::KEY_INPUT_FOCUS:
932       {
933         if ( value.Get< bool >() )
934         {
935           controlImpl.SetKeyInputFocus();
936         }
937         else
938         {
939           controlImpl.ClearKeyInputFocus();
940         }
941         break;
942       }
943
944       case Toolkit::Control::Property::BACKGROUND:
945       {
946         std::string url;
947         Vector4 color;
948         const Property::Map* map = value.GetMap();
949         if( map && !map->Empty() )
950         {
951           controlImpl.SetBackground( *map );
952         }
953         else if( value.Get( url ) )
954         {
955           // don't know the size to load
956           Toolkit::Visual::Base visual = Toolkit::VisualFactory::Get().CreateVisual( url, ImageDimensions() );
957           if( visual )
958           {
959             controlImpl.mImpl->RegisterVisual( Toolkit::Control::Property::BACKGROUND, visual, DepthIndex::BACKGROUND );
960           }
961         }
962         else if( value.Get( color ) )
963         {
964           controlImpl.SetBackgroundColor(color);
965         }
966         else
967         {
968           // The background is an empty property map, so we should clear the background
969           controlImpl.ClearBackground();
970         }
971         break;
972       }
973
974       case Toolkit::Control::Property::MARGIN:
975       {
976         Extents margin;
977         if( value.Get( margin ) )
978         {
979           controlImpl.mImpl->SetMargin( margin );
980         }
981         break;
982       }
983
984       case Toolkit::Control::Property::PADDING:
985       {
986         Extents padding;
987         if( value.Get( padding ) )
988         {
989           controlImpl.mImpl->SetPadding( padding );
990         }
991         break;
992       }
993
994       case Toolkit::DevelControl::Property::TOOLTIP:
995       {
996         TooltipPtr& tooltipPtr = controlImpl.mImpl->mTooltip;
997         if( ! tooltipPtr )
998         {
999           tooltipPtr = Tooltip::New( control );
1000         }
1001         tooltipPtr->SetProperties( value );
1002         break;
1003       }
1004
1005     }
1006   }
1007 }
1008
1009 Property::Value Control::Impl::GetProperty( BaseObject* object, Property::Index index )
1010 {
1011   Property::Value value;
1012
1013   Toolkit::Control control = Toolkit::Control::DownCast( BaseHandle( object ) );
1014
1015   if ( control )
1016   {
1017     Control& controlImpl( GetImplementation( control ) );
1018
1019     switch ( index )
1020     {
1021       case Toolkit::Control::Property::STYLE_NAME:
1022       {
1023         value = controlImpl.GetStyleName();
1024         break;
1025       }
1026
1027       case Toolkit::DevelControl::Property::STATE:
1028       {
1029         value = controlImpl.mImpl->mState;
1030         break;
1031       }
1032
1033       case Toolkit::DevelControl::Property::SUB_STATE:
1034       {
1035         value = controlImpl.mImpl->mSubStateName;
1036         break;
1037       }
1038
1039       case Toolkit::DevelControl::Property::LEFT_FOCUSABLE_ACTOR_ID:
1040       {
1041         value = controlImpl.mImpl->mLeftFocusableActorId;
1042         break;
1043       }
1044
1045       case Toolkit::DevelControl::Property::RIGHT_FOCUSABLE_ACTOR_ID:
1046       {
1047         value = controlImpl.mImpl->mRightFocusableActorId;
1048         break;
1049       }
1050
1051       case Toolkit::DevelControl::Property::UP_FOCUSABLE_ACTOR_ID:
1052       {
1053         value = controlImpl.mImpl->mUpFocusableActorId;
1054         break;
1055       }
1056
1057       case Toolkit::DevelControl::Property::DOWN_FOCUSABLE_ACTOR_ID:
1058       {
1059         value = controlImpl.mImpl->mDownFocusableActorId;
1060         break;
1061       }
1062
1063       case Toolkit::Control::Property::BACKGROUND_COLOR:
1064       {
1065         DALI_LOG_WARNING( "BACKGROUND_COLOR property is deprecated. Use BACKGROUND property instead\n" );
1066         value = controlImpl.GetBackgroundColor();
1067         break;
1068       }
1069
1070       case Toolkit::Control::Property::BACKGROUND_IMAGE:
1071       {
1072         DALI_LOG_WARNING( "BACKGROUND_IMAGE property is deprecated. Use BACKGROUND property instead\n" );
1073         Property::Map map;
1074         Toolkit::Visual::Base visual = controlImpl.mImpl->GetVisual( Toolkit::Control::Property::BACKGROUND );
1075         if( visual )
1076         {
1077           visual.CreatePropertyMap( map );
1078         }
1079         value = map;
1080         break;
1081       }
1082
1083       case Toolkit::Control::Property::KEY_INPUT_FOCUS:
1084       {
1085         value = controlImpl.HasKeyInputFocus();
1086         break;
1087       }
1088
1089       case Toolkit::Control::Property::BACKGROUND:
1090       {
1091         Property::Map map;
1092         Toolkit::Visual::Base visual = controlImpl.mImpl->GetVisual( Toolkit::Control::Property::BACKGROUND );
1093         if( visual )
1094         {
1095           visual.CreatePropertyMap( map );
1096         }
1097
1098         value = map;
1099         break;
1100       }
1101
1102       case Toolkit::Control::Property::MARGIN:
1103       {
1104         value = controlImpl.mImpl->GetMargin();
1105         break;
1106       }
1107
1108       case Toolkit::Control::Property::PADDING:
1109       {
1110         value = controlImpl.mImpl->GetPadding();
1111         break;
1112       }
1113
1114       case Toolkit::DevelControl::Property::TOOLTIP:
1115       {
1116         Property::Map map;
1117         if( controlImpl.mImpl->mTooltip )
1118         {
1119           controlImpl.mImpl->mTooltip->CreatePropertyMap( map );
1120         }
1121         value = map;
1122         break;
1123       }
1124     }
1125   }
1126
1127   return value;
1128 }
1129
1130
1131 void  Control::Impl::CopyInstancedProperties( RegisteredVisualContainer& visuals, Dictionary<Property::Map>& instancedProperties )
1132 {
1133   for(RegisteredVisualContainer::Iterator iter = visuals.Begin(); iter!= visuals.End(); iter++)
1134   {
1135     if( (*iter)->visual )
1136     {
1137       Property::Map instanceMap;
1138       Toolkit::GetImplementation((*iter)->visual).CreateInstancePropertyMap(instanceMap);
1139       instancedProperties.Add( (*iter)->visual.GetName(), instanceMap );
1140     }
1141   }
1142 }
1143
1144
1145 void Control::Impl::RemoveVisual( RegisteredVisualContainer& visuals, const std::string& visualName )
1146 {
1147   Actor self( mControlImpl.Self() );
1148
1149   for ( RegisteredVisualContainer::Iterator visualIter = visuals.Begin();
1150         visualIter != visuals.End(); ++visualIter )
1151   {
1152     Toolkit::Visual::Base visual = (*visualIter)->visual;
1153     if( visual && visual.GetName() == visualName )
1154     {
1155       Toolkit::GetImplementation(visual).SetOffStage( self );
1156       (*visualIter)->visual.Reset();
1157       visuals.Erase( visualIter );
1158       break;
1159     }
1160   }
1161 }
1162
1163 void Control::Impl::RemoveVisuals( RegisteredVisualContainer& visuals, DictionaryKeys& removeVisuals )
1164 {
1165   Actor self( mControlImpl.Self() );
1166   for( DictionaryKeys::iterator iter = removeVisuals.begin(); iter != removeVisuals.end(); ++iter )
1167   {
1168     const std::string visualName = *iter;
1169     RemoveVisual( visuals, visualName );
1170   }
1171 }
1172
1173 void Control::Impl::RecreateChangedVisuals( Dictionary<Property::Map>& stateVisualsToChange,
1174                              Dictionary<Property::Map>& instancedProperties )
1175 {
1176   Dali::CustomActor handle( mControlImpl.GetOwner() );
1177   for( Dictionary<Property::Map>::iterator iter = stateVisualsToChange.Begin();
1178        iter != stateVisualsToChange.End(); ++iter )
1179   {
1180     const std::string& visualName = (*iter).key;
1181     const Property::Map& toMap = (*iter).entry;
1182
1183     // is it a candidate for re-creation?
1184     bool recreate = false;
1185
1186     Toolkit::Visual::Base visual = GetVisualByName( mVisuals, visualName );
1187     if( visual )
1188     {
1189       Property::Map fromMap;
1190       visual.CreatePropertyMap( fromMap );
1191
1192       Toolkit::Visual::Type fromType = GetVisualTypeFromMap( fromMap );
1193       Toolkit::Visual::Type toType = GetVisualTypeFromMap( toMap );
1194
1195       if( fromType != toType )
1196       {
1197         recreate = true;
1198       }
1199       else
1200       {
1201         if( fromType == Toolkit::Visual::IMAGE || fromType == Toolkit::Visual::N_PATCH
1202             || fromType == Toolkit::Visual::SVG || fromType == Toolkit::Visual::ANIMATED_IMAGE )
1203         {
1204           Property::Value* fromUrl = fromMap.Find( Toolkit::ImageVisual::Property::URL, IMAGE_URL_NAME );
1205           Property::Value* toUrl = toMap.Find( Toolkit::ImageVisual::Property::URL, IMAGE_URL_NAME );
1206
1207           if( fromUrl && toUrl )
1208           {
1209             std::string fromUrlString;
1210             std::string toUrlString;
1211             fromUrl->Get(fromUrlString);
1212             toUrl->Get(toUrlString);
1213
1214             if( fromUrlString != toUrlString )
1215             {
1216               recreate = true;
1217             }
1218           }
1219         }
1220       }
1221
1222       const Property::Map* instancedMap = instancedProperties.FindConst( visualName );
1223       if( recreate || instancedMap )
1224       {
1225         RemoveVisual( mVisuals, visualName );
1226         Style::ApplyVisual( handle, visualName, toMap, instancedMap );
1227       }
1228       else
1229       {
1230         // @todo check to see if we can apply toMap without recreating the visual
1231         // e.g. by setting only animatable properties
1232         // For now, recreate all visuals, but merge in instance data.
1233         RemoveVisual( mVisuals, visualName );
1234         Style::ApplyVisual( handle, visualName, toMap, instancedMap );
1235       }
1236     }
1237   }
1238 }
1239
1240 void Control::Impl::ReplaceStateVisualsAndProperties( const StylePtr oldState, const StylePtr newState, const std::string& subState )
1241 {
1242   // Collect all old visual names
1243   DictionaryKeys stateVisualsToRemove;
1244   if( oldState )
1245   {
1246     oldState->visuals.GetKeys( stateVisualsToRemove );
1247     if( ! subState.empty() )
1248     {
1249       const StylePtr* oldSubState = oldState->subStates.FindConst(subState);
1250       if( oldSubState )
1251       {
1252         DictionaryKeys subStateVisualsToRemove;
1253         (*oldSubState)->visuals.GetKeys( subStateVisualsToRemove );
1254         Merge( stateVisualsToRemove, subStateVisualsToRemove );
1255       }
1256     }
1257   }
1258
1259   // Collect all new visual properties
1260   Dictionary<Property::Map> stateVisualsToAdd;
1261   if( newState )
1262   {
1263     stateVisualsToAdd = newState->visuals;
1264     if( ! subState.empty() )
1265     {
1266       const StylePtr* newSubState = newState->subStates.FindConst(subState);
1267       if( newSubState )
1268       {
1269         stateVisualsToAdd.Merge( (*newSubState)->visuals );
1270       }
1271     }
1272   }
1273
1274   // If a name is in both add/remove, move it to change list.
1275   Dictionary<Property::Map> stateVisualsToChange;
1276   FindChangableVisuals( stateVisualsToAdd, stateVisualsToChange, stateVisualsToRemove);
1277
1278   // Copy instanced properties (e.g. text label) of current visuals
1279   Dictionary<Property::Map> instancedProperties;
1280   CopyInstancedProperties( mVisuals, instancedProperties );
1281
1282   // For each visual in remove list, remove from mVisuals
1283   RemoveVisuals( mVisuals, stateVisualsToRemove );
1284
1285   // For each visual in add list, create and add to mVisuals
1286   Dali::CustomActor handle( mControlImpl.GetOwner() );
1287   Style::ApplyVisuals( handle, stateVisualsToAdd, instancedProperties );
1288
1289   // For each visual in change list, if it requires a new visual,
1290   // remove old visual, create and add to mVisuals
1291   RecreateChangedVisuals( stateVisualsToChange, instancedProperties );
1292 }
1293
1294 void Control::Impl::SetState( DevelControl::State newState, bool withTransitions )
1295 {
1296   DevelControl::State oldState = mState;
1297   Dali::CustomActor handle( mControlImpl.GetOwner() );
1298   DALI_LOG_INFO(gLogFilter, Debug::Concise, "Control::Impl::SetState: %s\n",
1299                 (mState == DevelControl::NORMAL ? "NORMAL" :(
1300                   mState == DevelControl::FOCUSED ?"FOCUSED" : (
1301                     mState == DevelControl::DISABLED?"DISABLED":"NONE" ))));
1302
1303   if( mState != newState )
1304   {
1305     // If mState was Disabled, and new state is Focused, should probably
1306     // store that fact, e.g. in another property that FocusManager can access.
1307     mState = newState;
1308
1309     // Trigger state change and transitions
1310     // Apply new style, if stylemanager is available
1311     Toolkit::StyleManager styleManager = Toolkit::StyleManager::Get();
1312     if( styleManager )
1313     {
1314       const StylePtr stylePtr = GetImpl( styleManager ).GetRecordedStyle( Toolkit::Control( mControlImpl.GetOwner() ) );
1315
1316       if( stylePtr )
1317       {
1318         std::string oldStateName = Scripting::GetEnumerationName< Toolkit::DevelControl::State >( oldState, ControlStateTable, ControlStateTableCount );
1319         std::string newStateName = Scripting::GetEnumerationName< Toolkit::DevelControl::State >( newState, ControlStateTable, ControlStateTableCount );
1320
1321         const StylePtr* newStateStyle = stylePtr->subStates.Find( newStateName );
1322         const StylePtr* oldStateStyle = stylePtr->subStates.Find( oldStateName );
1323         if( oldStateStyle && newStateStyle )
1324         {
1325           // Only change if both state styles exist
1326           ReplaceStateVisualsAndProperties( *oldStateStyle, *newStateStyle, mSubStateName );
1327         }
1328       }
1329     }
1330   }
1331 }
1332
1333 void Control::Impl::SetSubState( const std::string& subStateName, bool withTransitions )
1334 {
1335   if( mSubStateName != subStateName )
1336   {
1337     // Get existing sub-state visuals, and unregister them
1338     Dali::CustomActor handle( mControlImpl.GetOwner() );
1339
1340     Toolkit::StyleManager styleManager = Toolkit::StyleManager::Get();
1341     if( styleManager )
1342     {
1343       const StylePtr stylePtr = GetImpl( styleManager ).GetRecordedStyle( Toolkit::Control( mControlImpl.GetOwner() ) );
1344       if( stylePtr )
1345       {
1346         // Stringify state
1347         std::string stateName = Scripting::GetEnumerationName< Toolkit::DevelControl::State >( mState, ControlStateTable, ControlStateTableCount );
1348
1349         const StylePtr* state = stylePtr->subStates.Find( stateName );
1350         if( state )
1351         {
1352           StylePtr stateStyle(*state);
1353
1354           const StylePtr* newStateStyle = stateStyle->subStates.Find( subStateName );
1355           const StylePtr* oldStateStyle = stateStyle->subStates.Find( mSubStateName );
1356           if( oldStateStyle && newStateStyle )
1357           {
1358             std::string empty;
1359             ReplaceStateVisualsAndProperties( *oldStateStyle, *newStateStyle, empty );
1360           }
1361         }
1362       }
1363     }
1364
1365     mSubStateName = subStateName;
1366   }
1367 }
1368
1369 void Control::Impl::OnStageDisconnection()
1370 {
1371   Actor self = mControlImpl.Self();
1372
1373   // Any visuals set for replacement but not yet ready should still be registered.
1374   // Reason: If a request was made to register a new visual but the control removed from stage before visual was ready
1375   // then when this control appears back on stage it should use that new visual.
1376
1377   // Iterate through all registered visuals and set off stage
1378   SetVisualsOffStage( mVisuals, self );
1379
1380   // Visuals pending replacement can now be taken out of the removal list and set off stage
1381   // Iterate through all replacement visuals and add to a move queue then set off stage
1382   for( auto removalIter = mRemoveVisuals.Begin(), end = mRemoveVisuals.End(); removalIter != end; removalIter++ )
1383   {
1384     Toolkit::GetImplementation((*removalIter)->visual).SetOffStage( self );
1385   }
1386
1387   for( auto replacedIter = mVisuals.Begin(), end = mVisuals.End(); replacedIter != end; replacedIter++ )
1388   {
1389     (*replacedIter)->pending = false;
1390   }
1391
1392   mRemoveVisuals.Clear();
1393 }
1394
1395 void Control::Impl::SetMargin( Extents margin )
1396 {
1397   mControlImpl.mImpl->mMargin = margin;
1398
1399   // Trigger a size negotiation request that may be needed when setting a margin.
1400   mControlImpl.RelayoutRequest();
1401 }
1402
1403 Extents Control::Impl::GetMargin() const
1404 {
1405   return mControlImpl.mImpl->mMargin;
1406 }
1407
1408 void Control::Impl::SetPadding( Extents padding )
1409 {
1410   mControlImpl.mImpl->mPadding = padding;
1411
1412   // Trigger a size negotiation request that may be needed when setting a padding.
1413   mControlImpl.RelayoutRequest();
1414 }
1415
1416 Extents Control::Impl::GetPadding() const
1417 {
1418   return mControlImpl.mImpl->mPadding;
1419 }
1420
1421 void Control::Impl::SetInputMethodContext( InputMethodContext& inputMethodContext )
1422 {
1423   mInputMethodContext = inputMethodContext;
1424 }
1425
1426 bool Control::Impl::FilterKeyEvent( const KeyEvent& event )
1427 {
1428   bool consumed ( false );
1429
1430   if ( mInputMethodContext )
1431   {
1432     consumed = mInputMethodContext.FilterEventKey( event );
1433   }
1434   return consumed;
1435 }
1436
1437 Toolkit::Internal::LayoutItemPtr Control::Impl::GetLayout() const
1438 {
1439   return mLayout;
1440 }
1441
1442 void Control::Impl::SetLayout( Toolkit::Internal::LayoutItem& layout )
1443 {
1444   DALI_LOG_INFO( gLogFilterLayout, Debug::Verbose, "Control::SetLayout control:%s  replacing existing layout:%s\n",
1445                                    mControlImpl.Self().GetName().c_str(),
1446                                    mLayout?"true":"false" );
1447   // Check if layout already has an owner.
1448   auto control = Toolkit::Control::DownCast( layout.GetOwner() );
1449   if ( control )
1450   {
1451     // If the owner is not this control then the owning control can no longer own it.
1452     Dali::Toolkit::Control handle( mControlImpl.GetOwner() );
1453     if( control != handle )
1454     {
1455       DALI_LOG_INFO( gLogFilterLayout, Debug::Verbose, "Control::SetLayout Layout already in use, %s will now have a BinLayout\n",
1456                                                         control.GetName().c_str() );
1457       Toolkit::BinLayout binLayout = Toolkit::BinLayout::New();
1458       // Previous owner of the layout gets a BinLayout instead of the layout.
1459       DevelControl::SetLayout( control, binLayout ) ;
1460     }
1461     else
1462     {
1463       return; // layout is already set to this control.
1464     }
1465   }
1466
1467   if( mLayout )
1468   {
1469     mLayout->Unparent();
1470     mLayout.Reset();
1471   }
1472
1473   mLayout = &layout;
1474
1475   auto controlHandle = Toolkit::Control::DownCast( mControlImpl.Self() ); // Get a handle of this control implementation without copying internals.
1476   mLayout->Initialize( controlHandle, controlHandle.GetTypeName() ); // LayoutGroup takes ownership of existing children
1477 }
1478
1479 void Control::Impl::RemoveLayout()
1480 {
1481   DALI_LOG_INFO( gLogFilterLayout, Debug::Verbose, "Control::Impl::RemoveLayout\n");
1482
1483   Toolkit::BinLayout binLayout = Toolkit::BinLayout::New();
1484
1485   mControlImpl.mImpl->SetLayout( GetImplementation( binLayout ) ) ;
1486 }
1487
1488 void Control::Impl::SetLayoutingRequired( bool layoutingRequired )
1489 {
1490   mControlImpl.mImpl->mIsLayoutingRequired = layoutingRequired;
1491 }
1492
1493 bool Control::Impl::IsLayoutingRequired()
1494 {
1495   return mControlImpl.mImpl->mIsLayoutingRequired;
1496 }
1497
1498 } // namespace Internal
1499
1500 } // namespace Toolkit
1501
1502 } // namespace Dali