Change Visual depth index API from float to int
[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     // Check if the control has been type registered:
443     TypeInfo typeInfo = TypeRegistry::Get().GetTypeInfo( typeid( mControlImpl ) );
444     if( typeInfo )
445     {
446       // Check if the property index has been registered:
447       Property::IndexContainer indices;
448       typeInfo.GetPropertyIndices( indices );
449       Property::IndexContainer::Iterator iter = std::find( indices.Begin(), indices.End(), index );
450       if( iter != indices.End() )
451       {
452         // If it has, then get it's name and use that for the visual
453         std::string visualName = typeInfo.GetPropertyName( index );
454         visual.SetName( visualName );
455       }
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         Internal::Visual::Base& visualImpl = Toolkit::GetImplementation( visual );
607         visualImpl.AnimateProperty( transition, *animator );
608       }
609       else
610       {
611         // Otherwise, try any actor children of control (Including the control)
612         Actor child = mControlImpl.Self().FindChildByName( animator->objectName );
613         if( child )
614         {
615           Property::Index propertyIndex = DevelHandle::GetPropertyIndex( child, animator->propertyKey );
616           if( propertyIndex != Property::INVALID_INDEX )
617           {
618             if( animator->animate == false )
619             {
620               if( animator->targetValue.GetType() != Property::NONE )
621               {
622                 child.SetProperty( propertyIndex, animator->targetValue );
623               }
624             }
625             else // animate the property
626             {
627               if( animator->initialValue.GetType() != Property::NONE )
628               {
629                 child.SetProperty( propertyIndex, animator->initialValue );
630               }
631
632               if( ! transition )
633               {
634                 transition = Dali::Animation::New( 0.1f );
635               }
636
637               transition.AnimateTo( Property( child, propertyIndex ),
638                                     animator->targetValue,
639                                     animator->alphaFunction,
640                                     TimePeriod( animator->timePeriodDelay,
641                                                 animator->timePeriodDuration ) );
642             }
643           }
644         }
645       }
646     }
647   }
648
649   return transition;
650 }
651
652 void Control::Impl::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
653 {
654   Toolkit::Control control = Toolkit::Control::DownCast( BaseHandle( object ) );
655
656   if ( control )
657   {
658     Control& controlImpl( GetImplementation( control ) );
659
660     switch ( index )
661     {
662       case Toolkit::Control::Property::STYLE_NAME:
663       {
664         controlImpl.SetStyleName( value.Get< std::string >() );
665         break;
666       }
667
668       case Toolkit::DevelControl::Property::STATE:
669       {
670         bool withTransitions=true;
671         const Property::Value* valuePtr=&value;
672         Property::Map* map = value.GetMap();
673         if(map)
674         {
675           Property::Value* value2 = map->Find("withTransitions");
676           if( value2 )
677           {
678             withTransitions = value2->Get<bool>();
679           }
680
681           valuePtr = map->Find("state");
682         }
683
684         if( valuePtr )
685         {
686           Toolkit::DevelControl::State state( controlImpl.mImpl->mState );
687           if( Scripting::GetEnumerationProperty< Toolkit::DevelControl::State >( *valuePtr, ControlStateTable, ControlStateTableCount, state ) )
688           {
689             controlImpl.mImpl->SetState( state, withTransitions );
690           }
691         }
692       }
693       break;
694
695       case Toolkit::DevelControl::Property::SUB_STATE:
696       {
697         std::string subState;
698         if( value.Get( subState ) )
699         {
700           controlImpl.mImpl->SetSubState( subState );
701         }
702       }
703       break;
704
705       case Toolkit::DevelControl::Property::LEFT_FOCUSABLE_ACTOR_ID:
706       {
707         int focusId;
708         if( value.Get( focusId ) )
709         {
710           controlImpl.mImpl->mLeftFocusableActorId = focusId;
711         }
712       }
713       break;
714
715       case Toolkit::DevelControl::Property::RIGHT_FOCUSABLE_ACTOR_ID:
716       {
717         int focusId;
718         if( value.Get( focusId ) )
719         {
720           controlImpl.mImpl->mRightFocusableActorId = focusId;
721         }
722       }
723       break;
724
725       case Toolkit::DevelControl::Property::UP_FOCUSABLE_ACTOR_ID:
726       {
727         int focusId;
728         if( value.Get( focusId ) )
729         {
730           controlImpl.mImpl->mUpFocusableActorId = focusId;
731         }
732       }
733       break;
734
735       case Toolkit::DevelControl::Property::DOWN_FOCUSABLE_ACTOR_ID:
736       {
737         int focusId;
738         if( value.Get( focusId ) )
739         {
740           controlImpl.mImpl->mDownFocusableActorId = focusId;
741         }
742       }
743       break;
744
745       case Toolkit::Control::Property::BACKGROUND_COLOR:
746       {
747         DALI_LOG_WARNING( "BACKGROUND_COLOR property is deprecated. Use BACKGROUND property instead\n" );
748         controlImpl.SetBackgroundColor( value.Get< Vector4 >() );
749         break;
750       }
751
752       case Toolkit::Control::Property::BACKGROUND_IMAGE:
753       {
754         DALI_LOG_WARNING( "BACKGROUND_IMAGE property is deprecated. Use BACKGROUND property instead\n" );
755         Image image = Scripting::NewImage( value );
756         if ( image )
757         {
758           controlImpl.SetBackgroundImage( image );
759         }
760         else
761         {
762           // An empty image means the background is no longer required
763           controlImpl.ClearBackground();
764         }
765         break;
766       }
767
768       case Toolkit::Control::Property::KEY_INPUT_FOCUS:
769       {
770         if ( value.Get< bool >() )
771         {
772           controlImpl.SetKeyInputFocus();
773         }
774         else
775         {
776           controlImpl.ClearKeyInputFocus();
777         }
778         break;
779       }
780
781       case Toolkit::Control::Property::BACKGROUND:
782       {
783         std::string url;
784         Vector4 color;
785         const Property::Map* map = value.GetMap();
786         if( map && !map->Empty() )
787         {
788           controlImpl.SetBackground( *map );
789         }
790         else if( value.Get( url ) )
791         {
792           // don't know the size to load
793           Toolkit::Visual::Base visual = Toolkit::VisualFactory::Get().CreateVisual( url, ImageDimensions() );
794           if( visual )
795           {
796             controlImpl.mImpl->RegisterVisual( Toolkit::Control::Property::BACKGROUND, visual, DepthIndex::BACKGROUND );
797           }
798         }
799         else if( value.Get( color ) )
800         {
801           controlImpl.SetBackgroundColor(color);
802         }
803         else
804         {
805           // The background is an empty property map, so we should clear the background
806           controlImpl.ClearBackground();
807         }
808         break;
809       }
810
811       case Toolkit::DevelControl::Property::TOOLTIP:
812       {
813         TooltipPtr& tooltipPtr = controlImpl.mImpl->mTooltip;
814         if( ! tooltipPtr )
815         {
816           tooltipPtr = Tooltip::New( control );
817         }
818         tooltipPtr->SetProperties( value );
819       }
820     }
821   }
822 }
823
824 Property::Value Control::Impl::GetProperty( BaseObject* object, Property::Index index )
825 {
826   Property::Value value;
827
828   Toolkit::Control control = Toolkit::Control::DownCast( BaseHandle( object ) );
829
830   if ( control )
831   {
832     Control& controlImpl( GetImplementation( control ) );
833
834     switch ( index )
835     {
836       case Toolkit::Control::Property::STYLE_NAME:
837       {
838         value = controlImpl.GetStyleName();
839         break;
840       }
841
842       case Toolkit::DevelControl::Property::STATE:
843       {
844         value = controlImpl.mImpl->mState;
845         break;
846       }
847
848       case Toolkit::DevelControl::Property::SUB_STATE:
849       {
850         value = controlImpl.mImpl->mSubStateName;
851         break;
852       }
853
854       case Toolkit::DevelControl::Property::LEFT_FOCUSABLE_ACTOR_ID:
855       {
856         value = controlImpl.mImpl->mLeftFocusableActorId;
857         break;
858       }
859
860       case Toolkit::DevelControl::Property::RIGHT_FOCUSABLE_ACTOR_ID:
861       {
862         value = controlImpl.mImpl->mRightFocusableActorId;
863         break;
864       }
865
866       case Toolkit::DevelControl::Property::UP_FOCUSABLE_ACTOR_ID:
867       {
868         value = controlImpl.mImpl->mUpFocusableActorId;
869         break;
870       }
871
872       case Toolkit::DevelControl::Property::DOWN_FOCUSABLE_ACTOR_ID:
873       {
874         value = controlImpl.mImpl->mDownFocusableActorId;
875         break;
876       }
877
878       case Toolkit::Control::Property::BACKGROUND_COLOR:
879       {
880         DALI_LOG_WARNING( "BACKGROUND_COLOR property is deprecated. Use BACKGROUND property instead\n" );
881         value = controlImpl.GetBackgroundColor();
882         break;
883       }
884
885       case Toolkit::Control::Property::BACKGROUND_IMAGE:
886       {
887         DALI_LOG_WARNING( "BACKGROUND_IMAGE property is deprecated. Use BACKGROUND property instead\n" );
888         Property::Map map;
889         Toolkit::Visual::Base visual = controlImpl.mImpl->GetVisual( Toolkit::Control::Property::BACKGROUND );
890         if( visual )
891         {
892           visual.CreatePropertyMap( map );
893         }
894         value = map;
895         break;
896       }
897
898       case Toolkit::Control::Property::KEY_INPUT_FOCUS:
899       {
900         value = controlImpl.HasKeyInputFocus();
901         break;
902       }
903
904       case Toolkit::Control::Property::BACKGROUND:
905       {
906         Property::Map map;
907         Toolkit::Visual::Base visual = controlImpl.mImpl->GetVisual( Toolkit::Control::Property::BACKGROUND );
908         if( visual )
909         {
910           visual.CreatePropertyMap( map );
911         }
912
913         value = map;
914         break;
915       }
916
917       case Toolkit::DevelControl::Property::TOOLTIP:
918       {
919         Property::Map map;
920         if( controlImpl.mImpl->mTooltip )
921         {
922           controlImpl.mImpl->mTooltip->CreatePropertyMap( map );
923         }
924         value = map;
925         break;
926       }
927
928     }
929   }
930
931   return value;
932 }
933
934
935 void  Control::Impl::CopyInstancedProperties( RegisteredVisualContainer& visuals, Dictionary<Property::Map>& instancedProperties )
936 {
937   for(RegisteredVisualContainer::Iterator iter = visuals.Begin(); iter!= visuals.End(); iter++)
938   {
939     if( (*iter)->visual )
940     {
941       Property::Map instanceMap;
942       Toolkit::GetImplementation((*iter)->visual).CreateInstancePropertyMap(instanceMap);
943       instancedProperties.Add( (*iter)->visual.GetName(), instanceMap );
944     }
945   }
946 }
947
948
949 void Control::Impl::RemoveVisual( RegisteredVisualContainer& visuals, const std::string& visualName )
950 {
951   Actor self( mControlImpl.Self() );
952
953   for ( RegisteredVisualContainer::Iterator visualIter = visuals.Begin();
954         visualIter != visuals.End(); ++visualIter )
955   {
956     Toolkit::Visual::Base visual = (*visualIter)->visual;
957     if( visual && visual.GetName() == visualName )
958     {
959       Toolkit::GetImplementation(visual).SetOffStage( self );
960       (*visualIter)->visual.Reset();
961       visuals.Erase( visualIter );
962       break;
963     }
964   }
965 }
966
967 void Control::Impl::RemoveVisuals( RegisteredVisualContainer& visuals, DictionaryKeys& removeVisuals )
968 {
969   Actor self( mControlImpl.Self() );
970   for( DictionaryKeys::iterator iter = removeVisuals.begin(); iter != removeVisuals.end(); ++iter )
971   {
972     const std::string visualName = *iter;
973     RemoveVisual( visuals, visualName );
974   }
975 }
976
977 void Control::Impl::RecreateChangedVisuals( Dictionary<Property::Map>& stateVisualsToChange,
978                              Dictionary<Property::Map>& instancedProperties )
979 {
980   Dali::CustomActor handle( mControlImpl.GetOwner() );
981   for( Dictionary<Property::Map>::iterator iter = stateVisualsToChange.Begin();
982        iter != stateVisualsToChange.End(); ++iter )
983   {
984     const std::string& visualName = (*iter).key;
985     const Property::Map& toMap = (*iter).entry;
986
987     // is it a candidate for re-creation?
988     bool recreate = false;
989
990     Toolkit::Visual::Base visual = GetVisualByName( mVisuals, visualName );
991     if( visual )
992     {
993       Property::Map fromMap;
994       visual.CreatePropertyMap( fromMap );
995
996       Toolkit::DevelVisual::Type fromType = GetVisualTypeFromMap( fromMap );
997       Toolkit::DevelVisual::Type toType = GetVisualTypeFromMap( toMap );
998
999       if( fromType != toType )
1000       {
1001         recreate = true;
1002       }
1003       else
1004       {
1005         if( fromType == Toolkit::DevelVisual::IMAGE || fromType == Toolkit::DevelVisual::N_PATCH
1006             || fromType == Toolkit::DevelVisual::SVG || fromType == Toolkit::DevelVisual::ANIMATED_IMAGE )
1007         {
1008           Property::Value* fromUrl = fromMap.Find( Toolkit::ImageVisual::Property::URL, IMAGE_URL_NAME );
1009           Property::Value* toUrl = toMap.Find( Toolkit::ImageVisual::Property::URL, IMAGE_URL_NAME );
1010
1011           if( fromUrl && toUrl )
1012           {
1013             std::string fromUrlString;
1014             std::string toUrlString;
1015             fromUrl->Get(fromUrlString);
1016             toUrl->Get(toUrlString);
1017
1018             if( fromUrlString != toUrlString )
1019             {
1020               recreate = true;
1021             }
1022           }
1023         }
1024       }
1025
1026       const Property::Map* instancedMap = instancedProperties.FindConst( visualName );
1027       if( recreate || instancedMap )
1028       {
1029         RemoveVisual( mVisuals, visualName );
1030         Style::ApplyVisual( handle, visualName, toMap, instancedMap );
1031       }
1032       else
1033       {
1034         // @todo check to see if we can apply toMap without recreating the visual
1035         // e.g. by setting only animatable properties
1036         // For now, recreate all visuals, but merge in instance data.
1037         RemoveVisual( mVisuals, visualName );
1038         Style::ApplyVisual( handle, visualName, toMap, instancedMap );
1039       }
1040     }
1041   }
1042 }
1043
1044 void Control::Impl::ReplaceStateVisualsAndProperties( const StylePtr oldState, const StylePtr newState, const std::string& subState )
1045 {
1046   // Collect all old visual names
1047   DictionaryKeys stateVisualsToRemove;
1048   if( oldState )
1049   {
1050     oldState->visuals.GetKeys( stateVisualsToRemove );
1051     if( ! subState.empty() )
1052     {
1053       const StylePtr* oldSubState = oldState->subStates.FindConst(subState);
1054       if( oldSubState )
1055       {
1056         DictionaryKeys subStateVisualsToRemove;
1057         (*oldSubState)->visuals.GetKeys( subStateVisualsToRemove );
1058         Merge( stateVisualsToRemove, subStateVisualsToRemove );
1059       }
1060     }
1061   }
1062
1063   // Collect all new visual properties
1064   Dictionary<Property::Map> stateVisualsToAdd;
1065   if( newState )
1066   {
1067     stateVisualsToAdd = newState->visuals;
1068     if( ! subState.empty() )
1069     {
1070       const StylePtr* newSubState = newState->subStates.FindConst(subState);
1071       if( newSubState )
1072       {
1073         stateVisualsToAdd.Merge( (*newSubState)->visuals );
1074       }
1075     }
1076   }
1077
1078   // If a name is in both add/remove, move it to change list.
1079   Dictionary<Property::Map> stateVisualsToChange;
1080   FindChangableVisuals( stateVisualsToAdd, stateVisualsToChange, stateVisualsToRemove);
1081
1082   // Copy instanced properties (e.g. text label) of current visuals
1083   Dictionary<Property::Map> instancedProperties;
1084   CopyInstancedProperties( mVisuals, instancedProperties );
1085
1086   // For each visual in remove list, remove from mVisuals
1087   RemoveVisuals( mVisuals, stateVisualsToRemove );
1088
1089   // For each visual in add list, create and add to mVisuals
1090   Dali::CustomActor handle( mControlImpl.GetOwner() );
1091   Style::ApplyVisuals( handle, stateVisualsToAdd, instancedProperties );
1092
1093   // For each visual in change list, if it requires a new visual,
1094   // remove old visual, create and add to mVisuals
1095   RecreateChangedVisuals( stateVisualsToChange, instancedProperties );
1096 }
1097
1098 void Control::Impl::SetState( DevelControl::State newState, bool withTransitions )
1099 {
1100   DevelControl::State oldState = mState;
1101   Dali::CustomActor handle( mControlImpl.GetOwner() );
1102   DALI_LOG_INFO(gLogFilter, Debug::Concise, "Control::Impl::SetState: %s\n",
1103                 (mState == DevelControl::NORMAL ? "NORMAL" :(
1104                   mState == DevelControl::FOCUSED ?"FOCUSED" : (
1105                     mState == DevelControl::DISABLED?"DISABLED":"NONE" ))));
1106
1107   if( mState != newState )
1108   {
1109     // If mState was Disabled, and new state is Focused, should probably
1110     // store that fact, e.g. in another property that FocusManager can access.
1111     mState = newState;
1112
1113     // Trigger state change and transitions
1114     // Apply new style, if stylemanager is available
1115     Toolkit::StyleManager styleManager = Toolkit::StyleManager::Get();
1116     if( styleManager )
1117     {
1118       const StylePtr stylePtr = GetImpl( styleManager ).GetRecordedStyle( Toolkit::Control( mControlImpl.GetOwner() ) );
1119
1120       if( stylePtr )
1121       {
1122         std::string oldStateName = Scripting::GetEnumerationName< Toolkit::DevelControl::State >( oldState, ControlStateTable, ControlStateTableCount );
1123         std::string newStateName = Scripting::GetEnumerationName< Toolkit::DevelControl::State >( newState, ControlStateTable, ControlStateTableCount );
1124
1125         const StylePtr* newStateStyle = stylePtr->subStates.Find( newStateName );
1126         const StylePtr* oldStateStyle = stylePtr->subStates.Find( oldStateName );
1127         if( oldStateStyle && newStateStyle )
1128         {
1129           // Only change if both state styles exist
1130           ReplaceStateVisualsAndProperties( *oldStateStyle, *newStateStyle, mSubStateName );
1131         }
1132       }
1133     }
1134   }
1135 }
1136
1137 void Control::Impl::SetSubState( const std::string& subStateName, bool withTransitions )
1138 {
1139   if( mSubStateName != subStateName )
1140   {
1141     // Get existing sub-state visuals, and unregister them
1142     Dali::CustomActor handle( mControlImpl.GetOwner() );
1143
1144     Toolkit::StyleManager styleManager = Toolkit::StyleManager::Get();
1145     if( styleManager )
1146     {
1147       const StylePtr stylePtr = GetImpl( styleManager ).GetRecordedStyle( Toolkit::Control( mControlImpl.GetOwner() ) );
1148       if( stylePtr )
1149       {
1150         // Stringify state
1151         std::string stateName = Scripting::GetEnumerationName< Toolkit::DevelControl::State >( mState, ControlStateTable, ControlStateTableCount );
1152
1153         const StylePtr* state = stylePtr->subStates.Find( stateName );
1154         if( state )
1155         {
1156           StylePtr stateStyle(*state);
1157
1158           const StylePtr* newStateStyle = stateStyle->subStates.Find( subStateName );
1159           const StylePtr* oldStateStyle = stateStyle->subStates.Find( mSubStateName );
1160           if( oldStateStyle && newStateStyle )
1161           {
1162             std::string empty;
1163             ReplaceStateVisualsAndProperties( *oldStateStyle, *newStateStyle, empty );
1164           }
1165         }
1166       }
1167     }
1168
1169     mSubStateName = subStateName;
1170   }
1171 }
1172
1173 } // namespace Internal
1174
1175 } // namespace Toolkit
1176
1177 } // namespace Dali