Added GetTypeInfo to get registered type of a control wrapper
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / controls / control / control-data-impl.cpp
1 /*
2  * Copyright (c) 2017 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/public-api/common/dali-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/devel-api/controls/control-depth-index-ranges.h>
35 #include <dali-toolkit/internal/styling/style-manager-impl.h>
36 #include <dali-toolkit/public-api/visuals/image-visual-properties.h>
37 #include <dali-toolkit/devel-api/visuals/visual-properties-devel.h>
38 #include <dali-toolkit/internal/visuals/visual-string-constants.h>
39 #include <dali-toolkit/devel-api/controls/control-devel.h>
40 #include <dali-toolkit/devel-api/controls/control-wrapper-impl.h>
41
42 namespace Dali
43 {
44
45 namespace Toolkit
46 {
47
48 namespace Internal
49 {
50
51 extern const Dali::Scripting::StringEnum ControlStateTable[];
52 extern const unsigned int ControlStateTableCount;
53
54
55 // Not static or anonymous - shared with other translation units
56 const Scripting::StringEnum ControlStateTable[] = {
57   { "NORMAL",   Toolkit::DevelControl::NORMAL   },
58   { "FOCUSED",  Toolkit::DevelControl::FOCUSED  },
59   { "DISABLED", Toolkit::DevelControl::DISABLED },
60 };
61 const unsigned int ControlStateTableCount = sizeof( ControlStateTable ) / sizeof( ControlStateTable[0] );
62
63
64
65 namespace
66 {
67
68 #if defined(DEBUG_ENABLED)
69 Debug::Filter* gLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_CONTROL_VISUALS");
70 #endif
71
72
73 template<typename T>
74 void Remove( Dictionary<T>& keyValues, const std::string& name )
75 {
76   keyValues.Remove(name);
77 }
78
79 void Remove( DictionaryKeys& keys, const std::string& name )
80 {
81   DictionaryKeys::iterator iter = std::find( keys.begin(), keys.end(), name );
82   if( iter != keys.end())
83   {
84     keys.erase(iter);
85   }
86 }
87
88 Toolkit::DevelVisual::Type GetVisualTypeFromMap( const Property::Map& map )
89 {
90   Property::Value* typeValue = map.Find( Toolkit::DevelVisual::Property::TYPE, VISUAL_TYPE  );
91   Toolkit::DevelVisual::Type type = Toolkit::DevelVisual::IMAGE;
92   if( typeValue )
93   {
94     Scripting::GetEnumerationProperty( *typeValue, VISUAL_TYPE_TABLE, VISUAL_TYPE_TABLE_COUNT, type );
95   }
96   return type;
97 }
98
99 /**
100  *  Finds visual in given array, returning true if found along with the iterator for that visual as a out parameter
101  */
102 bool FindVisual( Property::Index targetIndex, const RegisteredVisualContainer& visuals, RegisteredVisualContainer::Iterator& iter )
103 {
104   for ( iter = visuals.Begin(); iter != visuals.End(); iter++ )
105   {
106     if ( (*iter)->index ==  targetIndex )
107     {
108       return true;
109     }
110   }
111   return false;
112 }
113
114 void FindChangableVisuals( Dictionary<Property::Map>& stateVisualsToAdd,
115                            Dictionary<Property::Map>& stateVisualsToChange,
116                            DictionaryKeys& stateVisualsToRemove)
117 {
118   DictionaryKeys copyOfStateVisualsToRemove = stateVisualsToRemove;
119
120   for( DictionaryKeys::iterator iter = copyOfStateVisualsToRemove.begin();
121        iter != copyOfStateVisualsToRemove.end(); ++iter )
122   {
123     const std::string& visualName = (*iter);
124     Property::Map* toMap = stateVisualsToAdd.Find( visualName );
125     if( toMap )
126     {
127       stateVisualsToChange.Add( visualName, *toMap );
128       stateVisualsToAdd.Remove( visualName );
129       Remove( stateVisualsToRemove, visualName );
130     }
131   }
132 }
133
134 Toolkit::Visual::Base GetVisualByName(
135   const RegisteredVisualContainer& visuals,
136   const std::string& visualName )
137 {
138   Toolkit::Visual::Base visualHandle;
139
140   RegisteredVisualContainer::Iterator iter;
141   for ( iter = visuals.Begin(); iter != visuals.End(); iter++ )
142   {
143     Toolkit::Visual::Base visual = (*iter)->visual;
144     if( visual && visual.GetName() == visualName )
145     {
146       visualHandle = visual;
147       break;
148     }
149   }
150   return visualHandle;
151 }
152
153 /**
154  * Performs actions as requested using the action name.
155  * @param[in] object The object on which to perform the action.
156  * @param[in] actionName The action to perform.
157  * @param[in] attributes The attributes with which to perfrom this action.
158  * @return true if action has been accepted by this control
159  */
160 const char* ACTION_ACCESSIBILITY_ACTIVATED = "accessibilityActivated";
161 static bool DoAction( BaseObject* object, const std::string& actionName, const Property::Map& attributes )
162 {
163   bool ret = false;
164
165   if( object && ( 0 == strcmp( actionName.c_str(), ACTION_ACCESSIBILITY_ACTIVATED ) ) )
166   {
167     Toolkit::Control control = Toolkit::Control::DownCast( BaseHandle( object ) );
168     if( control )
169     {
170       // if cast succeeds there is an implementation so no need to check
171       ret = Internal::GetImplementation( control ).OnAccessibilityActivated();
172     }
173   }
174
175   return ret;
176 }
177
178 /**
179  * Connects a callback function with the object's signals.
180  * @param[in] object The object providing the signal.
181  * @param[in] tracker Used to disconnect the signal.
182  * @param[in] signalName The signal to connect to.
183  * @param[in] functor A newly allocated FunctorDelegate.
184  * @return True if the signal was connected.
185  * @post If a signal was connected, ownership of functor was passed to CallbackBase. Otherwise the caller is responsible for deleting the unused functor.
186  */
187 const char* SIGNAL_KEY_EVENT = "keyEvent";
188 const char* SIGNAL_KEY_INPUT_FOCUS_GAINED = "keyInputFocusGained";
189 const char* SIGNAL_KEY_INPUT_FOCUS_LOST = "keyInputFocusLost";
190 const char* SIGNAL_TAPPED = "tapped";
191 const char* SIGNAL_PANNED = "panned";
192 const char* SIGNAL_PINCHED = "pinched";
193 const char* SIGNAL_LONG_PRESSED = "longPressed";
194 static bool DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
195 {
196   Dali::BaseHandle handle( object );
197
198   bool connected( false );
199   Toolkit::Control control = Toolkit::Control::DownCast( handle );
200   if ( control )
201   {
202     Internal::Control& controlImpl( Internal::GetImplementation( control ) );
203     connected = true;
204
205     if ( 0 == strcmp( signalName.c_str(), SIGNAL_KEY_EVENT ) )
206     {
207       controlImpl.KeyEventSignal().Connect( tracker, functor );
208     }
209     else if( 0 == strcmp( signalName.c_str(), SIGNAL_KEY_INPUT_FOCUS_GAINED ) )
210     {
211       controlImpl.KeyInputFocusGainedSignal().Connect( tracker, functor );
212     }
213     else if( 0 == strcmp( signalName.c_str(), SIGNAL_KEY_INPUT_FOCUS_LOST ) )
214     {
215       controlImpl.KeyInputFocusLostSignal().Connect( tracker, functor );
216     }
217     else if( 0 == strcmp( signalName.c_str(), SIGNAL_TAPPED ) )
218     {
219       controlImpl.EnableGestureDetection( Gesture::Tap );
220       controlImpl.GetTapGestureDetector().DetectedSignal().Connect( tracker, functor );
221     }
222     else if( 0 == strcmp( signalName.c_str(), SIGNAL_PANNED ) )
223     {
224       controlImpl.EnableGestureDetection( Gesture::Pan );
225       controlImpl.GetPanGestureDetector().DetectedSignal().Connect( tracker, functor );
226     }
227     else if( 0 == strcmp( signalName.c_str(), SIGNAL_PINCHED ) )
228     {
229       controlImpl.EnableGestureDetection( Gesture::Pinch );
230       controlImpl.GetPinchGestureDetector().DetectedSignal().Connect( tracker, functor );
231     }
232     else if( 0 == strcmp( signalName.c_str(), SIGNAL_LONG_PRESSED ) )
233     {
234       controlImpl.EnableGestureDetection( Gesture::LongPress );
235       controlImpl.GetLongPressGestureDetector().DetectedSignal().Connect( tracker, functor );
236     }
237   }
238   return connected;
239 }
240
241 /**
242  * Creates control through type registry
243  */
244 BaseHandle Create()
245 {
246   return Internal::Control::New();
247 }
248 // Setup signals and actions using the type-registry.
249 DALI_TYPE_REGISTRATION_BEGIN( Control, CustomActor, Create );
250
251 // Note: Properties are registered separately below.
252
253 SignalConnectorType registerSignal1( typeRegistration, SIGNAL_KEY_EVENT, &DoConnectSignal );
254 SignalConnectorType registerSignal2( typeRegistration, SIGNAL_KEY_INPUT_FOCUS_GAINED, &DoConnectSignal );
255 SignalConnectorType registerSignal3( typeRegistration, SIGNAL_KEY_INPUT_FOCUS_LOST, &DoConnectSignal );
256 SignalConnectorType registerSignal4( typeRegistration, SIGNAL_TAPPED, &DoConnectSignal );
257 SignalConnectorType registerSignal5( typeRegistration, SIGNAL_PANNED, &DoConnectSignal );
258 SignalConnectorType registerSignal6( typeRegistration, SIGNAL_PINCHED, &DoConnectSignal );
259 SignalConnectorType registerSignal7( typeRegistration, SIGNAL_LONG_PRESSED, &DoConnectSignal );
260
261 TypeAction registerAction( typeRegistration, ACTION_ACCESSIBILITY_ACTIVATED, &DoAction );
262
263 DALI_TYPE_REGISTRATION_END()
264
265 } // unnamed namespace
266
267
268 // Properties registered without macro to use specific member variables.
269 const PropertyRegistration Control::Impl::PROPERTY_1( typeRegistration, "styleName",              Toolkit::Control::Property::STYLE_NAME,                   Property::STRING,  &Control::Impl::SetProperty, &Control::Impl::GetProperty );
270 const PropertyRegistration Control::Impl::PROPERTY_2( typeRegistration, "backgroundColor",        Toolkit::Control::Property::BACKGROUND_COLOR,             Property::VECTOR4, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
271 const PropertyRegistration Control::Impl::PROPERTY_3( typeRegistration, "backgroundImage",        Toolkit::Control::Property::BACKGROUND_IMAGE,             Property::MAP,     &Control::Impl::SetProperty, &Control::Impl::GetProperty );
272 const PropertyRegistration Control::Impl::PROPERTY_4( typeRegistration, "keyInputFocus",          Toolkit::Control::Property::KEY_INPUT_FOCUS,              Property::BOOLEAN, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
273 const PropertyRegistration Control::Impl::PROPERTY_5( typeRegistration, "background",             Toolkit::Control::Property::BACKGROUND,                   Property::MAP,     &Control::Impl::SetProperty, &Control::Impl::GetProperty );
274 const PropertyRegistration Control::Impl::PROPERTY_6( typeRegistration, "tooltip",                Toolkit::DevelControl::Property::TOOLTIP,                 Property::MAP,     &Control::Impl::SetProperty, &Control::Impl::GetProperty );
275 const PropertyRegistration Control::Impl::PROPERTY_7( typeRegistration, "state",                  Toolkit::DevelControl::Property::STATE,                   Property::STRING,  &Control::Impl::SetProperty, &Control::Impl::GetProperty );
276 const PropertyRegistration Control::Impl::PROPERTY_8( typeRegistration, "subState",               Toolkit::DevelControl::Property::SUB_STATE,               Property::STRING,  &Control::Impl::SetProperty, &Control::Impl::GetProperty );
277 const PropertyRegistration Control::Impl::PROPERTY_9( typeRegistration, "leftFocusableActorId",   Toolkit::DevelControl::Property::LEFT_FOCUSABLE_ACTOR_ID, Property::INTEGER, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
278 const PropertyRegistration Control::Impl::PROPERTY_10( typeRegistration, "rightFocusableActorId", Toolkit::DevelControl::Property::RIGHT_FOCUSABLE_ACTOR_ID,Property::INTEGER, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
279 const PropertyRegistration Control::Impl::PROPERTY_11( typeRegistration, "upFocusableActorId",    Toolkit::DevelControl::Property::UP_FOCUSABLE_ACTOR_ID,   Property::INTEGER, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
280 const PropertyRegistration Control::Impl::PROPERTY_12( typeRegistration, "downFocusableActorId",  Toolkit::DevelControl::Property::DOWN_FOCUSABLE_ACTOR_ID, Property::INTEGER, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
281
282
283
284 Control::Impl::Impl( Control& controlImpl )
285 : mControlImpl( controlImpl ),
286   mState( Toolkit::DevelControl::NORMAL ),
287   mSubStateName(""),
288   mLeftFocusableActorId( -1 ),
289   mRightFocusableActorId( -1 ),
290   mUpFocusableActorId( -1 ),
291   mDownFocusableActorId( -1 ),
292   mStyleName(""),
293   mBackgroundColor(Color::TRANSPARENT),
294   mStartingPinchScale( NULL ),
295   mKeyEventSignal(),
296   mPinchGestureDetector(),
297   mPanGestureDetector(),
298   mTapGestureDetector(),
299   mLongPressGestureDetector(),
300   mFlags( Control::ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ),
301   mIsKeyboardNavigationSupported( false ),
302   mIsKeyboardFocusGroup( false )
303 {
304
305 }
306
307 Control::Impl::~Impl()
308 {
309   // All gesture detectors will be destroyed so no need to disconnect.
310   delete mStartingPinchScale;
311 }
312
313 Control::Impl& Control::Impl::Get( Internal::Control& internalControl )
314 {
315   return *internalControl.mImpl;
316 }
317
318 const Control::Impl& Control::Impl::Get( const Internal::Control& internalControl )
319 {
320   return *internalControl.mImpl;
321 }
322
323 // Gesture Detection Methods
324 void Control::Impl::PinchDetected(Actor actor, const PinchGesture& pinch)
325 {
326   mControlImpl.OnPinch(pinch);
327 }
328
329 void Control::Impl::PanDetected(Actor actor, const PanGesture& pan)
330 {
331   mControlImpl.OnPan(pan);
332 }
333
334 void Control::Impl::TapDetected(Actor actor, const TapGesture& tap)
335 {
336   mControlImpl.OnTap(tap);
337 }
338
339 void Control::Impl::LongPressDetected(Actor actor, const LongPressGesture& longPress)
340 {
341   mControlImpl.OnLongPress(longPress);
342 }
343
344 // Called by a Visual when it's resource is ready
345 void Control::Impl::ResourceReady( Visual::Base& object)
346 {
347
348   // go through and check if all the visuals are ready, if they are emit a signal
349   for ( RegisteredVisualContainer::ConstIterator visualIter = mVisuals.Begin();
350         visualIter != mVisuals.End(); ++visualIter )
351   {
352     const Toolkit::Visual::Base visual = (*visualIter)->visual;
353     const Internal::Visual::Base& visualImpl = Toolkit::GetImplementation( visual );
354
355     // one of the visuals is not ready
356     if( !visualImpl.IsResourceReady() )
357     {
358       return;
359     }
360   }
361
362   // all the visuals are ready
363   Dali::Toolkit::Control handle( mControlImpl.GetOwner() );
364   mResourceReadySignal.Emit( handle );
365
366 }
367
368 bool Control::Impl::IsResourceReady() const
369 {
370   // go through and check all the visuals are ready
371   for ( RegisteredVisualContainer::ConstIterator visualIter = mVisuals.Begin();
372          visualIter != mVisuals.End(); ++visualIter )
373    {
374      const Toolkit::Visual::Base visual = (*visualIter)->visual;
375      const Internal::Visual::Base& visualImpl = Toolkit::GetImplementation( visual );
376
377      // one of the visuals is not ready
378      if( !visualImpl.IsResourceReady()  )
379      {
380        return false;
381      }
382    }
383   return true;
384 }
385
386 void Control::Impl::RegisterVisual( Property::Index index, Toolkit::Visual::Base& visual )
387 {
388   RegisterVisual( index, visual, VisualState::ENABLED, DepthIndexValue::NOT_SET );
389 }
390
391 void Control::Impl::RegisterVisual( Property::Index index, Toolkit::Visual::Base& visual, int depthIndex )
392 {
393   RegisterVisual( index, visual, VisualState::ENABLED, DepthIndexValue::SET, depthIndex );
394 }
395
396 void Control::Impl::RegisterVisual( Property::Index index, Toolkit::Visual::Base& visual, bool enabled )
397 {
398   RegisterVisual( index, visual, ( enabled ? VisualState::ENABLED : VisualState::DISABLED ), DepthIndexValue::NOT_SET );
399 }
400
401 void Control::Impl::RegisterVisual( Property::Index index, Toolkit::Visual::Base& visual, bool enabled, int depthIndex )
402 {
403   RegisterVisual( index, visual, ( enabled ? VisualState::ENABLED : VisualState::DISABLED ), DepthIndexValue::SET, depthIndex );
404 }
405
406 void Control::Impl::RegisterVisual( Property::Index index, Toolkit::Visual::Base& visual, VisualState::Type enabled, DepthIndexValue::Type depthIndexValueSet, int depthIndex )
407 {
408   bool visualReplaced ( false );
409   Actor self = mControlImpl.Self();
410
411   if( !mVisuals.Empty() )
412   {
413     RegisteredVisualContainer::Iterator iter;
414     // Check if visual (index) is already registered.  Replace if so.
415     if ( FindVisual( index, mVisuals, iter ) )
416     {
417       if( (*iter)->visual && self.OnStage() )
418       {
419         Toolkit::GetImplementation((*iter)->visual).SetOffStage( self );
420       }
421
422       // 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
423       if( ( depthIndexValueSet == DepthIndexValue::NOT_SET ) &&
424           ( visual.GetDepthIndex() == 0 ) )
425       {
426         const int currentDepthIndex = (*iter)->visual.GetDepthIndex();
427         visual.SetDepthIndex( currentDepthIndex );
428       }
429
430       StopObservingVisual( (*iter)->visual );
431       StartObservingVisual( visual );
432
433       (*iter)->visual = visual;
434       (*iter)->enabled = ( enabled == VisualState::ENABLED ) ? true : false;
435       visualReplaced = true;
436     }
437   }
438
439   // If not set, set the name of the visual to the same name as the control's property.
440   // ( If the control has been type registered )
441   if( visual.GetName().empty() )
442   {
443     try
444     {
445       std::string visualName = self.GetPropertyName( index );
446       if( !visualName.empty() )
447       {
448         DALI_LOG_INFO( gLogFilter, Debug::Concise, "Setting visual name for property %d to %s\n",
449                        index, visualName.c_str() );
450         visual.SetName( visualName );
451       }
452     }
453     catch( Dali::DaliException e )
454     {
455       DALI_LOG_WARNING( "Attempting to register visual without a registered property, index: %d\n", index );
456     }
457   }
458
459   if( !visualReplaced ) // New registration entry
460   {
461     mVisuals.PushBack( new RegisteredVisual( index, visual, ( enabled == VisualState::ENABLED ? true : false ) ) );
462
463     // monitor when the visuals resources are ready
464     StartObservingVisual( visual );
465
466     // 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
467     if( ( depthIndexValueSet == DepthIndexValue::NOT_SET ) &&
468         ( mVisuals.Size() > 1 ) &&
469         ( visual.GetDepthIndex() == 0 ) )
470     {
471       int maxDepthIndex = std::numeric_limits< int >::min();
472
473       RegisteredVisualContainer::ConstIterator iter;
474       const RegisteredVisualContainer::ConstIterator endIter = mVisuals.End();
475       for ( iter = mVisuals.Begin(); iter != endIter; iter++ )
476       {
477         const int visualDepthIndex = (*iter)->visual.GetDepthIndex();
478         if ( visualDepthIndex > maxDepthIndex )
479         {
480           maxDepthIndex = visualDepthIndex;
481         }
482       }
483
484       ++maxDepthIndex; // Add one to the current maximum depth index so that our added visual appears on top
485       visual.SetDepthIndex( maxDepthIndex );
486     }
487   }
488
489   if( visual )
490   {
491     // If the caller has set the depth-index, then set it here
492     if( depthIndexValueSet == DepthIndexValue::SET )
493     {
494       visual.SetDepthIndex( depthIndex );
495     }
496
497     // Put on stage if enabled and the control is already on the stage
498     if( ( enabled == VisualState::ENABLED ) && self.OnStage() )
499     {
500       Toolkit::GetImplementation(visual).SetOnStage( self );
501     }
502   }
503
504   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::RegisterVisual() Registered %s(%d), enabled:%s\n",  visual.GetName().c_str(), index, enabled?"T":"F" );
505 }
506
507 void Control::Impl::UnregisterVisual( Property::Index index )
508 {
509    RegisteredVisualContainer::Iterator iter;
510    if ( FindVisual( index, mVisuals, iter ) )
511    {
512      // stop observing visual
513      StopObservingVisual( (*iter)->visual );
514
515      Actor self( mControlImpl.Self() );
516      Toolkit::GetImplementation((*iter)->visual).SetOffStage( self );
517      (*iter)->visual.Reset();
518      mVisuals.Erase( iter );
519    }
520 }
521
522 Toolkit::Visual::Base Control::Impl::GetVisual( Property::Index index ) const
523 {
524   RegisteredVisualContainer::Iterator iter;
525   if ( FindVisual( index, mVisuals, iter ) )
526   {
527     return (*iter)->visual;
528   }
529
530   return Toolkit::Visual::Base();
531 }
532
533 void Control::Impl::EnableVisual( Property::Index index, bool enable )
534 {
535   RegisteredVisualContainer::Iterator iter;
536   if ( FindVisual( index, mVisuals, iter ) )
537   {
538     if (  (*iter)->enabled == enable )
539     {
540       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::EnableVisual Visual %s(%d) already %s\n", (*iter)->visual.GetName().c_str(), index, enable?"enabled":"disabled");
541       return;
542     }
543
544     (*iter)->enabled = enable;
545     Actor parentActor = mControlImpl.Self();
546     if ( mControlImpl.Self().OnStage() ) // If control not on Stage then Visual will be added when StageConnection is called.
547     {
548       if ( enable )
549       {
550         DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::EnableVisual Setting %s(%d) on stage \n", (*iter)->visual.GetName().c_str(), index );
551         Toolkit::GetImplementation((*iter)->visual).SetOnStage( parentActor );
552       }
553       else
554       {
555         DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::EnableVisual Setting %s(%d) off stage \n", (*iter)->visual.GetName().c_str(), index );
556         Toolkit::GetImplementation((*iter)->visual).SetOffStage( parentActor );  // No need to call if control not staged.
557       }
558     }
559   }
560 }
561
562 bool Control::Impl::IsVisualEnabled( Property::Index index ) const
563 {
564   RegisteredVisualContainer::Iterator iter;
565   if ( FindVisual( index, mVisuals, iter ) )
566   {
567     return (*iter)->enabled;
568   }
569   return false;
570 }
571
572 void Control::Impl::StopObservingVisual( Toolkit::Visual::Base& visual )
573 {
574   Internal::Visual::Base& visualImpl = Toolkit::GetImplementation( visual );
575
576   // Stop observing the visual
577   visualImpl.RemoveResourceObserver( *this );
578 }
579
580 void Control::Impl::StartObservingVisual( Toolkit::Visual::Base& visual)
581 {
582   Internal::Visual::Base& visualImpl = Toolkit::GetImplementation( visual );
583
584   // start observing the visual for resource ready
585   visualImpl.AddResourceObserver( *this );
586 }
587
588 Dali::Animation Control::Impl::CreateTransition( const Toolkit::TransitionData& handle )
589 {
590   Dali::Animation transition;
591   const Internal::TransitionData& transitionData = Toolkit::GetImplementation( handle );
592
593   if( transitionData.Count() > 0 )
594   {
595     // Setup a Transition from TransitionData.
596     TransitionData::Iterator end = transitionData.End();
597     for( TransitionData::Iterator iter = transitionData.Begin() ;
598          iter != end; ++iter )
599     {
600       TransitionData::Animator* animator = (*iter);
601
602       Toolkit::Visual::Base visual = GetVisualByName( mVisuals, animator->objectName );
603
604       if( visual )
605       {
606 #if defined(DEBUG_ENABLED)
607         Dali::TypeInfo typeInfo;
608         ControlWrapper* controlWrapperImpl = dynamic_cast<ControlWrapper*>(&mControlImpl);
609         if( controlWrapperImpl )
610         {
611           typeInfo = controlWrapperImpl->GetTypeInfo();
612         }
613
614         DALI_LOG_INFO( gLogFilter, Debug::Concise, "CreateTransition: Found %s visual for %s\n",
615                        visual.GetName().c_str(), typeInfo?typeInfo.GetName().c_str():"Unknown" );
616 #endif
617         Internal::Visual::Base& visualImpl = Toolkit::GetImplementation( visual );
618         visualImpl.AnimateProperty( transition, *animator );
619       }
620       else
621       {
622         DALI_LOG_INFO( gLogFilter, Debug::Concise, "CreateTransition: Could not find visual. Trying actors");
623         // Otherwise, try any actor children of control (Including the control)
624         Actor child = mControlImpl.Self().FindChildByName( animator->objectName );
625         if( child )
626         {
627           Property::Index propertyIndex = DevelHandle::GetPropertyIndex( child, animator->propertyKey );
628           if( propertyIndex != Property::INVALID_INDEX )
629           {
630             if( animator->animate == false )
631             {
632               if( animator->targetValue.GetType() != Property::NONE )
633               {
634                 child.SetProperty( propertyIndex, animator->targetValue );
635               }
636             }
637             else // animate the property
638             {
639               if( animator->initialValue.GetType() != Property::NONE )
640               {
641                 child.SetProperty( propertyIndex, animator->initialValue );
642               }
643
644               if( ! transition )
645               {
646                 transition = Dali::Animation::New( 0.1f );
647               }
648
649               transition.AnimateTo( Property( child, propertyIndex ),
650                                     animator->targetValue,
651                                     animator->alphaFunction,
652                                     TimePeriod( animator->timePeriodDelay,
653                                                 animator->timePeriodDuration ) );
654             }
655           }
656         }
657       }
658     }
659   }
660
661   return transition;
662 }
663
664 void Control::Impl::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
665 {
666   Toolkit::Control control = Toolkit::Control::DownCast( BaseHandle( object ) );
667
668   if ( control )
669   {
670     Control& controlImpl( GetImplementation( control ) );
671
672     switch ( index )
673     {
674       case Toolkit::Control::Property::STYLE_NAME:
675       {
676         controlImpl.SetStyleName( value.Get< std::string >() );
677         break;
678       }
679
680       case Toolkit::DevelControl::Property::STATE:
681       {
682         bool withTransitions=true;
683         const Property::Value* valuePtr=&value;
684         Property::Map* map = value.GetMap();
685         if(map)
686         {
687           Property::Value* value2 = map->Find("withTransitions");
688           if( value2 )
689           {
690             withTransitions = value2->Get<bool>();
691           }
692
693           valuePtr = map->Find("state");
694         }
695
696         if( valuePtr )
697         {
698           Toolkit::DevelControl::State state( controlImpl.mImpl->mState );
699           if( Scripting::GetEnumerationProperty< Toolkit::DevelControl::State >( *valuePtr, ControlStateTable, ControlStateTableCount, state ) )
700           {
701             controlImpl.mImpl->SetState( state, withTransitions );
702           }
703         }
704       }
705       break;
706
707       case Toolkit::DevelControl::Property::SUB_STATE:
708       {
709         std::string subState;
710         if( value.Get( subState ) )
711         {
712           controlImpl.mImpl->SetSubState( subState );
713         }
714       }
715       break;
716
717       case Toolkit::DevelControl::Property::LEFT_FOCUSABLE_ACTOR_ID:
718       {
719         int focusId;
720         if( value.Get( focusId ) )
721         {
722           controlImpl.mImpl->mLeftFocusableActorId = focusId;
723         }
724       }
725       break;
726
727       case Toolkit::DevelControl::Property::RIGHT_FOCUSABLE_ACTOR_ID:
728       {
729         int focusId;
730         if( value.Get( focusId ) )
731         {
732           controlImpl.mImpl->mRightFocusableActorId = focusId;
733         }
734       }
735       break;
736
737       case Toolkit::DevelControl::Property::UP_FOCUSABLE_ACTOR_ID:
738       {
739         int focusId;
740         if( value.Get( focusId ) )
741         {
742           controlImpl.mImpl->mUpFocusableActorId = focusId;
743         }
744       }
745       break;
746
747       case Toolkit::DevelControl::Property::DOWN_FOCUSABLE_ACTOR_ID:
748       {
749         int focusId;
750         if( value.Get( focusId ) )
751         {
752           controlImpl.mImpl->mDownFocusableActorId = focusId;
753         }
754       }
755       break;
756
757       case Toolkit::Control::Property::BACKGROUND_COLOR:
758       {
759         DALI_LOG_WARNING( "BACKGROUND_COLOR property is deprecated. Use BACKGROUND property instead\n" );
760         controlImpl.SetBackgroundColor( value.Get< Vector4 >() );
761         break;
762       }
763
764       case Toolkit::Control::Property::BACKGROUND_IMAGE:
765       {
766         DALI_LOG_WARNING( "BACKGROUND_IMAGE property is deprecated. Use BACKGROUND property instead\n" );
767         Image image = Scripting::NewImage( value );
768         if ( image )
769         {
770           controlImpl.SetBackgroundImage( image );
771         }
772         else
773         {
774           // An empty image means the background is no longer required
775           controlImpl.ClearBackground();
776         }
777         break;
778       }
779
780       case Toolkit::Control::Property::KEY_INPUT_FOCUS:
781       {
782         if ( value.Get< bool >() )
783         {
784           controlImpl.SetKeyInputFocus();
785         }
786         else
787         {
788           controlImpl.ClearKeyInputFocus();
789         }
790         break;
791       }
792
793       case Toolkit::Control::Property::BACKGROUND:
794       {
795         std::string url;
796         Vector4 color;
797         const Property::Map* map = value.GetMap();
798         if( map && !map->Empty() )
799         {
800           controlImpl.SetBackground( *map );
801         }
802         else if( value.Get( url ) )
803         {
804           // don't know the size to load
805           Toolkit::Visual::Base visual = Toolkit::VisualFactory::Get().CreateVisual( url, ImageDimensions() );
806           if( visual )
807           {
808             controlImpl.mImpl->RegisterVisual( Toolkit::Control::Property::BACKGROUND, visual, DepthIndex::BACKGROUND );
809           }
810         }
811         else if( value.Get( color ) )
812         {
813           controlImpl.SetBackgroundColor(color);
814         }
815         else
816         {
817           // The background is an empty property map, so we should clear the background
818           controlImpl.ClearBackground();
819         }
820         break;
821       }
822
823       case Toolkit::DevelControl::Property::TOOLTIP:
824       {
825         TooltipPtr& tooltipPtr = controlImpl.mImpl->mTooltip;
826         if( ! tooltipPtr )
827         {
828           tooltipPtr = Tooltip::New( control );
829         }
830         tooltipPtr->SetProperties( value );
831       }
832     }
833   }
834 }
835
836 Property::Value Control::Impl::GetProperty( BaseObject* object, Property::Index index )
837 {
838   Property::Value value;
839
840   Toolkit::Control control = Toolkit::Control::DownCast( BaseHandle( object ) );
841
842   if ( control )
843   {
844     Control& controlImpl( GetImplementation( control ) );
845
846     switch ( index )
847     {
848       case Toolkit::Control::Property::STYLE_NAME:
849       {
850         value = controlImpl.GetStyleName();
851         break;
852       }
853
854       case Toolkit::DevelControl::Property::STATE:
855       {
856         value = controlImpl.mImpl->mState;
857         break;
858       }
859
860       case Toolkit::DevelControl::Property::SUB_STATE:
861       {
862         value = controlImpl.mImpl->mSubStateName;
863         break;
864       }
865
866       case Toolkit::DevelControl::Property::LEFT_FOCUSABLE_ACTOR_ID:
867       {
868         value = controlImpl.mImpl->mLeftFocusableActorId;
869         break;
870       }
871
872       case Toolkit::DevelControl::Property::RIGHT_FOCUSABLE_ACTOR_ID:
873       {
874         value = controlImpl.mImpl->mRightFocusableActorId;
875         break;
876       }
877
878       case Toolkit::DevelControl::Property::UP_FOCUSABLE_ACTOR_ID:
879       {
880         value = controlImpl.mImpl->mUpFocusableActorId;
881         break;
882       }
883
884       case Toolkit::DevelControl::Property::DOWN_FOCUSABLE_ACTOR_ID:
885       {
886         value = controlImpl.mImpl->mDownFocusableActorId;
887         break;
888       }
889
890       case Toolkit::Control::Property::BACKGROUND_COLOR:
891       {
892         DALI_LOG_WARNING( "BACKGROUND_COLOR property is deprecated. Use BACKGROUND property instead\n" );
893         value = controlImpl.GetBackgroundColor();
894         break;
895       }
896
897       case Toolkit::Control::Property::BACKGROUND_IMAGE:
898       {
899         DALI_LOG_WARNING( "BACKGROUND_IMAGE property is deprecated. Use BACKGROUND property instead\n" );
900         Property::Map map;
901         Toolkit::Visual::Base visual = controlImpl.mImpl->GetVisual( Toolkit::Control::Property::BACKGROUND );
902         if( visual )
903         {
904           visual.CreatePropertyMap( map );
905         }
906         value = map;
907         break;
908       }
909
910       case Toolkit::Control::Property::KEY_INPUT_FOCUS:
911       {
912         value = controlImpl.HasKeyInputFocus();
913         break;
914       }
915
916       case Toolkit::Control::Property::BACKGROUND:
917       {
918         Property::Map map;
919         Toolkit::Visual::Base visual = controlImpl.mImpl->GetVisual( Toolkit::Control::Property::BACKGROUND );
920         if( visual )
921         {
922           visual.CreatePropertyMap( map );
923         }
924
925         value = map;
926         break;
927       }
928
929       case Toolkit::DevelControl::Property::TOOLTIP:
930       {
931         Property::Map map;
932         if( controlImpl.mImpl->mTooltip )
933         {
934           controlImpl.mImpl->mTooltip->CreatePropertyMap( map );
935         }
936         value = map;
937         break;
938       }
939
940     }
941   }
942
943   return value;
944 }
945
946
947 void  Control::Impl::CopyInstancedProperties( RegisteredVisualContainer& visuals, Dictionary<Property::Map>& instancedProperties )
948 {
949   for(RegisteredVisualContainer::Iterator iter = visuals.Begin(); iter!= visuals.End(); iter++)
950   {
951     if( (*iter)->visual )
952     {
953       Property::Map instanceMap;
954       Toolkit::GetImplementation((*iter)->visual).CreateInstancePropertyMap(instanceMap);
955       instancedProperties.Add( (*iter)->visual.GetName(), instanceMap );
956     }
957   }
958 }
959
960
961 void Control::Impl::RemoveVisual( RegisteredVisualContainer& visuals, const std::string& visualName )
962 {
963   Actor self( mControlImpl.Self() );
964
965   for ( RegisteredVisualContainer::Iterator visualIter = visuals.Begin();
966         visualIter != visuals.End(); ++visualIter )
967   {
968     Toolkit::Visual::Base visual = (*visualIter)->visual;
969     if( visual && visual.GetName() == visualName )
970     {
971       Toolkit::GetImplementation(visual).SetOffStage( self );
972       (*visualIter)->visual.Reset();
973       visuals.Erase( visualIter );
974       break;
975     }
976   }
977 }
978
979 void Control::Impl::RemoveVisuals( RegisteredVisualContainer& visuals, DictionaryKeys& removeVisuals )
980 {
981   Actor self( mControlImpl.Self() );
982   for( DictionaryKeys::iterator iter = removeVisuals.begin(); iter != removeVisuals.end(); ++iter )
983   {
984     const std::string visualName = *iter;
985     RemoveVisual( visuals, visualName );
986   }
987 }
988
989 void Control::Impl::RecreateChangedVisuals( Dictionary<Property::Map>& stateVisualsToChange,
990                              Dictionary<Property::Map>& instancedProperties )
991 {
992   Dali::CustomActor handle( mControlImpl.GetOwner() );
993   for( Dictionary<Property::Map>::iterator iter = stateVisualsToChange.Begin();
994        iter != stateVisualsToChange.End(); ++iter )
995   {
996     const std::string& visualName = (*iter).key;
997     const Property::Map& toMap = (*iter).entry;
998
999     // is it a candidate for re-creation?
1000     bool recreate = false;
1001
1002     Toolkit::Visual::Base visual = GetVisualByName( mVisuals, visualName );
1003     if( visual )
1004     {
1005       Property::Map fromMap;
1006       visual.CreatePropertyMap( fromMap );
1007
1008       Toolkit::DevelVisual::Type fromType = GetVisualTypeFromMap( fromMap );
1009       Toolkit::DevelVisual::Type toType = GetVisualTypeFromMap( toMap );
1010
1011       if( fromType != toType )
1012       {
1013         recreate = true;
1014       }
1015       else
1016       {
1017         if( fromType == Toolkit::DevelVisual::IMAGE || fromType == Toolkit::DevelVisual::N_PATCH
1018             || fromType == Toolkit::DevelVisual::SVG || fromType == Toolkit::DevelVisual::ANIMATED_IMAGE )
1019         {
1020           Property::Value* fromUrl = fromMap.Find( Toolkit::ImageVisual::Property::URL, IMAGE_URL_NAME );
1021           Property::Value* toUrl = toMap.Find( Toolkit::ImageVisual::Property::URL, IMAGE_URL_NAME );
1022
1023           if( fromUrl && toUrl )
1024           {
1025             std::string fromUrlString;
1026             std::string toUrlString;
1027             fromUrl->Get(fromUrlString);
1028             toUrl->Get(toUrlString);
1029
1030             if( fromUrlString != toUrlString )
1031             {
1032               recreate = true;
1033             }
1034           }
1035         }
1036       }
1037
1038       const Property::Map* instancedMap = instancedProperties.FindConst( visualName );
1039       if( recreate || instancedMap )
1040       {
1041         RemoveVisual( mVisuals, visualName );
1042         Style::ApplyVisual( handle, visualName, toMap, instancedMap );
1043       }
1044       else
1045       {
1046         // @todo check to see if we can apply toMap without recreating the visual
1047         // e.g. by setting only animatable properties
1048         // For now, recreate all visuals, but merge in instance data.
1049         RemoveVisual( mVisuals, visualName );
1050         Style::ApplyVisual( handle, visualName, toMap, instancedMap );
1051       }
1052     }
1053   }
1054 }
1055
1056 void Control::Impl::ReplaceStateVisualsAndProperties( const StylePtr oldState, const StylePtr newState, const std::string& subState )
1057 {
1058   // Collect all old visual names
1059   DictionaryKeys stateVisualsToRemove;
1060   if( oldState )
1061   {
1062     oldState->visuals.GetKeys( stateVisualsToRemove );
1063     if( ! subState.empty() )
1064     {
1065       const StylePtr* oldSubState = oldState->subStates.FindConst(subState);
1066       if( oldSubState )
1067       {
1068         DictionaryKeys subStateVisualsToRemove;
1069         (*oldSubState)->visuals.GetKeys( subStateVisualsToRemove );
1070         Merge( stateVisualsToRemove, subStateVisualsToRemove );
1071       }
1072     }
1073   }
1074
1075   // Collect all new visual properties
1076   Dictionary<Property::Map> stateVisualsToAdd;
1077   if( newState )
1078   {
1079     stateVisualsToAdd = newState->visuals;
1080     if( ! subState.empty() )
1081     {
1082       const StylePtr* newSubState = newState->subStates.FindConst(subState);
1083       if( newSubState )
1084       {
1085         stateVisualsToAdd.Merge( (*newSubState)->visuals );
1086       }
1087     }
1088   }
1089
1090   // If a name is in both add/remove, move it to change list.
1091   Dictionary<Property::Map> stateVisualsToChange;
1092   FindChangableVisuals( stateVisualsToAdd, stateVisualsToChange, stateVisualsToRemove);
1093
1094   // Copy instanced properties (e.g. text label) of current visuals
1095   Dictionary<Property::Map> instancedProperties;
1096   CopyInstancedProperties( mVisuals, instancedProperties );
1097
1098   // For each visual in remove list, remove from mVisuals
1099   RemoveVisuals( mVisuals, stateVisualsToRemove );
1100
1101   // For each visual in add list, create and add to mVisuals
1102   Dali::CustomActor handle( mControlImpl.GetOwner() );
1103   Style::ApplyVisuals( handle, stateVisualsToAdd, instancedProperties );
1104
1105   // For each visual in change list, if it requires a new visual,
1106   // remove old visual, create and add to mVisuals
1107   RecreateChangedVisuals( stateVisualsToChange, instancedProperties );
1108 }
1109
1110 void Control::Impl::SetState( DevelControl::State newState, bool withTransitions )
1111 {
1112   DevelControl::State oldState = mState;
1113   Dali::CustomActor handle( mControlImpl.GetOwner() );
1114   DALI_LOG_INFO(gLogFilter, Debug::Concise, "Control::Impl::SetState: %s\n",
1115                 (mState == DevelControl::NORMAL ? "NORMAL" :(
1116                   mState == DevelControl::FOCUSED ?"FOCUSED" : (
1117                     mState == DevelControl::DISABLED?"DISABLED":"NONE" ))));
1118
1119   if( mState != newState )
1120   {
1121     // If mState was Disabled, and new state is Focused, should probably
1122     // store that fact, e.g. in another property that FocusManager can access.
1123     mState = newState;
1124
1125     // Trigger state change and transitions
1126     // Apply new style, if stylemanager is available
1127     Toolkit::StyleManager styleManager = Toolkit::StyleManager::Get();
1128     if( styleManager )
1129     {
1130       const StylePtr stylePtr = GetImpl( styleManager ).GetRecordedStyle( Toolkit::Control( mControlImpl.GetOwner() ) );
1131
1132       if( stylePtr )
1133       {
1134         std::string oldStateName = Scripting::GetEnumerationName< Toolkit::DevelControl::State >( oldState, ControlStateTable, ControlStateTableCount );
1135         std::string newStateName = Scripting::GetEnumerationName< Toolkit::DevelControl::State >( newState, ControlStateTable, ControlStateTableCount );
1136
1137         const StylePtr* newStateStyle = stylePtr->subStates.Find( newStateName );
1138         const StylePtr* oldStateStyle = stylePtr->subStates.Find( oldStateName );
1139         if( oldStateStyle && newStateStyle )
1140         {
1141           // Only change if both state styles exist
1142           ReplaceStateVisualsAndProperties( *oldStateStyle, *newStateStyle, mSubStateName );
1143         }
1144       }
1145     }
1146   }
1147 }
1148
1149 void Control::Impl::SetSubState( const std::string& subStateName, bool withTransitions )
1150 {
1151   if( mSubStateName != subStateName )
1152   {
1153     // Get existing sub-state visuals, and unregister them
1154     Dali::CustomActor handle( mControlImpl.GetOwner() );
1155
1156     Toolkit::StyleManager styleManager = Toolkit::StyleManager::Get();
1157     if( styleManager )
1158     {
1159       const StylePtr stylePtr = GetImpl( styleManager ).GetRecordedStyle( Toolkit::Control( mControlImpl.GetOwner() ) );
1160       if( stylePtr )
1161       {
1162         // Stringify state
1163         std::string stateName = Scripting::GetEnumerationName< Toolkit::DevelControl::State >( mState, ControlStateTable, ControlStateTableCount );
1164
1165         const StylePtr* state = stylePtr->subStates.Find( stateName );
1166         if( state )
1167         {
1168           StylePtr stateStyle(*state);
1169
1170           const StylePtr* newStateStyle = stateStyle->subStates.Find( subStateName );
1171           const StylePtr* oldStateStyle = stateStyle->subStates.Find( mSubStateName );
1172           if( oldStateStyle && newStateStyle )
1173           {
1174             std::string empty;
1175             ReplaceStateVisualsAndProperties( *oldStateStyle, *newStateStyle, empty );
1176           }
1177         }
1178       }
1179     }
1180
1181     mSubStateName = subStateName;
1182   }
1183 }
1184
1185 } // namespace Internal
1186
1187 } // namespace Toolkit
1188
1189 } // namespace Dali