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