[dali_1.9.35] Merge branch 'devel/master'
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / controls / control / control-data-impl.cpp
1 /*
2  * Copyright (c) 2019 Samsung Electronics Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17
18 // CLASS HEADER
19 #include "control-data-impl.h"
20
21 // EXTERNAL INCLUDES
22 #include <dali-toolkit/public-api/dali-toolkit-common.h>
23 #include <dali/integration-api/debug.h>
24 #include <dali/devel-api/object/handle-devel.h>
25 #include <dali/devel-api/scripting/enum-helper.h>
26 #include <dali/devel-api/scripting/scripting.h>
27 #include <dali/integration-api/debug.h>
28 #include <dali/public-api/object/type-registry-helper.h>
29 #include <dali/integration-api/adaptor-framework/adaptor.h>
30 #include <cstring>
31 #include <limits>
32
33 // INTERNAL INCLUDES
34 #include <dali-toolkit/internal/visuals/visual-base-impl.h>
35 #include <dali-toolkit/public-api/visuals/image-visual-properties.h>
36 #include <dali-toolkit/public-api/visuals/visual-properties.h>
37 #include <dali-toolkit/devel-api/controls/control-depth-index-ranges.h>
38 #include <dali-toolkit/devel-api/controls/control-devel.h>
39 #include <dali-toolkit/devel-api/controls/control-wrapper-impl.h>
40 #include <dali-toolkit/internal/styling/style-manager-impl.h>
41 #include <dali-toolkit/internal/visuals/visual-string-constants.h>
42
43 namespace Dali
44 {
45
46 namespace Toolkit
47 {
48
49 namespace Internal
50 {
51
52 extern const Dali::Scripting::StringEnum ControlStateTable[];
53 extern const unsigned int ControlStateTableCount;
54
55
56 // Not static or anonymous - shared with other translation units
57 const Scripting::StringEnum ControlStateTable[] = {
58   { "NORMAL",   Toolkit::DevelControl::NORMAL   },
59   { "FOCUSED",  Toolkit::DevelControl::FOCUSED  },
60   { "DISABLED", Toolkit::DevelControl::DISABLED },
61 };
62 const unsigned int ControlStateTableCount = sizeof( ControlStateTable ) / sizeof( ControlStateTable[0] );
63
64
65
66 namespace
67 {
68
69 #if defined(DEBUG_ENABLED)
70 Debug::Filter* gLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_CONTROL_VISUALS");
71 #endif
72
73
74 template<typename T>
75 void Remove( Dictionary<T>& keyValues, const std::string& name )
76 {
77   keyValues.Remove(name);
78 }
79
80 void Remove( DictionaryKeys& keys, const std::string& name )
81 {
82   DictionaryKeys::iterator iter = std::find( keys.begin(), keys.end(), name );
83   if( iter != keys.end())
84   {
85     keys.erase(iter);
86   }
87 }
88
89 Toolkit::Visual::Type GetVisualTypeFromMap( const Property::Map& map )
90 {
91   Property::Value* typeValue = map.Find( Toolkit::Visual::Property::TYPE, VISUAL_TYPE  );
92   Toolkit::Visual::Type type = Toolkit::Visual::IMAGE;
93   if( typeValue )
94   {
95     Scripting::GetEnumerationProperty( *typeValue, VISUAL_TYPE_TABLE, VISUAL_TYPE_TABLE_COUNT, type );
96   }
97   return type;
98 }
99
100 /**
101  *  Finds visual in given array, returning true if found along with the iterator for that visual as a out parameter
102  */
103 bool FindVisual( Property::Index targetIndex, const RegisteredVisualContainer& visuals, RegisteredVisualContainer::Iterator& iter )
104 {
105   for ( iter = visuals.Begin(); iter != visuals.End(); iter++ )
106   {
107     if ( (*iter)->index ==  targetIndex )
108     {
109       return true;
110     }
111   }
112   return false;
113 }
114
115 void FindChangableVisuals( Dictionary<Property::Map>& stateVisualsToAdd,
116                            Dictionary<Property::Map>& stateVisualsToChange,
117                            DictionaryKeys& stateVisualsToRemove)
118 {
119   DictionaryKeys copyOfStateVisualsToRemove = stateVisualsToRemove;
120
121   for( DictionaryKeys::iterator iter = copyOfStateVisualsToRemove.begin();
122        iter != copyOfStateVisualsToRemove.end(); ++iter )
123   {
124     const std::string& visualName = (*iter);
125     Property::Map* toMap = stateVisualsToAdd.Find( visualName );
126     if( toMap )
127     {
128       stateVisualsToChange.Add( visualName, *toMap );
129       stateVisualsToAdd.Remove( visualName );
130       Remove( stateVisualsToRemove, visualName );
131     }
132   }
133 }
134
135 Toolkit::Visual::Base GetVisualByName(
136   const RegisteredVisualContainer& visuals,
137   const std::string& visualName )
138 {
139   Toolkit::Visual::Base visualHandle;
140
141   RegisteredVisualContainer::Iterator iter;
142   for ( iter = visuals.Begin(); iter != visuals.End(); iter++ )
143   {
144     Toolkit::Visual::Base visual = (*iter)->visual;
145     if( visual && visual.GetName() == visualName )
146     {
147       visualHandle = visual;
148       break;
149     }
150   }
151   return visualHandle;
152 }
153
154 /**
155  * Move visual from source to destination container
156  */
157 void MoveVisual( RegisteredVisualContainer::Iterator sourceIter, RegisteredVisualContainer& source, RegisteredVisualContainer& destination )
158 {
159    Toolkit::Visual::Base visual = (*sourceIter)->visual;
160    if( visual )
161    {
162      RegisteredVisual* rv = source.Release( sourceIter );
163      destination.PushBack( rv );
164    }
165 }
166
167 /**
168  * Performs actions as requested using the action name.
169  * @param[in] object The object on which to perform the action.
170  * @param[in] actionName The action to perform.
171  * @param[in] attributes The attributes with which to perfrom this action.
172  * @return true if action has been accepted by this control
173  */
174 const char* ACTION_ACCESSIBILITY_ACTIVATED = "accessibilityActivated";
175 static bool DoAction( BaseObject* object, const std::string& actionName, const Property::Map& attributes )
176 {
177   bool ret = false;
178
179   if( object && ( 0 == strcmp( actionName.c_str(), ACTION_ACCESSIBILITY_ACTIVATED ) ) )
180   {
181     Toolkit::Control control = Toolkit::Control::DownCast( BaseHandle( object ) );
182     if( control )
183     {
184       // if cast succeeds there is an implementation so no need to check
185       ret = Internal::GetImplementation( control ).OnAccessibilityActivated();
186     }
187   }
188
189   return ret;
190 }
191
192 /**
193  * Connects a callback function with the object's signals.
194  * @param[in] object The object providing the signal.
195  * @param[in] tracker Used to disconnect the signal.
196  * @param[in] signalName The signal to connect to.
197  * @param[in] functor A newly allocated FunctorDelegate.
198  * @return True if the signal was connected.
199  * @post If a signal was connected, ownership of functor was passed to CallbackBase. Otherwise the caller is responsible for deleting the unused functor.
200  */
201 const char* SIGNAL_KEY_EVENT = "keyEvent";
202 const char* SIGNAL_KEY_INPUT_FOCUS_GAINED = "keyInputFocusGained";
203 const char* SIGNAL_KEY_INPUT_FOCUS_LOST = "keyInputFocusLost";
204 const char* SIGNAL_TAPPED = "tapped";
205 const char* SIGNAL_PANNED = "panned";
206 const char* SIGNAL_PINCHED = "pinched";
207 const char* SIGNAL_LONG_PRESSED = "longPressed";
208 static bool DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
209 {
210   Dali::BaseHandle handle( object );
211
212   bool connected( false );
213   Toolkit::Control control = Toolkit::Control::DownCast( handle );
214   if ( control )
215   {
216     Internal::Control& controlImpl( Internal::GetImplementation( control ) );
217     connected = true;
218
219     if ( 0 == strcmp( signalName.c_str(), SIGNAL_KEY_EVENT ) )
220     {
221       controlImpl.KeyEventSignal().Connect( tracker, functor );
222     }
223     else if( 0 == strcmp( signalName.c_str(), SIGNAL_KEY_INPUT_FOCUS_GAINED ) )
224     {
225       controlImpl.KeyInputFocusGainedSignal().Connect( tracker, functor );
226     }
227     else if( 0 == strcmp( signalName.c_str(), SIGNAL_KEY_INPUT_FOCUS_LOST ) )
228     {
229       controlImpl.KeyInputFocusLostSignal().Connect( tracker, functor );
230     }
231     else if( 0 == strcmp( signalName.c_str(), SIGNAL_TAPPED ) )
232     {
233       controlImpl.EnableGestureDetection( GestureType::TAP );
234       controlImpl.GetTapGestureDetector().DetectedSignal().Connect( tracker, functor );
235     }
236     else if( 0 == strcmp( signalName.c_str(), SIGNAL_PANNED ) )
237     {
238       controlImpl.EnableGestureDetection( GestureType::PAN );
239       controlImpl.GetPanGestureDetector().DetectedSignal().Connect( tracker, functor );
240     }
241     else if( 0 == strcmp( signalName.c_str(), SIGNAL_PINCHED ) )
242     {
243       controlImpl.EnableGestureDetection( GestureType::PINCH );
244       controlImpl.GetPinchGestureDetector().DetectedSignal().Connect( tracker, functor );
245     }
246     else if( 0 == strcmp( signalName.c_str(), SIGNAL_LONG_PRESSED ) )
247     {
248       controlImpl.EnableGestureDetection( GestureType::LONG_PRESS );
249       controlImpl.GetLongPressGestureDetector().DetectedSignal().Connect( tracker, functor );
250     }
251   }
252   return connected;
253 }
254
255 /**
256  * Creates control through type registry
257  */
258 BaseHandle Create()
259 {
260   return Internal::Control::New();
261 }
262 // Setup signals and actions using the type-registry.
263 DALI_TYPE_REGISTRATION_BEGIN( Control, CustomActor, Create );
264
265 // Note: Properties are registered separately below.
266
267 SignalConnectorType registerSignal1( typeRegistration, SIGNAL_KEY_EVENT, &DoConnectSignal );
268 SignalConnectorType registerSignal2( typeRegistration, SIGNAL_KEY_INPUT_FOCUS_GAINED, &DoConnectSignal );
269 SignalConnectorType registerSignal3( typeRegistration, SIGNAL_KEY_INPUT_FOCUS_LOST, &DoConnectSignal );
270 SignalConnectorType registerSignal4( typeRegistration, SIGNAL_TAPPED, &DoConnectSignal );
271 SignalConnectorType registerSignal5( typeRegistration, SIGNAL_PANNED, &DoConnectSignal );
272 SignalConnectorType registerSignal6( typeRegistration, SIGNAL_PINCHED, &DoConnectSignal );
273 SignalConnectorType registerSignal7( typeRegistration, SIGNAL_LONG_PRESSED, &DoConnectSignal );
274
275 TypeAction registerAction( typeRegistration, ACTION_ACCESSIBILITY_ACTIVATED, &DoAction );
276
277 DALI_TYPE_REGISTRATION_END()
278
279 /**
280  * @brief Iterate through given container and setOffScene any visual found
281  *
282  * @param[in] container Container of visuals
283  * @param[in] parent Parent actor to remove visuals from
284  */
285 void SetVisualsOffScene( const RegisteredVisualContainer& container, Actor parent )
286 {
287   for( auto iter = container.Begin(), end = container.End() ; iter!= end; iter++)
288   {
289     if( (*iter)->visual )
290     {
291       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::SetOffScene Setting visual(%d) off stage\n", (*iter)->index );
292       Toolkit::GetImplementation((*iter)->visual).SetOffScene( parent );
293     }
294   }
295 }
296
297 } // unnamed namespace
298
299
300 // Properties registered without macro to use specific member variables.
301 const PropertyRegistration Control::Impl::PROPERTY_1( typeRegistration, "styleName",              Toolkit::Control::Property::STYLE_NAME,                   Property::STRING,  &Control::Impl::SetProperty, &Control::Impl::GetProperty );
302 const PropertyRegistration Control::Impl::PROPERTY_4( typeRegistration, "keyInputFocus",          Toolkit::Control::Property::KEY_INPUT_FOCUS,              Property::BOOLEAN, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
303 const PropertyRegistration Control::Impl::PROPERTY_5( typeRegistration, "background",             Toolkit::Control::Property::BACKGROUND,                   Property::MAP,     &Control::Impl::SetProperty, &Control::Impl::GetProperty );
304 const PropertyRegistration Control::Impl::PROPERTY_6( typeRegistration, "margin",                 Toolkit::Control::Property::MARGIN,                       Property::EXTENTS, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
305 const PropertyRegistration Control::Impl::PROPERTY_7( typeRegistration, "padding",                Toolkit::Control::Property::PADDING,                      Property::EXTENTS, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
306 const PropertyRegistration Control::Impl::PROPERTY_8( typeRegistration, "tooltip",                Toolkit::DevelControl::Property::TOOLTIP,                 Property::MAP,     &Control::Impl::SetProperty, &Control::Impl::GetProperty );
307 const PropertyRegistration Control::Impl::PROPERTY_9( typeRegistration, "state",                  Toolkit::DevelControl::Property::STATE,                   Property::STRING,  &Control::Impl::SetProperty, &Control::Impl::GetProperty );
308 const PropertyRegistration Control::Impl::PROPERTY_10( typeRegistration, "subState",               Toolkit::DevelControl::Property::SUB_STATE,               Property::STRING,  &Control::Impl::SetProperty, &Control::Impl::GetProperty );
309 const PropertyRegistration Control::Impl::PROPERTY_11( typeRegistration, "leftFocusableActorId",   Toolkit::DevelControl::Property::LEFT_FOCUSABLE_ACTOR_ID, Property::INTEGER, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
310 const PropertyRegistration Control::Impl::PROPERTY_12( typeRegistration, "rightFocusableActorId", Toolkit::DevelControl::Property::RIGHT_FOCUSABLE_ACTOR_ID,Property::INTEGER, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
311 const PropertyRegistration Control::Impl::PROPERTY_13( typeRegistration, "upFocusableActorId",    Toolkit::DevelControl::Property::UP_FOCUSABLE_ACTOR_ID,   Property::INTEGER, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
312 const PropertyRegistration Control::Impl::PROPERTY_14( typeRegistration, "downFocusableActorId",  Toolkit::DevelControl::Property::DOWN_FOCUSABLE_ACTOR_ID, Property::INTEGER, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
313 const PropertyRegistration Control::Impl::PROPERTY_15( typeRegistration, "shadow",                Toolkit::DevelControl::Property::SHADOW,                  Property::MAP,     &Control::Impl::SetProperty, &Control::Impl::GetProperty );
314
315
316 Control::Impl::Impl( Control& controlImpl )
317 : mControlImpl( controlImpl ),
318   mState( Toolkit::DevelControl::NORMAL ),
319   mSubStateName(""),
320   mLeftFocusableActorId( -1 ),
321   mRightFocusableActorId( -1 ),
322   mUpFocusableActorId( -1 ),
323   mDownFocusableActorId( -1 ),
324   mStyleName(""),
325   mBackgroundColor(Color::TRANSPARENT),
326   mStartingPinchScale(nullptr),
327   mMargin( 0, 0, 0, 0 ),
328   mPadding( 0, 0, 0, 0 ),
329   mKeyEventSignal(),
330   mKeyInputFocusGainedSignal(),
331   mKeyInputFocusLostSignal(),
332   mResourceReadySignal(),
333   mVisualEventSignal(),
334   mPinchGestureDetector(),
335   mPanGestureDetector(),
336   mTapGestureDetector(),
337   mLongPressGestureDetector(),
338   mTooltip( NULL ),
339   mInputMethodContext(),
340   mIdleCallback(nullptr),
341   mFlags( Control::ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ),
342   mIsKeyboardNavigationSupported( false ),
343   mIsKeyboardFocusGroup( false ),
344   mIsEmittingResourceReadySignal(false),
345   mNeedToEmitResourceReady(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   if(mIdleCallback && Adaptor::IsAvailable())
355   {
356     // Removes the callback from the callback manager in case the control is destroyed before the callback is executed.
357     Adaptor::Get().RemoveIdle(mIdleCallback);
358   }
359 }
360
361 Control::Impl& Control::Impl::Get( Internal::Control& internalControl )
362 {
363   return *internalControl.mImpl;
364 }
365
366 const Control::Impl& Control::Impl::Get( const Internal::Control& internalControl )
367 {
368   return *internalControl.mImpl;
369 }
370
371 // Gesture Detection Methods
372 void Control::Impl::PinchDetected(Actor actor, const PinchGesture& pinch)
373 {
374   mControlImpl.OnPinch(pinch);
375 }
376
377 void Control::Impl::PanDetected(Actor actor, const PanGesture& pan)
378 {
379   mControlImpl.OnPan(pan);
380 }
381
382 void Control::Impl::TapDetected(Actor actor, const TapGesture& tap)
383 {
384   mControlImpl.OnTap(tap);
385 }
386
387 void Control::Impl::LongPressDetected(Actor actor, const LongPressGesture& longPress)
388 {
389   mControlImpl.OnLongPress(longPress);
390 }
391
392 void Control::Impl::RegisterVisual( Property::Index index, Toolkit::Visual::Base& visual )
393 {
394   RegisterVisual( index, visual, VisualState::ENABLED, DepthIndexValue::NOT_SET );
395 }
396
397 void Control::Impl::RegisterVisual( Property::Index index, Toolkit::Visual::Base& visual, int depthIndex )
398 {
399   RegisterVisual( index, visual, VisualState::ENABLED, DepthIndexValue::SET, depthIndex );
400 }
401
402 void Control::Impl::RegisterVisual( Property::Index index, Toolkit::Visual::Base& visual, bool enabled )
403 {
404   RegisterVisual( index, visual, ( enabled ? VisualState::ENABLED : VisualState::DISABLED ), DepthIndexValue::NOT_SET );
405 }
406
407 void Control::Impl::RegisterVisual( Property::Index index, Toolkit::Visual::Base& visual, bool enabled, int depthIndex )
408 {
409   RegisterVisual( index, visual, ( enabled ? VisualState::ENABLED : VisualState::DISABLED ), DepthIndexValue::SET, depthIndex );
410 }
411
412 void Control::Impl::RegisterVisual( Property::Index index, Toolkit::Visual::Base& visual, VisualState::Type enabled, DepthIndexValue::Type depthIndexValueSet, int depthIndex )
413 {
414   DALI_LOG_INFO( gLogFilter, Debug::Concise, "RegisterVisual:%d \n", index );
415
416   bool visualReplaced ( false );
417   Actor self = mControlImpl.Self();
418
419   // Set the depth index, if not set by caller this will be either the current visual depth, max depth of all visuals
420   // or zero.
421   int requiredDepthIndex = visual.GetDepthIndex();
422
423   if( depthIndexValueSet == DepthIndexValue::SET )
424   {
425     requiredDepthIndex = depthIndex;
426   }
427
428   // Visual replacement, existing visual should only be removed from stage when replacement ready.
429   if( !mVisuals.Empty() )
430   {
431     RegisteredVisualContainer::Iterator registeredVisualsiter;
432     // Check if visual (index) is already registered, this is the current visual.
433     if( FindVisual( index, mVisuals, registeredVisualsiter ) )
434     {
435       Toolkit::Visual::Base& currentRegisteredVisual = (*registeredVisualsiter)->visual;
436       if( currentRegisteredVisual )
437       {
438         // Store current visual depth index as may need to set the replacement visual to same depth
439         const int currentDepthIndex = (*registeredVisualsiter)->visual.GetDepthIndex();
440
441         // No longer required to know if the replaced visual's resources are ready
442         StopObservingVisual( currentRegisteredVisual );
443
444         // If control staged and visual enabled then visuals will be swapped once ready
445         if(  self.GetProperty< bool >( Actor::Property::CONNECTED_TO_SCENE ) && enabled )
446         {
447           // Check if visual is currently in the process of being replaced ( is in removal container )
448           RegisteredVisualContainer::Iterator visualQueuedForRemoval;
449           if ( FindVisual( index, mRemoveVisuals, visualQueuedForRemoval ) )
450           {
451             // Visual with same index is already in removal container so current visual pending
452             // Only the the last requested visual will be displayed so remove current visual which is staged but not ready.
453             Toolkit::GetImplementation( currentRegisteredVisual ).SetOffScene( self );
454             mVisuals.Erase( registeredVisualsiter );
455           }
456           else
457           {
458             // current visual not already in removal container so add now.
459             DALI_LOG_INFO( gLogFilter, Debug::Verbose, "RegisterVisual Move current registered visual to removal Queue: %d \n", index );
460             MoveVisual( registeredVisualsiter, mVisuals, mRemoveVisuals );
461           }
462         }
463         else
464         {
465           // Control not staged or visual disabled so can just erase from registered visuals and new visual will be added later.
466           mVisuals.Erase( registeredVisualsiter );
467         }
468
469         // 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
470         if( ( depthIndexValueSet == DepthIndexValue::NOT_SET ) &&
471             ( visual.GetDepthIndex() == 0 ) )
472         {
473           requiredDepthIndex = currentDepthIndex;
474         }
475       }
476
477       visualReplaced = true;
478     }
479   }
480
481   // If not set, set the name of the visual to the same name as the control's property.
482   // ( If the control has been type registered )
483   if( visual.GetName().empty() )
484   {
485     // returns empty string if index is not found as long as index is not -1
486     std::string visualName = self.GetPropertyName( index );
487     if( !visualName.empty() )
488     {
489       DALI_LOG_INFO( gLogFilter, Debug::Concise, "Setting visual name for property %d to %s\n",
490                      index, visualName.c_str() );
491       visual.SetName( visualName );
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.GetProperty< bool >( Actor::Property::CONNECTED_TO_SCENE ) )
536     {
537       visualImpl.SetOnScene( 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).SetOffScene( 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 ).SetOffScene( 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().GetProperty< bool >( Actor::Property::CONNECTED_TO_SCENE ) ) // If control not on Scene then Visual will be added when SceneConnection 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).SetOnScene( 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).SetOffScene( 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.RemoveEventObserver( *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 events
642   visualImpl.AddEventObserver( *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 ).SetOffScene( 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.GetProperty< bool >( Actor::Property::CONNECTED_TO_SCENE ) )
676   {
677     mControlImpl.RelayoutRequest();
678   }
679
680   // Emit signal if all enabled visuals registered by the control are ready.
681   if( IsResourceReady() )
682   {
683     // Reset the flag
684     mNeedToEmitResourceReady = false;
685
686     EmitResourceReadySignal();
687   }
688 }
689
690 void Control::Impl::NotifyVisualEvent( Visual::Base& object, Property::Index signalId )
691 {
692   for( auto registeredIter = mVisuals.Begin(),  end = mVisuals.End(); registeredIter != end; ++registeredIter )
693   {
694     Internal::Visual::Base& registeredVisualImpl = Toolkit::GetImplementation( (*registeredIter)->visual );
695     if( &object == &registeredVisualImpl )
696     {
697       Dali::Toolkit::Control handle( mControlImpl.GetOwner() );
698       mVisualEventSignal.Emit( handle, (*registeredIter)->index, signalId );
699       break;
700     }
701   }
702 }
703
704 bool Control::Impl::IsResourceReady() const
705 {
706   // Iterate through and check all the enabled visuals are ready
707   for( auto visualIter = mVisuals.Begin();
708          visualIter != mVisuals.End(); ++visualIter )
709   {
710     const Toolkit::Visual::Base visual = (*visualIter)->visual;
711     const Internal::Visual::Base& visualImpl = Toolkit::GetImplementation( visual );
712
713     // one of the enabled visuals is not ready
714     if( !visualImpl.IsResourceReady() && (*visualIter)->enabled )
715     {
716       return false;
717     }
718   }
719   return true;
720 }
721
722 Toolkit::Visual::ResourceStatus Control::Impl::GetVisualResourceStatus( Property::Index index ) const
723 {
724   RegisteredVisualContainer::Iterator iter;
725   if ( FindVisual( index, mVisuals, iter ) )
726   {
727     const Toolkit::Visual::Base visual = (*iter)->visual;
728     const Internal::Visual::Base& visualImpl = Toolkit::GetImplementation( visual );
729     return visualImpl.GetResourceStatus( );
730   }
731
732   return Toolkit::Visual::ResourceStatus::PREPARING;
733 }
734
735
736
737 void Control::Impl::AddTransitions( Dali::Animation& animation,
738                                     const Toolkit::TransitionData& handle,
739                                     bool createAnimation )
740 {
741   // Setup a Transition from TransitionData.
742   const Internal::TransitionData& transitionData = Toolkit::GetImplementation( handle );
743   TransitionData::Iterator end = transitionData.End();
744   for( TransitionData::Iterator iter = transitionData.Begin() ;
745        iter != end; ++iter )
746   {
747     TransitionData::Animator* animator = (*iter);
748
749     Toolkit::Visual::Base visual = GetVisualByName( mVisuals, animator->objectName );
750
751     if( visual )
752     {
753 #if defined(DEBUG_ENABLED)
754       Dali::TypeInfo typeInfo;
755       ControlWrapper* controlWrapperImpl = dynamic_cast<ControlWrapper*>(&mControlImpl);
756       if( controlWrapperImpl )
757       {
758         typeInfo = controlWrapperImpl->GetTypeInfo();
759       }
760
761       DALI_LOG_INFO( gLogFilter, Debug::Concise, "CreateTransition: Found %s visual for %s\n",
762                      visual.GetName().c_str(), typeInfo?typeInfo.GetName().c_str():"Unknown" );
763 #endif
764       Internal::Visual::Base& visualImpl = Toolkit::GetImplementation( visual );
765       visualImpl.AnimateProperty( animation, *animator );
766     }
767     else
768     {
769       DALI_LOG_INFO( gLogFilter, Debug::Concise, "CreateTransition: Could not find visual. Trying actors");
770       // Otherwise, try any actor children of control (Including the control)
771       Actor child = mControlImpl.Self().FindChildByName( animator->objectName );
772       if( child )
773       {
774         Property::Index propertyIndex = child.GetPropertyIndex( animator->propertyKey );
775         if( propertyIndex != Property::INVALID_INDEX )
776         {
777           if( animator->animate == false )
778           {
779             if( animator->targetValue.GetType() != Property::NONE )
780             {
781               child.SetProperty( propertyIndex, animator->targetValue );
782             }
783           }
784           else // animate the property
785           {
786             if( animator->initialValue.GetType() != Property::NONE )
787             {
788               child.SetProperty( propertyIndex, animator->initialValue );
789             }
790
791             if( createAnimation && !animation )
792             {
793               animation = Dali::Animation::New( 0.1f );
794             }
795
796             animation.AnimateTo( Property( child, propertyIndex ),
797                                  animator->targetValue,
798                                  animator->alphaFunction,
799                                  TimePeriod( animator->timePeriodDelay,
800                                              animator->timePeriodDuration ) );
801           }
802         }
803       }
804     }
805   }
806 }
807
808 Dali::Animation Control::Impl::CreateTransition( const Toolkit::TransitionData& transitionData )
809 {
810   Dali::Animation transition;
811
812   if( transitionData.Count() > 0 )
813   {
814     AddTransitions( transition, transitionData, true );
815   }
816   return transition;
817 }
818
819
820
821 void Control::Impl::DoAction( Dali::Property::Index visualIndex, Dali::Property::Index actionId, const Dali::Property::Value attributes )
822 {
823   RegisteredVisualContainer::Iterator iter;
824   if ( FindVisual( visualIndex, mVisuals, iter ) )
825   {
826     Toolkit::GetImplementation((*iter)->visual).DoAction( actionId, attributes );
827   }
828 }
829
830 void Control::Impl::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
831 {
832   Toolkit::Control control = Toolkit::Control::DownCast( BaseHandle( object ) );
833
834   if ( control )
835   {
836     Control& controlImpl( GetImplementation( control ) );
837
838     switch ( index )
839     {
840       case Toolkit::Control::Property::STYLE_NAME:
841       {
842         controlImpl.SetStyleName( value.Get< std::string >() );
843         break;
844       }
845
846       case Toolkit::DevelControl::Property::STATE:
847       {
848         bool withTransitions=true;
849         const Property::Value* valuePtr=&value;
850         const Property::Map* map = value.GetMap();
851         if(map)
852         {
853           Property::Value* value2 = map->Find("withTransitions");
854           if( value2 )
855           {
856             withTransitions = value2->Get<bool>();
857           }
858
859           valuePtr = map->Find("state");
860         }
861
862         if( valuePtr )
863         {
864           Toolkit::DevelControl::State state( controlImpl.mImpl->mState );
865           if( Scripting::GetEnumerationProperty< Toolkit::DevelControl::State >( *valuePtr, ControlStateTable, ControlStateTableCount, state ) )
866           {
867             controlImpl.mImpl->SetState( state, withTransitions );
868           }
869         }
870       }
871       break;
872
873       case Toolkit::DevelControl::Property::SUB_STATE:
874       {
875         std::string subState;
876         if( value.Get( subState ) )
877         {
878           controlImpl.mImpl->SetSubState( subState );
879         }
880       }
881       break;
882
883       case Toolkit::DevelControl::Property::LEFT_FOCUSABLE_ACTOR_ID:
884       {
885         int focusId;
886         if( value.Get( focusId ) )
887         {
888           controlImpl.mImpl->mLeftFocusableActorId = focusId;
889         }
890       }
891       break;
892
893       case Toolkit::DevelControl::Property::RIGHT_FOCUSABLE_ACTOR_ID:
894       {
895         int focusId;
896         if( value.Get( focusId ) )
897         {
898           controlImpl.mImpl->mRightFocusableActorId = focusId;
899         }
900       }
901       break;
902
903       case Toolkit::DevelControl::Property::UP_FOCUSABLE_ACTOR_ID:
904       {
905         int focusId;
906         if( value.Get( focusId ) )
907         {
908           controlImpl.mImpl->mUpFocusableActorId = focusId;
909         }
910       }
911       break;
912
913       case Toolkit::DevelControl::Property::DOWN_FOCUSABLE_ACTOR_ID:
914       {
915         int focusId;
916         if( value.Get( focusId ) )
917         {
918           controlImpl.mImpl->mDownFocusableActorId = focusId;
919         }
920       }
921       break;
922
923       case Toolkit::Control::Property::KEY_INPUT_FOCUS:
924       {
925         if ( value.Get< bool >() )
926         {
927           controlImpl.SetKeyInputFocus();
928         }
929         else
930         {
931           controlImpl.ClearKeyInputFocus();
932         }
933         break;
934       }
935
936       case Toolkit::Control::Property::BACKGROUND:
937       {
938         std::string url;
939         Vector4 color;
940         const Property::Map* map = value.GetMap();
941         if( map && !map->Empty() )
942         {
943           controlImpl.SetBackground( *map );
944         }
945         else if( value.Get( url ) )
946         {
947           // don't know the size to load
948           Toolkit::Visual::Base visual = Toolkit::VisualFactory::Get().CreateVisual( url, ImageDimensions() );
949           if( visual )
950           {
951             controlImpl.mImpl->RegisterVisual( Toolkit::Control::Property::BACKGROUND, visual, DepthIndex::BACKGROUND );
952           }
953         }
954         else if( value.Get( color ) )
955         {
956           controlImpl.SetBackgroundColor(color);
957         }
958         else
959         {
960           // The background is an empty property map, so we should clear the background
961           controlImpl.ClearBackground();
962         }
963         break;
964       }
965
966       case Toolkit::Control::Property::MARGIN:
967       {
968         Extents margin;
969         if( value.Get( margin ) )
970         {
971           controlImpl.mImpl->SetMargin( margin );
972         }
973         break;
974       }
975
976       case Toolkit::Control::Property::PADDING:
977       {
978         Extents padding;
979         if( value.Get( padding ) )
980         {
981           controlImpl.mImpl->SetPadding( padding );
982         }
983         break;
984       }
985
986       case Toolkit::DevelControl::Property::TOOLTIP:
987       {
988         TooltipPtr& tooltipPtr = controlImpl.mImpl->mTooltip;
989         if( ! tooltipPtr )
990         {
991           tooltipPtr = Tooltip::New( control );
992         }
993         tooltipPtr->SetProperties( value );
994         break;
995       }
996
997       case Toolkit::DevelControl::Property::SHADOW:
998       {
999         const Property::Map* map = value.GetMap();
1000         if( map && !map->Empty() )
1001         {
1002           controlImpl.mImpl->SetShadow( *map );
1003         }
1004         else
1005         {
1006           // The shadow is an empty property map, so we should clear the shadow
1007           controlImpl.mImpl->ClearShadow();
1008         }
1009         break;
1010       }
1011
1012     }
1013   }
1014 }
1015
1016 Property::Value Control::Impl::GetProperty( BaseObject* object, Property::Index index )
1017 {
1018   Property::Value value;
1019
1020   Toolkit::Control control = Toolkit::Control::DownCast( BaseHandle( object ) );
1021
1022   if ( control )
1023   {
1024     Control& controlImpl( GetImplementation( control ) );
1025
1026     switch ( index )
1027     {
1028       case Toolkit::Control::Property::STYLE_NAME:
1029       {
1030         value = controlImpl.GetStyleName();
1031         break;
1032       }
1033
1034       case Toolkit::DevelControl::Property::STATE:
1035       {
1036         value = controlImpl.mImpl->mState;
1037         break;
1038       }
1039
1040       case Toolkit::DevelControl::Property::SUB_STATE:
1041       {
1042         value = controlImpl.mImpl->mSubStateName;
1043         break;
1044       }
1045
1046       case Toolkit::DevelControl::Property::LEFT_FOCUSABLE_ACTOR_ID:
1047       {
1048         value = controlImpl.mImpl->mLeftFocusableActorId;
1049         break;
1050       }
1051
1052       case Toolkit::DevelControl::Property::RIGHT_FOCUSABLE_ACTOR_ID:
1053       {
1054         value = controlImpl.mImpl->mRightFocusableActorId;
1055         break;
1056       }
1057
1058       case Toolkit::DevelControl::Property::UP_FOCUSABLE_ACTOR_ID:
1059       {
1060         value = controlImpl.mImpl->mUpFocusableActorId;
1061         break;
1062       }
1063
1064       case Toolkit::DevelControl::Property::DOWN_FOCUSABLE_ACTOR_ID:
1065       {
1066         value = controlImpl.mImpl->mDownFocusableActorId;
1067         break;
1068       }
1069
1070       case Toolkit::Control::Property::KEY_INPUT_FOCUS:
1071       {
1072         value = controlImpl.HasKeyInputFocus();
1073         break;
1074       }
1075
1076       case Toolkit::Control::Property::BACKGROUND:
1077       {
1078         Property::Map map;
1079         Toolkit::Visual::Base visual = controlImpl.mImpl->GetVisual( Toolkit::Control::Property::BACKGROUND );
1080         if( visual )
1081         {
1082           visual.CreatePropertyMap( map );
1083         }
1084
1085         value = map;
1086         break;
1087       }
1088
1089       case Toolkit::Control::Property::MARGIN:
1090       {
1091         value = controlImpl.mImpl->GetMargin();
1092         break;
1093       }
1094
1095       case Toolkit::Control::Property::PADDING:
1096       {
1097         value = controlImpl.mImpl->GetPadding();
1098         break;
1099       }
1100
1101       case Toolkit::DevelControl::Property::TOOLTIP:
1102       {
1103         Property::Map map;
1104         if( controlImpl.mImpl->mTooltip )
1105         {
1106           controlImpl.mImpl->mTooltip->CreatePropertyMap( map );
1107         }
1108         value = map;
1109         break;
1110       }
1111
1112       case Toolkit::DevelControl::Property::SHADOW:
1113       {
1114         Property::Map map;
1115         Toolkit::Visual::Base visual = controlImpl.mImpl->GetVisual( Toolkit::DevelControl::Property::SHADOW );
1116         if( visual )
1117         {
1118           visual.CreatePropertyMap( map );
1119         }
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).SetOffScene( 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::OnSceneDisconnection()
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 scene 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 scene
1378   SetVisualsOffScene( mVisuals, self );
1379
1380   // Visuals pending replacement can now be taken out of the removal list and set off scene
1381   // Iterate through all replacement visuals and add to a move queue then set off scene
1382   for( auto removalIter = mRemoveVisuals.Begin(), end = mRemoveVisuals.End(); removalIter != end; removalIter++ )
1383   {
1384     Toolkit::GetImplementation((*removalIter)->visual).SetOffScene( 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 DevelControl::VisualEventSignalType& Control::Impl::VisualEventSignal()
1438 {
1439   return mVisualEventSignal;
1440 }
1441
1442 void Control::Impl::SetShadow( const Property::Map& map )
1443 {
1444   Toolkit::Visual::Base visual = Toolkit::VisualFactory::Get().CreateVisual( map );
1445   visual.SetName("shadow");
1446
1447   if( visual )
1448   {
1449     mControlImpl.mImpl->RegisterVisual( Toolkit::DevelControl::Property::SHADOW, visual, DepthIndex::BACKGROUND_EFFECT );
1450
1451     mControlImpl.RelayoutRequest();
1452   }
1453 }
1454
1455 void Control::Impl::ClearShadow()
1456 {
1457    mControlImpl.mImpl->UnregisterVisual( Toolkit::DevelControl::Property::SHADOW );
1458
1459    // Trigger a size negotiation request that may be needed when unregistering a visual.
1460    mControlImpl.RelayoutRequest();
1461 }
1462
1463 void Control::Impl::EmitResourceReadySignal()
1464 {
1465   if(!mIsEmittingResourceReadySignal)
1466   {
1467     // Guard against calls to emit the signal during the callback
1468     mIsEmittingResourceReadySignal = true;
1469
1470     // If the signal handler changes visual, it may become ready during this call & therefore this method will
1471     // get called again recursively. If so, mNeedToEmitResourceReady is set below, and we act on it after that secondary
1472     // invocation has completed by notifying in an Idle callback to prevent further recursion.
1473     Dali::Toolkit::Control handle(mControlImpl.GetOwner());
1474     mResourceReadySignal.Emit(handle);
1475
1476     if(mNeedToEmitResourceReady)
1477     {
1478       // Add idler to emit the signal again
1479       if(!mIdleCallback)
1480       {
1481         // The callback manager takes the ownership of the callback object.
1482         mIdleCallback = MakeCallback( this, &Control::Impl::OnIdleCallback);
1483         Adaptor::Get().AddIdle(mIdleCallback, false);
1484       }
1485     }
1486
1487     mIsEmittingResourceReadySignal = false;
1488   }
1489   else
1490   {
1491     mNeedToEmitResourceReady = true;
1492   }
1493 }
1494
1495 void Control::Impl::OnIdleCallback()
1496 {
1497   if(mNeedToEmitResourceReady)
1498   {
1499     // Reset the flag
1500     mNeedToEmitResourceReady = false;
1501
1502     // A visual is ready so control may need relayouting if staged
1503     if(mControlImpl.Self().GetProperty<bool>(Actor::Property::CONNECTED_TO_SCENE))
1504     {
1505       mControlImpl.RelayoutRequest();
1506     }
1507
1508     EmitResourceReadySignal();
1509   }
1510
1511   // Set the pointer to null as the callback manager deletes the callback after execute it.
1512   mIdleCallback = nullptr;
1513 }
1514
1515 } // namespace Internal
1516
1517 } // namespace Toolkit
1518
1519 } // namespace Dali