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