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