[dali_1.2.26] Merge branch 'devel/master'
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / public-api / controls / control-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 <dali-toolkit/public-api/controls/control-impl.h>
20
21 // EXTERNAL INCLUDES
22 #include <cstring> // for strcmp
23 #include <limits>
24 #include <stack>
25 #include <typeinfo>
26 #include <dali/public-api/animation/constraint.h>
27 #include <dali/public-api/animation/constraints.h>
28 #include <dali/public-api/object/type-registry.h>
29 #include <dali/public-api/object/type-registry-helper.h>
30 #include <dali/public-api/rendering/renderer.h>
31 #include <dali/public-api/size-negotiation/relayout-container.h>
32 #include <dali/devel-api/common/owner-container.h>
33 #include <dali/devel-api/object/handle-devel.h>
34 #include <dali/devel-api/scripting/enum-helper.h>
35 #include <dali/devel-api/scripting/scripting.h>
36 #include <dali/integration-api/debug.h>
37
38 // INTERNAL INCLUDES
39 #include <dali-toolkit/public-api/focus-manager/keyboard-focus-manager.h>
40 #include <dali-toolkit/public-api/controls/control.h>
41 #include <dali-toolkit/public-api/styling/style-manager.h>
42 #include <dali-toolkit/public-api/visuals/color-visual-properties.h>
43 #include <dali-toolkit/devel-api/controls/control-depth-index-ranges.h>
44 #include <dali-toolkit/devel-api/controls/control-devel.h>
45 #include <dali-toolkit/devel-api/visuals/visual-properties-devel.h>
46 #include <dali-toolkit/devel-api/visual-factory/visual-factory.h>
47 #include <dali-toolkit/devel-api/focus-manager/keyinput-focus-manager.h>
48 #include <dali-toolkit/internal/styling/style-manager-impl.h>
49 #include <dali-toolkit/internal/visuals/color/color-visual.h>
50 #include <dali-toolkit/internal/visuals/transition-data-impl.h>
51 #include <dali-toolkit/internal/visuals/visual-string-constants.h>
52 #include <dali-toolkit/devel-api/align-enums.h>
53 #include <dali-toolkit/internal/controls/tooltip/tooltip.h>
54
55 namespace Dali
56 {
57
58 namespace Toolkit
59 {
60
61 namespace
62 {
63
64 #if defined(DEBUG_ENABLED)
65 Debug::Filter* gLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_CONTROL_VISUALS");
66 #endif
67
68 DALI_ENUM_TO_STRING_TABLE_BEGIN( CLIPPING_MODE )
69 DALI_ENUM_TO_STRING_WITH_SCOPE( ClippingMode, DISABLED )
70 DALI_ENUM_TO_STRING_WITH_SCOPE( ClippingMode, CLIP_CHILDREN )
71 DALI_ENUM_TO_STRING_TABLE_END( CLIPPING_MODE )
72
73 /**
74  * Struct used to store Visual within the control, index is a unique key for each visual.
75  */
76 struct RegisteredVisual
77 {
78   Property::Index index;
79   Toolkit::Visual::Base visual;
80   bool enabled;
81
82   RegisteredVisual( Property::Index aIndex, Toolkit::Visual::Base &aVisual, bool aEnabled)
83   : index(aIndex), visual(aVisual), enabled(aEnabled)
84   {
85   }
86 };
87
88 typedef Dali::OwnerContainer< RegisteredVisual* > RegisteredVisualContainer;
89
90 /**
91  *  Finds visual in given array, returning true if found along with the iterator for that visual as a out parameter
92  */
93 bool FindVisual( Property::Index targetIndex, RegisteredVisualContainer& visuals, RegisteredVisualContainer::Iterator& iter )
94 {
95   for ( iter = visuals.Begin(); iter != visuals.End(); iter++ )
96   {
97     if ( (*iter)->index ==  targetIndex )
98     {
99       return true;
100     }
101   }
102   return false;
103 }
104
105 Toolkit::Visual::Base GetVisualByName(
106   RegisteredVisualContainer& visuals,
107   const std::string& visualName )
108 {
109   Toolkit::Visual::Base visualHandle;
110
111   RegisteredVisualContainer::Iterator iter;
112   for ( iter = visuals.Begin(); iter != visuals.End(); iter++ )
113   {
114     Toolkit::Visual::Base visual = (*iter)->visual;
115     if( visual && visual.GetName() == visualName )
116     {
117       visualHandle = visual;
118       break;
119     }
120   }
121   return visualHandle;
122 }
123
124 /**
125  * Creates control through type registry
126  */
127 BaseHandle Create()
128 {
129   return Internal::Control::New();
130 }
131
132 /**
133  * Performs actions as requested using the action name.
134  * @param[in] object The object on which to perform the action.
135  * @param[in] actionName The action to perform.
136  * @param[in] attributes The attributes with which to perfrom this action.
137  * @return true if action has been accepted by this control
138  */
139 const char* ACTION_ACCESSIBILITY_ACTIVATED = "accessibilityActivated";
140 static bool DoAction( BaseObject* object, const std::string& actionName, const Property::Map& attributes )
141 {
142   bool ret = false;
143
144   if( object && ( 0 == strcmp( actionName.c_str(), ACTION_ACCESSIBILITY_ACTIVATED ) ) )
145   {
146     Toolkit::Control control = Toolkit::Control::DownCast( BaseHandle( object ) );
147     if( control )
148     {
149       // if cast succeeds there is an implementation so no need to check
150       ret = Internal::GetImplementation( control ).OnAccessibilityActivated();
151     }
152   }
153
154   return ret;
155 }
156
157 /**
158  * Connects a callback function with the object's signals.
159  * @param[in] object The object providing the signal.
160  * @param[in] tracker Used to disconnect the signal.
161  * @param[in] signalName The signal to connect to.
162  * @param[in] functor A newly allocated FunctorDelegate.
163  * @return True if the signal was connected.
164  * @post If a signal was connected, ownership of functor was passed to CallbackBase. Otherwise the caller is responsible for deleting the unused functor.
165  */
166 const char* SIGNAL_KEY_EVENT = "keyEvent";
167 const char* SIGNAL_KEY_INPUT_FOCUS_GAINED = "keyInputFocusGained";
168 const char* SIGNAL_KEY_INPUT_FOCUS_LOST = "keyInputFocusLost";
169 const char* SIGNAL_TAPPED = "tapped";
170 const char* SIGNAL_PANNED = "panned";
171 const char* SIGNAL_PINCHED = "pinched";
172 const char* SIGNAL_LONG_PRESSED = "longPressed";
173 static bool DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
174 {
175   Dali::BaseHandle handle( object );
176
177   bool connected( false );
178   Toolkit::Control control = Toolkit::Control::DownCast( handle );
179   if ( control )
180   {
181     Internal::Control& controlImpl( Internal::GetImplementation( control ) );
182     connected = true;
183
184     if ( 0 == strcmp( signalName.c_str(), SIGNAL_KEY_EVENT ) )
185     {
186       controlImpl.KeyEventSignal().Connect( tracker, functor );
187     }
188     else if( 0 == strcmp( signalName.c_str(), SIGNAL_KEY_INPUT_FOCUS_GAINED ) )
189     {
190       controlImpl.KeyInputFocusGainedSignal().Connect( tracker, functor );
191     }
192     else if( 0 == strcmp( signalName.c_str(), SIGNAL_KEY_INPUT_FOCUS_LOST ) )
193     {
194       controlImpl.KeyInputFocusLostSignal().Connect( tracker, functor );
195     }
196     else if( 0 == strcmp( signalName.c_str(), SIGNAL_TAPPED ) )
197     {
198       controlImpl.EnableGestureDetection( Gesture::Tap );
199       controlImpl.GetTapGestureDetector().DetectedSignal().Connect( tracker, functor );
200     }
201     else if( 0 == strcmp( signalName.c_str(), SIGNAL_PANNED ) )
202     {
203       controlImpl.EnableGestureDetection( Gesture::Pan );
204       controlImpl.GetPanGestureDetector().DetectedSignal().Connect( tracker, functor );
205     }
206     else if( 0 == strcmp( signalName.c_str(), SIGNAL_PINCHED ) )
207     {
208       controlImpl.EnableGestureDetection( Gesture::Pinch );
209       controlImpl.GetPinchGestureDetector().DetectedSignal().Connect( tracker, functor );
210     }
211     else if( 0 == strcmp( signalName.c_str(), SIGNAL_LONG_PRESSED ) )
212     {
213       controlImpl.EnableGestureDetection( Gesture::LongPress );
214       controlImpl.GetLongPressGestureDetector().DetectedSignal().Connect( tracker, functor );
215     }
216   }
217   return connected;
218 }
219
220 // Setup signals and actions using the type-registry.
221 DALI_TYPE_REGISTRATION_BEGIN( Control, CustomActor, Create );
222
223 // Note: Properties are registered separately below.
224
225 SignalConnectorType registerSignal1( typeRegistration, SIGNAL_KEY_EVENT, &DoConnectSignal );
226 SignalConnectorType registerSignal2( typeRegistration, SIGNAL_KEY_INPUT_FOCUS_GAINED, &DoConnectSignal );
227 SignalConnectorType registerSignal3( typeRegistration, SIGNAL_KEY_INPUT_FOCUS_LOST, &DoConnectSignal );
228 SignalConnectorType registerSignal4( typeRegistration, SIGNAL_TAPPED, &DoConnectSignal );
229 SignalConnectorType registerSignal5( typeRegistration, SIGNAL_PANNED, &DoConnectSignal );
230 SignalConnectorType registerSignal6( typeRegistration, SIGNAL_PINCHED, &DoConnectSignal );
231 SignalConnectorType registerSignal7( typeRegistration, SIGNAL_LONG_PRESSED, &DoConnectSignal );
232
233 TypeAction registerAction( typeRegistration, ACTION_ACCESSIBILITY_ACTIVATED, &DoAction );
234
235 DALI_TYPE_REGISTRATION_END()
236
237 } // unnamed namespace
238
239 namespace Internal
240 {
241
242 class Control::Impl : public ConnectionTracker
243 {
244 public:
245
246   // Construction & Destruction
247   Impl(Control& controlImpl)
248   : mControlImpl( controlImpl ),
249     mStyleName(""),
250     mBackgroundColor(Color::TRANSPARENT),
251     mStartingPinchScale( NULL ),
252     mKeyEventSignal(),
253     mPinchGestureDetector(),
254     mPanGestureDetector(),
255     mTapGestureDetector(),
256     mLongPressGestureDetector(),
257     mFlags( Control::ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ),
258     mIsKeyboardNavigationSupported( false ),
259     mIsKeyboardFocusGroup( false )
260   {
261   }
262
263   ~Impl()
264   {
265     // All gesture detectors will be destroyed so no need to disconnect.
266     delete mStartingPinchScale;
267   }
268
269   // Gesture Detection Methods
270
271   void PinchDetected(Actor actor, const PinchGesture& pinch)
272   {
273     mControlImpl.OnPinch(pinch);
274   }
275
276   void PanDetected(Actor actor, const PanGesture& pan)
277   {
278     mControlImpl.OnPan(pan);
279   }
280
281   void TapDetected(Actor actor, const TapGesture& tap)
282   {
283     mControlImpl.OnTap(tap);
284   }
285
286   void LongPressDetected(Actor actor, const LongPressGesture& longPress)
287   {
288     mControlImpl.OnLongPress(longPress);
289   }
290
291   // Properties
292
293   /**
294    * Called when a property of an object of this type is set.
295    * @param[in] object The object whose property is set.
296    * @param[in] index The property index.
297    * @param[in] value The new property value.
298    */
299   static void SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
300   {
301     Toolkit::Control control = Toolkit::Control::DownCast( BaseHandle( object ) );
302
303     if ( control )
304     {
305       Control& controlImpl( GetImplementation( control ) );
306
307       switch ( index )
308       {
309         case Toolkit::Control::Property::STYLE_NAME:
310         {
311           controlImpl.SetStyleName( value.Get< std::string >() );
312           break;
313         }
314
315         case Toolkit::Control::Property::BACKGROUND_COLOR:
316         {
317           DALI_LOG_WARNING( "BACKGROUND_COLOR property is deprecated. Use BACKGROUND property instead\n" );
318           controlImpl.SetBackgroundColor( value.Get< Vector4 >() );
319           break;
320         }
321
322         case Toolkit::Control::Property::BACKGROUND_IMAGE:
323         {
324           DALI_LOG_WARNING( "BACKGROUND_IMAGE property is deprecated. Use BACKGROUND property instead\n" );
325           Image image = Scripting::NewImage( value );
326           if ( image )
327           {
328             controlImpl.SetBackgroundImage( image );
329           }
330           else
331           {
332             // An empty image means the background is no longer required
333             controlImpl.ClearBackground();
334           }
335           break;
336         }
337
338         case Toolkit::Control::Property::KEY_INPUT_FOCUS:
339         {
340           if ( value.Get< bool >() )
341           {
342             controlImpl.SetKeyInputFocus();
343           }
344           else
345           {
346             controlImpl.ClearKeyInputFocus();
347           }
348           break;
349         }
350
351         case Toolkit::Control::Property::BACKGROUND:
352         {
353           std::string url;
354           const Property::Map* map = value.GetMap();
355           if( map && !map->Empty() )
356           {
357             controlImpl.SetBackground( *map );
358           }
359           else if( value.Get( url ) )
360           {
361             // don't know the size to load
362             Toolkit::Visual::Base visual = Toolkit::VisualFactory::Get().CreateVisual( url, ImageDimensions() );
363             if( visual )
364             {
365               controlImpl.RegisterVisual( Toolkit::Control::Property::BACKGROUND, visual );
366               visual.SetDepthIndex( DepthIndex::BACKGROUND );
367             }
368           }
369           else
370           {
371             // The background is an empty property map, so we should clear the background
372             controlImpl.ClearBackground();
373           }
374           break;
375         }
376
377         case Toolkit::DevelControl::Property::TOOLTIP:
378         {
379           TooltipPtr& tooltipPtr = controlImpl.mImpl->mTooltip;
380           if( ! tooltipPtr )
381           {
382             tooltipPtr = Tooltip::New( control );
383           }
384           tooltipPtr->SetProperties( value );
385         }
386       }
387     }
388   }
389
390   /**
391    * Called to retrieve a property of an object of this type.
392    * @param[in] object The object whose property is to be retrieved.
393    * @param[in] index The property index.
394    * @return The current value of the property.
395    */
396   static Property::Value GetProperty( BaseObject* object, Property::Index index )
397   {
398     Property::Value value;
399
400     Toolkit::Control control = Toolkit::Control::DownCast( BaseHandle( object ) );
401
402     if ( control )
403     {
404       Control& controlImpl( GetImplementation( control ) );
405
406       switch ( index )
407       {
408         case Toolkit::Control::Property::STYLE_NAME:
409         {
410           value = controlImpl.GetStyleName();
411           break;
412         }
413
414         case Toolkit::Control::Property::BACKGROUND_COLOR:
415         {
416           DALI_LOG_WARNING( "BACKGROUND_COLOR property is deprecated. Use BACKGROUND property instead\n" );
417           value = controlImpl.GetBackgroundColor();
418           break;
419         }
420
421         case Toolkit::Control::Property::BACKGROUND_IMAGE:
422         {
423           DALI_LOG_WARNING( "BACKGROUND_IMAGE property is deprecated. Use BACKGROUND property instead\n" );
424           Property::Map map;
425           Toolkit::Visual::Base visual = controlImpl.GetVisual( Toolkit::Control::Property::BACKGROUND );
426           if( visual )
427           {
428             visual.CreatePropertyMap( map );
429           }
430           value = map;
431           break;
432         }
433
434         case Toolkit::Control::Property::KEY_INPUT_FOCUS:
435         {
436           value = controlImpl.HasKeyInputFocus();
437           break;
438         }
439
440         case Toolkit::Control::Property::BACKGROUND:
441         {
442           Property::Map map;
443           Toolkit::Visual::Base visual = controlImpl.GetVisual( Toolkit::Control::Property::BACKGROUND );
444           if( visual )
445           {
446             visual.CreatePropertyMap( map );
447           }
448
449           value = map;
450           break;
451         }
452
453         case Toolkit::DevelControl::Property::TOOLTIP:
454         {
455           Property::Map map;
456           if( controlImpl.mImpl->mTooltip )
457           {
458             controlImpl.mImpl->mTooltip->CreatePropertyMap( map );
459           }
460           value = map;
461           break;
462         }
463
464       }
465     }
466
467     return value;
468   }
469
470   // Data
471
472   Control& mControlImpl;
473   RegisteredVisualContainer mVisuals; // Stores visuals needed by the control, non trivial type so std::vector used.
474   std::string mStyleName;
475   Vector4 mBackgroundColor;                       ///< The color of the background visual
476   Vector3* mStartingPinchScale;      ///< The scale when a pinch gesture starts, TODO: consider removing this
477   Toolkit::Control::KeyEventSignalType mKeyEventSignal;
478   Toolkit::Control::KeyInputFocusSignalType mKeyInputFocusGainedSignal;
479   Toolkit::Control::KeyInputFocusSignalType mKeyInputFocusLostSignal;
480
481   // Gesture Detection
482   PinchGestureDetector mPinchGestureDetector;
483   PanGestureDetector mPanGestureDetector;
484   TapGestureDetector mTapGestureDetector;
485   LongPressGestureDetector mLongPressGestureDetector;
486
487   // Tooltip
488   TooltipPtr mTooltip;
489
490   ControlBehaviour mFlags : CONTROL_BEHAVIOUR_FLAG_COUNT;    ///< Flags passed in from constructor.
491   bool mIsKeyboardNavigationSupported :1;  ///< Stores whether keyboard navigation is supported by the control.
492   bool mIsKeyboardFocusGroup :1;           ///< Stores whether the control is a focus group.
493
494   // Properties - these need to be members of Internal::Control::Impl as they access private methods/data of Internal::Control and Internal::Control::Impl.
495   static const PropertyRegistration PROPERTY_1;
496   static const PropertyRegistration PROPERTY_2;
497   static const PropertyRegistration PROPERTY_3;
498   static const PropertyRegistration PROPERTY_4;
499   static const PropertyRegistration PROPERTY_5;
500   static const PropertyRegistration PROPERTY_6;
501 };
502
503 // Properties registered without macro to use specific member variables.
504 const PropertyRegistration Control::Impl::PROPERTY_1( typeRegistration, "styleName",       Toolkit::Control::Property::STYLE_NAME,       Property::STRING,  &Control::Impl::SetProperty, &Control::Impl::GetProperty );
505 const PropertyRegistration Control::Impl::PROPERTY_2( typeRegistration, "backgroundColor", Toolkit::Control::Property::BACKGROUND_COLOR, Property::VECTOR4, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
506 const PropertyRegistration Control::Impl::PROPERTY_3( typeRegistration, "backgroundImage", Toolkit::Control::Property::BACKGROUND_IMAGE, Property::MAP,     &Control::Impl::SetProperty, &Control::Impl::GetProperty );
507 const PropertyRegistration Control::Impl::PROPERTY_4( typeRegistration, "keyInputFocus",   Toolkit::Control::Property::KEY_INPUT_FOCUS,  Property::BOOLEAN, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
508 const PropertyRegistration Control::Impl::PROPERTY_5( typeRegistration, "background",      Toolkit::Control::Property::BACKGROUND,       Property::MAP,     &Control::Impl::SetProperty, &Control::Impl::GetProperty );
509 const PropertyRegistration Control::Impl::PROPERTY_6( typeRegistration, "tooltip",         Toolkit::DevelControl::Property::TOOLTIP,     Property::MAP,     &Control::Impl::SetProperty, &Control::Impl::GetProperty );
510
511 Toolkit::Control Control::New()
512 {
513   // Create the implementation, temporarily owned on stack
514   IntrusivePtr<Control> controlImpl = new Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) );
515
516   // Pass ownership to handle
517   Toolkit::Control handle( *controlImpl );
518
519   // Second-phase init of the implementation
520   // This can only be done after the CustomActor connection has been made...
521   controlImpl->Initialize();
522
523   return handle;
524 }
525
526 void Control::SetStyleName( const std::string& styleName )
527 {
528   if( styleName != mImpl->mStyleName )
529   {
530     mImpl->mStyleName = styleName;
531
532     // Apply new style, if stylemanager is available
533     Toolkit::StyleManager styleManager = Toolkit::StyleManager::Get();
534     if( styleManager )
535     {
536       GetImpl( styleManager ).ApplyThemeStyle( Toolkit::Control( GetOwner() ) );
537     }
538   }
539 }
540
541 const std::string& Control::GetStyleName() const
542 {
543   return mImpl->mStyleName;
544 }
545
546 void Control::SetBackgroundColor( const Vector4& color )
547 {
548   mImpl->mBackgroundColor = color;
549   Property::Map map;
550   map[ Toolkit::DevelVisual::Property::TYPE ] = Toolkit::Visual::COLOR;
551   map[ Toolkit::ColorVisual::Property::MIX_COLOR ] = color;
552
553   SetBackground( map );
554 }
555
556 Vector4 Control::GetBackgroundColor() const
557 {
558   return mImpl->mBackgroundColor;
559 }
560
561 void Control::SetBackground( const Property::Map& map )
562 {
563   Toolkit::Visual::Base visual = Toolkit::VisualFactory::Get().CreateVisual( map );
564   if( visual )
565   {
566     RegisterVisual( Toolkit::Control::Property::BACKGROUND, visual );
567     visual.SetDepthIndex( DepthIndex::BACKGROUND );
568
569     // Trigger a size negotiation request that may be needed by the new visual to relayout its contents.
570     RelayoutRequest();
571   }
572 }
573
574 void Control::SetBackgroundImage( Image image )
575 {
576   Toolkit::Visual::Base visual = Toolkit::VisualFactory::Get().CreateVisual( image );
577   if( visual )
578   {
579     RegisterVisual( Toolkit::Control::Property::BACKGROUND, visual );
580     visual.SetDepthIndex( DepthIndex::BACKGROUND );
581   }
582 }
583
584 void Control::ClearBackground()
585 {
586    UnregisterVisual( Toolkit::Control::Property::BACKGROUND );
587    mImpl->mBackgroundColor = Color::TRANSPARENT;
588
589    // Trigger a size negotiation request that may be needed when unregistering a visual.
590    RelayoutRequest();
591 }
592
593 void Control::EnableGestureDetection(Gesture::Type type)
594 {
595   if ( (type & Gesture::Pinch) && !mImpl->mPinchGestureDetector )
596   {
597     mImpl->mPinchGestureDetector = PinchGestureDetector::New();
598     mImpl->mPinchGestureDetector.DetectedSignal().Connect(mImpl, &Impl::PinchDetected);
599     mImpl->mPinchGestureDetector.Attach(Self());
600   }
601
602   if ( (type & Gesture::Pan) && !mImpl->mPanGestureDetector )
603   {
604     mImpl->mPanGestureDetector = PanGestureDetector::New();
605     mImpl->mPanGestureDetector.DetectedSignal().Connect(mImpl, &Impl::PanDetected);
606     mImpl->mPanGestureDetector.Attach(Self());
607   }
608
609   if ( (type & Gesture::Tap) && !mImpl->mTapGestureDetector )
610   {
611     mImpl->mTapGestureDetector = TapGestureDetector::New();
612     mImpl->mTapGestureDetector.DetectedSignal().Connect(mImpl, &Impl::TapDetected);
613     mImpl->mTapGestureDetector.Attach(Self());
614   }
615
616   if ( (type & Gesture::LongPress) && !mImpl->mLongPressGestureDetector )
617   {
618     mImpl->mLongPressGestureDetector = LongPressGestureDetector::New();
619     mImpl->mLongPressGestureDetector.DetectedSignal().Connect(mImpl, &Impl::LongPressDetected);
620     mImpl->mLongPressGestureDetector.Attach(Self());
621   }
622 }
623
624 void Control::DisableGestureDetection(Gesture::Type type)
625 {
626   if ( (type & Gesture::Pinch) && mImpl->mPinchGestureDetector )
627   {
628     mImpl->mPinchGestureDetector.Detach(Self());
629     mImpl->mPinchGestureDetector.Reset();
630   }
631
632   if ( (type & Gesture::Pan) && mImpl->mPanGestureDetector )
633   {
634     mImpl->mPanGestureDetector.Detach(Self());
635     mImpl->mPanGestureDetector.Reset();
636   }
637
638   if ( (type & Gesture::Tap) && mImpl->mTapGestureDetector )
639   {
640     mImpl->mTapGestureDetector.Detach(Self());
641     mImpl->mTapGestureDetector.Reset();
642   }
643
644   if ( (type & Gesture::LongPress) && mImpl->mLongPressGestureDetector)
645   {
646     mImpl->mLongPressGestureDetector.Detach(Self());
647     mImpl->mLongPressGestureDetector.Reset();
648   }
649 }
650
651 PinchGestureDetector Control::GetPinchGestureDetector() const
652 {
653   return mImpl->mPinchGestureDetector;
654 }
655
656 PanGestureDetector Control::GetPanGestureDetector() const
657 {
658   return mImpl->mPanGestureDetector;
659 }
660
661 TapGestureDetector Control::GetTapGestureDetector() const
662 {
663   return mImpl->mTapGestureDetector;
664 }
665
666 LongPressGestureDetector Control::GetLongPressGestureDetector() const
667 {
668   return mImpl->mLongPressGestureDetector;
669 }
670
671 void Control::SetKeyboardNavigationSupport(bool isSupported)
672 {
673   mImpl->mIsKeyboardNavigationSupported = isSupported;
674 }
675
676 bool Control::IsKeyboardNavigationSupported()
677 {
678   return mImpl->mIsKeyboardNavigationSupported;
679 }
680
681 void Control::SetKeyInputFocus()
682 {
683   if( Self().OnStage() )
684   {
685     Toolkit::KeyInputFocusManager::Get().SetFocus(Toolkit::Control::DownCast(Self()));
686   }
687 }
688
689 bool Control::HasKeyInputFocus()
690 {
691   bool result = false;
692   if( Self().OnStage() )
693   {
694     result = Toolkit::KeyInputFocusManager::Get().IsKeyboardListener(Toolkit::Control::DownCast(Self()));
695   }
696   return result;
697 }
698
699 void Control::ClearKeyInputFocus()
700 {
701   if( Self().OnStage() )
702   {
703     Toolkit::KeyInputFocusManager::Get().RemoveFocus(Toolkit::Control::DownCast(Self()));
704   }
705 }
706
707 void Control::SetAsKeyboardFocusGroup(bool isFocusGroup)
708 {
709   mImpl->mIsKeyboardFocusGroup = isFocusGroup;
710
711   // The following line will be removed when the deprecated API in KeyboardFocusManager is deleted
712   Toolkit::KeyboardFocusManager::Get().SetAsFocusGroup(Self(), isFocusGroup);
713 }
714
715 bool Control::IsKeyboardFocusGroup()
716 {
717   return Toolkit::KeyboardFocusManager::Get().IsFocusGroup(Self());
718 }
719
720 void Control::AccessibilityActivate()
721 {
722   // Inform deriving classes
723   OnAccessibilityActivated();
724 }
725
726 void Control::KeyboardEnter()
727 {
728   // Inform deriving classes
729   OnKeyboardEnter();
730 }
731
732 void Control::RegisterVisual( Property::Index index, Toolkit::Visual::Base& visual )
733 {
734   RegisterVisual( index, visual, true );
735 }
736
737 void Control::RegisterVisual( Property::Index index, Toolkit::Visual::Base& visual, bool enabled )
738 {
739   bool visualReplaced ( false );
740   Actor self = Self();
741
742   if( !mImpl->mVisuals.Empty() )
743   {
744     RegisteredVisualContainer::Iterator iter;
745     // Check if visual (index) is already registered.  Replace if so.
746     if ( FindVisual( index, mImpl->mVisuals, iter ) )
747     {
748       if( (*iter)->visual && self.OnStage() )
749       {
750         Toolkit::GetImplementation((*iter)->visual).SetOffStage( self );
751       }
752       (*iter)->visual = visual;
753       visualReplaced = true;
754     }
755   }
756
757   // If not set, set the name of the visual to the same name as the control's property.
758   // ( If the control has been type registered )
759   if( visual.GetName().empty() )
760   {
761     // Check if the control has been type registered:
762     TypeInfo typeInfo = TypeRegistry::Get().GetTypeInfo( typeid(*this) );
763     if( typeInfo )
764     {
765       // Check if the property index has been registered:
766       Property::IndexContainer indices;
767       typeInfo.GetPropertyIndices( indices );
768       Property::IndexContainer::Iterator iter = std::find( indices.Begin(), indices.End(), index );
769       if( iter != indices.End() )
770       {
771         // If it has, then get it's name and use that for the visual
772         std::string visualName = typeInfo.GetPropertyName( index );
773         visual.SetName( visualName );
774       }
775     }
776   }
777
778   if( !visualReplaced ) // New registration entry
779   {
780     mImpl->mVisuals.PushBack( new RegisteredVisual( index, visual, enabled ) );
781   }
782
783   if( visual && self.OnStage() && enabled )
784   {
785     Toolkit::GetImplementation(visual).SetOnStage( self );
786   }
787
788   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::RegisterVisual() Registered %s(%d), enabled:%s\n",  visual.GetName().c_str(), index, enabled?"T":"F" );
789 }
790
791 void Control::UnregisterVisual( Property::Index index )
792 {
793    RegisteredVisualContainer::Iterator iter;
794    if ( FindVisual( index, mImpl->mVisuals, iter ) )
795    {
796      Actor self( Self() );
797      Toolkit::GetImplementation((*iter)->visual).SetOffStage( self );
798      (*iter)->visual.Reset();
799      mImpl->mVisuals.Erase( iter );
800    }
801 }
802
803 Toolkit::Visual::Base Control::GetVisual( Property::Index index ) const
804 {
805   RegisteredVisualContainer::Iterator iter;
806   if ( FindVisual( index, mImpl->mVisuals, iter ) )
807   {
808     return (*iter)->visual;
809   }
810
811   return Toolkit::Visual::Base();
812 }
813
814 void Control::EnableVisual( Property::Index index, bool enable )
815 {
816   RegisteredVisualContainer::Iterator iter;
817   if ( FindVisual( index, mImpl->mVisuals, iter ) )
818   {
819     if (  (*iter)->enabled == enable )
820     {
821       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::EnableVisual Visual %s(%d) already %s\n", (*iter)->visual.GetName().c_str(), index, enable?"enabled":"disabled");
822       return;
823     }
824
825     (*iter)->enabled = enable;
826     Actor parentActor = Self();
827     if ( Self().OnStage() ) // If control not on Stage then Visual will be added when StageConnection is called.
828     {
829       if ( enable )
830       {
831         DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::EnableVisual Setting %s(%d) on stage \n", (*iter)->visual.GetName().c_str(), index );
832         Toolkit::GetImplementation((*iter)->visual).SetOnStage( parentActor );
833       }
834       else
835       {
836         DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::EnableVisual Setting %s(%d) off stage \n", (*iter)->visual.GetName().c_str(), index );
837         Toolkit::GetImplementation((*iter)->visual).SetOffStage( parentActor );  // No need to call if control not staged.
838       }
839     }
840   }
841 }
842
843 bool Control::IsVisualEnabled( Property::Index index ) const
844 {
845   RegisteredVisualContainer::Iterator iter;
846   if ( FindVisual( index, mImpl->mVisuals, iter ) )
847   {
848     return (*iter)->enabled;
849   }
850   return false;
851 }
852
853 Dali::Animation Control::CreateTransition( const Toolkit::TransitionData& handle )
854 {
855   Dali::Animation transition;
856   const Internal::TransitionData& transitionData = Toolkit::GetImplementation( handle );
857
858   if( transitionData.Count() > 0 )
859   {
860     // Setup a Transition from TransitionData.
861     TransitionData::Iterator end = transitionData.End();
862     for( TransitionData::Iterator iter = transitionData.Begin() ;
863          iter != end; ++iter )
864     {
865       TransitionData::Animator* animator = (*iter);
866
867       Toolkit::Visual::Base visual = GetVisualByName( mImpl->mVisuals, animator->objectName );
868
869       if( visual )
870       {
871         Internal::Visual::Base& visualImpl = Toolkit::GetImplementation( visual );
872         visualImpl.AnimateProperty( transition, *animator );
873       }
874       else
875       {
876         // Otherwise, try any actor children of control (Including the control)
877         Actor child = Self().FindChildByName( animator->objectName );
878         if( child )
879         {
880           Property::Index propertyIndex = DevelHandle::GetPropertyIndex( child, animator->propertyKey );
881           if( propertyIndex != Property::INVALID_INDEX )
882           {
883             if( animator->animate == false )
884             {
885               if( animator->targetValue.GetType() != Property::NONE )
886               {
887                 child.SetProperty( propertyIndex, animator->targetValue );
888               }
889             }
890             else // animate the property
891             {
892               if( animator->initialValue.GetType() != Property::NONE )
893               {
894                 child.SetProperty( propertyIndex, animator->initialValue );
895               }
896
897               if( ! transition )
898               {
899                 transition = Dali::Animation::New( 0.1f );
900               }
901
902               transition.AnimateTo( Property( child, propertyIndex ),
903                                     animator->targetValue,
904                                     animator->alphaFunction,
905                                     TimePeriod( animator->timePeriodDelay,
906                                                 animator->timePeriodDuration ) );
907             }
908           }
909         }
910       }
911     }
912   }
913
914   return transition;
915 }
916
917 bool Control::OnAccessibilityActivated()
918 {
919   return false; // Accessibility activation is not handled by default
920 }
921
922 bool Control::OnKeyboardEnter()
923 {
924   return false; // Keyboard enter is not handled by default
925 }
926
927 bool Control::OnAccessibilityPan(PanGesture gesture)
928 {
929   return false; // Accessibility pan gesture is not handled by default
930 }
931
932 bool Control::OnAccessibilityTouch(const TouchEvent& touchEvent)
933 {
934   return false; // Accessibility touch event is not handled by default
935 }
936
937 bool Control::OnAccessibilityValueChange(bool isIncrease)
938 {
939   return false; // Accessibility value change action is not handled by default
940 }
941
942 bool Control::OnAccessibilityZoom()
943 {
944   return false; // Accessibility zoom action is not handled by default
945 }
946
947 Actor Control::GetNextKeyboardFocusableActor(Actor currentFocusedActor, Toolkit::Control::KeyboardFocus::Direction direction, bool loopEnabled)
948 {
949   return Actor();
950 }
951
952 void Control::OnKeyboardFocusChangeCommitted(Actor commitedFocusableActor)
953 {
954 }
955
956 Toolkit::Control::KeyEventSignalType& Control::KeyEventSignal()
957 {
958   return mImpl->mKeyEventSignal;
959 }
960
961 Toolkit::Control::KeyInputFocusSignalType& Control::KeyInputFocusGainedSignal()
962 {
963   return mImpl->mKeyInputFocusGainedSignal;
964 }
965
966 Toolkit::Control::KeyInputFocusSignalType& Control::KeyInputFocusLostSignal()
967 {
968   return mImpl->mKeyInputFocusLostSignal;
969 }
970
971 bool Control::EmitKeyEventSignal( const KeyEvent& event )
972 {
973   // Guard against destruction during signal emission
974   Dali::Toolkit::Control handle( GetOwner() );
975
976   bool consumed = false;
977
978   // signals are allocated dynamically when someone connects
979   if ( !mImpl->mKeyEventSignal.Empty() )
980   {
981     consumed = mImpl->mKeyEventSignal.Emit( handle, event );
982   }
983
984   if (!consumed)
985   {
986     // Notification for derived classes
987     consumed = OnKeyEvent(event);
988   }
989
990   return consumed;
991 }
992
993 Control::Control( ControlBehaviour behaviourFlags )
994 : CustomActorImpl( static_cast< ActorFlags >( behaviourFlags ) ),
995   mImpl(new Impl(*this))
996 {
997   mImpl->mFlags = behaviourFlags;
998 }
999
1000 Control::~Control()
1001 {
1002   delete mImpl;
1003 }
1004
1005 void Control::Initialize()
1006 {
1007   // Call deriving classes so initialised before styling is applied to them.
1008   OnInitialize();
1009
1010   if( (mImpl->mFlags & REQUIRES_STYLE_CHANGE_SIGNALS) ||
1011       !(mImpl->mFlags & DISABLE_STYLE_CHANGE_SIGNALS) )
1012   {
1013     Toolkit::StyleManager styleManager = StyleManager::Get();
1014
1015     // if stylemanager is available
1016     if( styleManager )
1017     {
1018       StyleManager& styleManagerImpl = GetImpl( styleManager );
1019
1020       // Register for style changes
1021       styleManagerImpl.ControlStyleChangeSignal().Connect( this, &Control::OnStyleChange );
1022
1023       // Apply the current style
1024       styleManagerImpl.ApplyThemeStyleAtInit( Toolkit::Control( GetOwner() ) );
1025     }
1026   }
1027
1028   if( mImpl->mFlags & REQUIRES_KEYBOARD_NAVIGATION_SUPPORT )
1029   {
1030     SetKeyboardNavigationSupport( true );
1031   }
1032 }
1033
1034 void Control::OnInitialize()
1035 {
1036 }
1037
1038 void Control::OnControlChildAdd( Actor& child )
1039 {
1040 }
1041
1042 void Control::OnControlChildRemove( Actor& child )
1043 {
1044 }
1045
1046 void Control::OnStyleChange( Toolkit::StyleManager styleManager, StyleChange::Type change )
1047 {
1048   // By default the control is only interested in theme (not font) changes
1049   if( styleManager && change == StyleChange::THEME_CHANGE )
1050   {
1051     GetImpl( styleManager ).ApplyThemeStyle( Toolkit::Control( GetOwner() ) );
1052   }
1053   RelayoutRequest();
1054 }
1055
1056 void Control::OnPinch(const PinchGesture& pinch)
1057 {
1058   if( !( mImpl->mStartingPinchScale ) )
1059   {
1060     // lazy allocate
1061     mImpl->mStartingPinchScale = new Vector3;
1062   }
1063
1064   if( pinch.state == Gesture::Started )
1065   {
1066     *( mImpl->mStartingPinchScale ) = Self().GetCurrentScale();
1067   }
1068
1069   Self().SetScale( *( mImpl->mStartingPinchScale ) * pinch.scale );
1070 }
1071
1072 void Control::OnPan( const PanGesture& pan )
1073 {
1074 }
1075
1076 void Control::OnTap(const TapGesture& tap)
1077 {
1078 }
1079
1080 void Control::OnLongPress( const LongPressGesture& longPress )
1081 {
1082 }
1083
1084 void Control::EmitKeyInputFocusSignal( bool focusGained )
1085 {
1086   Dali::Toolkit::Control handle( GetOwner() );
1087
1088   if ( focusGained )
1089   {
1090     // signals are allocated dynamically when someone connects
1091     if ( !mImpl->mKeyInputFocusGainedSignal.Empty() )
1092     {
1093       mImpl->mKeyInputFocusGainedSignal.Emit( handle );
1094     }
1095   }
1096   else
1097   {
1098     // signals are allocated dynamically when someone connects
1099     if ( !mImpl->mKeyInputFocusLostSignal.Empty() )
1100     {
1101       mImpl->mKeyInputFocusLostSignal.Emit( handle );
1102     }
1103   }
1104 }
1105
1106 void Control::OnStageConnection( int depth )
1107 {
1108   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::OnStageConnection number of registered visuals(%d)\n",  mImpl->mVisuals.Size() );
1109
1110   Actor self( Self() );
1111
1112   for(RegisteredVisualContainer::Iterator iter = mImpl->mVisuals.Begin(); iter!= mImpl->mVisuals.End(); iter++)
1113   {
1114     // Check whether the visual is empty and enabled
1115     if( (*iter)->visual && (*iter)->enabled )
1116     {
1117       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::OnStageConnection Setting visual(%d) on stage\n", (*iter)->index );
1118       Toolkit::GetImplementation((*iter)->visual).SetOnStage( self );
1119     }
1120   }
1121
1122   if( mImpl->mVisuals.Empty() && ! self.GetRendererCount() )
1123   {
1124     Property::Value clippingValue = self.GetProperty( Actor::Property::CLIPPING_MODE );
1125     int clippingMode = ClippingMode::DISABLED;
1126     if( clippingValue.Get( clippingMode ) )
1127     {
1128       // Add a transparent background if we do not have any renderers or visuals so we clip our children
1129
1130       if( clippingMode == ClippingMode::CLIP_CHILDREN )
1131       {
1132         // Create a transparent background visual which will also get staged.
1133         SetBackgroundColor( Color::TRANSPARENT );
1134       }
1135     }
1136   }
1137 }
1138
1139 void Control::OnStageDisconnection()
1140 {
1141   for(RegisteredVisualContainer::Iterator iter = mImpl->mVisuals.Begin(); iter!= mImpl->mVisuals.End(); iter++)
1142   {
1143     // Check whether the visual is empty
1144     if( (*iter)->visual )
1145     {
1146       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::OnStageDisconnection Setting visual(%d) off stage\n", (*iter)->index );
1147       Actor self( Self() );
1148       Toolkit::GetImplementation((*iter)->visual).SetOffStage( self );
1149     }
1150   }
1151 }
1152
1153 void Control::OnKeyInputFocusGained()
1154 {
1155   EmitKeyInputFocusSignal( true );
1156 }
1157
1158 void Control::OnKeyInputFocusLost()
1159 {
1160   EmitKeyInputFocusSignal( false );
1161 }
1162
1163 void Control::OnChildAdd(Actor& child)
1164 {
1165   // Notify derived classes.
1166   OnControlChildAdd( child );
1167 }
1168
1169 void Control::OnChildRemove(Actor& child)
1170 {
1171   // Notify derived classes.
1172   OnControlChildRemove( child );
1173 }
1174
1175 void Control::OnPropertySet( Property::Index index, Property::Value propertyValue )
1176 {
1177   Actor self( Self() );
1178   if( index == Actor::Property::CLIPPING_MODE )
1179   {
1180     // Only set the background if we're already on the stage and have no renderers or visuals
1181
1182     if( mImpl->mVisuals.Empty() && ! self.GetRendererCount() && self.OnStage() )
1183     {
1184       ClippingMode::Type clippingMode = ClippingMode::DISABLED;
1185       if( Scripting::GetEnumerationProperty< ClippingMode::Type >( propertyValue, CLIPPING_MODE_TABLE, CLIPPING_MODE_TABLE_COUNT, clippingMode ) )
1186       {
1187         // Add a transparent background if we do not have one so we clip children
1188
1189         if( clippingMode == ClippingMode::CLIP_CHILDREN )
1190         {
1191           SetBackgroundColor( Color::TRANSPARENT );
1192         }
1193       }
1194     }
1195   }
1196 }
1197
1198 void Control::OnSizeSet(const Vector3& targetSize)
1199 {
1200   Toolkit::Visual::Base visual = GetVisual( Toolkit::Control::Property::BACKGROUND );
1201   if( visual )
1202   {
1203     Vector2 size( targetSize );
1204     visual.SetTransformAndSize( Property::Map(), size ); // Send an empty map as we do not want to modify the visual's set transform
1205   }
1206 }
1207
1208 void Control::OnSizeAnimation(Animation& animation, const Vector3& targetSize)
1209 {
1210   // @todo size negotiate background to new size, animate as well?
1211 }
1212
1213 bool Control::OnTouchEvent(const TouchEvent& event)
1214 {
1215   return false; // Do not consume
1216 }
1217
1218 bool Control::OnHoverEvent(const HoverEvent& event)
1219 {
1220   return false; // Do not consume
1221 }
1222
1223 bool Control::OnKeyEvent(const KeyEvent& event)
1224 {
1225   return false; // Do not consume
1226 }
1227
1228 bool Control::OnWheelEvent(const WheelEvent& event)
1229 {
1230   return false; // Do not consume
1231 }
1232
1233 void Control::OnRelayout( const Vector2& size, RelayoutContainer& container )
1234 {
1235   for( unsigned int i = 0, numChildren = Self().GetChildCount(); i < numChildren; ++i )
1236   {
1237     container.Add( Self().GetChildAt( i ), size );
1238   }
1239
1240   Toolkit::Visual::Base visual = GetVisual( Toolkit::Control::Property::BACKGROUND );
1241   if( visual )
1242   {
1243     visual.SetTransformAndSize( Property::Map(), size ); // Send an empty map as we do not want to modify the visual's set transform
1244   }
1245 }
1246
1247 void Control::OnSetResizePolicy( ResizePolicy::Type policy, Dimension::Type dimension )
1248 {
1249 }
1250
1251 Vector3 Control::GetNaturalSize()
1252 {
1253   Toolkit::Visual::Base visual = GetVisual( Toolkit::Control::Property::BACKGROUND );
1254   if( visual )
1255   {
1256     Vector2 naturalSize;
1257     visual.GetNaturalSize( naturalSize );
1258     return Vector3( naturalSize );
1259   }
1260   return Vector3::ZERO;
1261 }
1262
1263 float Control::CalculateChildSize( const Dali::Actor& child, Dimension::Type dimension )
1264 {
1265   return CalculateChildSizeBase( child, dimension );
1266 }
1267
1268 float Control::GetHeightForWidth( float width )
1269 {
1270   return GetHeightForWidthBase( width );
1271 }
1272
1273 float Control::GetWidthForHeight( float height )
1274 {
1275   return GetWidthForHeightBase( height );
1276 }
1277
1278 bool Control::RelayoutDependentOnChildren( Dimension::Type dimension )
1279 {
1280   return RelayoutDependentOnChildrenBase( dimension );
1281 }
1282
1283 void Control::OnCalculateRelayoutSize( Dimension::Type dimension )
1284 {
1285 }
1286
1287 void Control::OnLayoutNegotiated( float size, Dimension::Type dimension )
1288 {
1289 }
1290
1291 void Control::SignalConnected( SlotObserver* slotObserver, CallbackBase* callback )
1292 {
1293   mImpl->SignalConnected( slotObserver, callback );
1294 }
1295
1296 void Control::SignalDisconnected( SlotObserver* slotObserver, CallbackBase* callback )
1297 {
1298   mImpl->SignalDisconnected( slotObserver, callback );
1299 }
1300
1301 Control& GetImplementation( Dali::Toolkit::Control& handle )
1302 {
1303   CustomActorImpl& customInterface = handle.GetImplementation();
1304   // downcast to control
1305   Control& impl = dynamic_cast< Internal::Control& >( customInterface );
1306   return impl;
1307 }
1308
1309 const Control& GetImplementation( const Dali::Toolkit::Control& handle )
1310 {
1311   const CustomActorImpl& customInterface = handle.GetImplementation();
1312   // downcast to control
1313   const Control& impl = dynamic_cast< const Internal::Control& >( customInterface );
1314   return impl;
1315 }
1316
1317 } // namespace Internal
1318
1319 } // namespace Toolkit
1320
1321 } // namespace Dali