5ecacd787464d808f0ef738cdf93b70e67d078d0
[platform/core/uifw/dali-toolkit.git] / base / dali-toolkit / public-api / controls / control-impl.cpp
1 //
2 // Copyright (c) 2014 Samsung Electronics Co., Ltd.
3 //
4 // Licensed under the Flora License, Version 1.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://floralicense.org/license/
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 #include <dali-toolkit/public-api/controls/control-impl.h>
18
19 #include <stack>
20
21 #include <dali/integration-api/debug.h>
22
23 #include "dali-toolkit/internal/controls/relayout-controller.h"
24 #include "dali-toolkit/internal/controls/relayout-helper.h"
25 #include "dali-toolkit/public-api/focus-manager/keyinput-focus-manager.h"
26 #include "dali-toolkit/public-api/focus-manager/keyboard-focus-manager.h"
27 #include <dali-toolkit/public-api/controls/control.h>
28
29 #include <dali-toolkit/public-api/styling/style-manager.h>
30 #include <dali-toolkit/internal/styling/style-manager-impl.h>
31
32 namespace Dali
33 {
34
35 namespace Toolkit
36 {
37
38 const Property::Index Control::PROPERTY_BACKGROUND_COLOR      = Internal::Control::CONTROL_PROPERTY_START_INDEX;
39 const Property::Index Control::PROPERTY_BACKGROUND            = Internal::Control::CONTROL_PROPERTY_START_INDEX + 1;
40 const Property::Index Control::PROPERTY_WIDTH_POLICY          = Internal::Control::CONTROL_PROPERTY_START_INDEX + 2;
41 const Property::Index Control::PROPERTY_HEIGHT_POLICY         = Internal::Control::CONTROL_PROPERTY_START_INDEX + 3;
42 const Property::Index Control::PROPERTY_MINIMUM_SIZE          = Internal::Control::CONTROL_PROPERTY_START_INDEX + 4;
43 const Property::Index Control::PROPERTY_MAXIMUM_SIZE          = Internal::Control::CONTROL_PROPERTY_START_INDEX + 5;
44 const Property::Index Control::PROPERTY_KEY_INPUT_FOCUS       = Internal::Control::CONTROL_PROPERTY_START_INDEX + 6;
45
46 namespace
47 {
48
49 const Scripting::StringEnum< Control::SizePolicy > SIZE_POLICY_STRING_TABLE[] =
50 {
51   { "FIXED",      Control::Fixed      },
52   { "MINIMUM",    Control::Minimum    },
53   { "MAXIMUM",    Control::Maximum    },
54   { "RANGE",      Control::Range      },
55   { "FLEXIBLE",   Control::Flexible   },
56 };
57 const unsigned int SIZE_POLICY_STRING_TABLE_COUNT = sizeof( SIZE_POLICY_STRING_TABLE ) / sizeof( SIZE_POLICY_STRING_TABLE[0] );
58
59 #if defined(DEBUG_ENABLED)
60 Integration::Log::Filter* gLogFilter  = Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_CONTROL");
61 #endif
62
63 const float MAX_FLOAT_VALUE( std::numeric_limits<float>::max() );
64 const float BACKGROUND_ACTOR_Z_POSITION( -0.1f );
65
66 BaseHandle Create()
67 {
68   return Internal::Control::New();
69 }
70
71 TypeRegistration CONTROL_TYPE( typeid(Control), typeid(CustomActor), Create );
72
73 // Property Registration after Internal::Control::Impl definition below
74
75 TypeAction ACTION_TYPE_1(CONTROL_TYPE, Toolkit::Control::ACTION_CONTROL_ACTIVATED, &Internal::Control::DoAction);
76
77 /**
78  * Helper class used to set the Control's size through the Actor's API or through children added.
79  */
80 class SetSizeLock
81 {
82 public:
83   SetSizeLock( bool& lock )
84   : mLock( lock )
85   {
86     mLock = true;
87   }
88
89   ~SetSizeLock()
90   {
91     mLock = false;
92   }
93
94 private:
95   bool& mLock;
96 };
97
98 /**
99  * Structure which holds information about the background of a control
100  */
101 struct Background
102 {
103   Actor actor;   ///< Either a MeshActor or an ImageActor
104   Vector4 color; ///< The color of the actor.
105
106   /**
107    * Constructor
108    */
109   Background()
110   : actor(),
111     color( Color::WHITE )
112   {
113   }
114 };
115
116 /**
117  * Helper function to calculate a dimension given the policy of that dimension; the minimum &
118  * maximum values that dimension can be; and the allocated value for that dimension.
119  *
120  * @param[in]  policy     The size policy for that dimension.
121  * @param[in]  minimum    The minimum value that dimension can be.
122  * @param[in]  maximum    The maximum value that dimension can be.
123  * @param[in]  allocated  The value allocated for that dimension.
124  *
125  * @return The value that the dimension should be.
126  *
127  * @note This does not handle Control::Fixed policy.
128  */
129 float Calculate( Control::SizePolicy policy, float minimum, float maximum, float allocated )
130 {
131   float size( allocated );
132
133   switch( policy )
134   {
135     case Control::Fixed:
136     {
137       // Use allocated value
138       break;
139     }
140
141     case Control::Minimum:
142     {
143       // Size is always at least the minimum.
144       size = std::max( allocated, minimum );
145       break;
146     }
147
148     case Control::Maximum:
149     {
150       // Size can grow but up to a maximum value.
151       size = std::min( allocated, maximum );
152       break;
153     }
154
155     case Control::Range:
156     {
157       // Size is at least the minimum and can grow up to the maximum
158       size = std::max( size, minimum );
159       size = std::min( size, maximum );
160      break;
161     }
162
163     case Control::Flexible:
164     {
165       // Size grows or shrinks with no limits.
166       size = allocated;
167       break;
168     }
169
170     default:
171     {
172       DALI_ASSERT_DEBUG( false && "This function was not intended to be used by any other policy." );
173       break;
174     }
175   }
176
177   return size;
178 }
179
180 /**
181  * Creates a white coloured Mesh.
182  */
183 Mesh CreateMesh()
184 {
185   Vector3 white( Color::WHITE );
186
187   MeshData meshData;
188
189   // Create vertices with a white color (actual color is set by actor color)
190   MeshData::VertexContainer vertices(4);
191   vertices[ 0 ] = MeshData::Vertex( Vector3( -0.5f, -0.5f, 0.0f ), Vector2::ZERO, white );
192   vertices[ 1 ] = MeshData::Vertex( Vector3(  0.5f, -0.5f, 0.0f ), Vector2::ZERO, white );
193   vertices[ 2 ] = MeshData::Vertex( Vector3( -0.5f,  0.5f, 0.0f ), Vector2::ZERO, white );
194   vertices[ 3 ] = MeshData::Vertex( Vector3(  0.5f,  0.5f, 0.0f ), Vector2::ZERO, white );
195
196   // Specify all the faces
197   MeshData::FaceIndices faces;
198   faces.reserve( 6 ); // 2 triangles in Quad
199   faces.push_back( 0 ); faces.push_back( 3 ); faces.push_back( 1 );
200   faces.push_back( 0 ); faces.push_back( 2 ); faces.push_back( 3 );
201
202   // Create the mesh data from the vertices and faces
203   meshData.SetMaterial( Material::New( "ControlMaterial" ) );
204   meshData.SetVertices( vertices );
205   meshData.SetFaceIndices( faces );
206   meshData.SetHasColor( true );
207
208   return Mesh::New( meshData );
209 }
210
211 /**
212  * Sets all the required properties for the background actor.
213  *
214  * @param[in]  actor              The actor to set the properties on.
215  * @param[in]  constrainingIndex  The property index to constrain the parent's size on.
216  * @param[in]  color              The required color of the actor.
217  */
218 void SetupBackgroundActor( Actor actor, Property::Index constrainingIndex, const Vector4& color )
219 {
220   actor.SetColor( color );
221   actor.SetPositionInheritanceMode( USE_PARENT_POSITION_PLUS_LOCAL_POSITION );
222   actor.SetZ( BACKGROUND_ACTOR_Z_POSITION );
223
224   Constraint constraint = Constraint::New<Vector3>( constrainingIndex,
225                                                     ParentSource( Actor::SIZE ),
226                                                     EqualToConstraint() );
227   actor.ApplyConstraint( constraint );
228 }
229
230 } // unnamed namespace
231
232 namespace Internal
233 {
234
235 class Control::Impl : public ConnectionTrackerInterface
236 {
237 public:
238   // Construction & Destruction
239   Impl(Control& controlImpl)
240   : mControlImpl(controlImpl),
241     mInitialized( false ),
242     mPinchGestureDetector(),
243     mPanGestureDetector(),
244     mTapGestureDetector(),
245     mLongPressGestureDetector(),
246     mStartingPinchScale(),
247     mLockSetSize( false ),
248     mWidthPolicy( Toolkit::Control::Fixed ),
249     mHeightPolicy( Toolkit::Control::Fixed ),
250     mSize(),
251     mSetSize(),
252     mMinimumSize(),
253     mMaximumSize( MAX_FLOAT_VALUE, MAX_FLOAT_VALUE, MAX_FLOAT_VALUE ),
254     mIsKeyboardNavigationSupported(false),
255     mIsKeyboardFocusGroup(false),
256     mKeyEventSignalV2(),
257     mBackground( NULL ),
258     mFlags( Control::CONTROL_BEHAVIOUR_NONE )
259   {
260   }
261
262   ~Impl()
263   {
264     // All gesture detectors will be destroyed so no need to disconnect.
265     if ( mBackground )
266     {
267       delete mBackground;
268     }
269   }
270
271   // Gesture Detection Methods
272
273   void PinchDetected(Actor actor, PinchGesture pinch)
274   {
275     mControlImpl.OnPinch(pinch);
276   }
277
278   void PanDetected(Actor actor, PanGesture pan)
279   {
280     mControlImpl.OnPan(pan);
281   }
282
283   void TapDetected(Actor actor, TapGesture tap)
284   {
285     mControlImpl.OnTap(tap);
286   }
287
288   void LongPressDetected(Actor actor, LongPressGesture longPress)
289   {
290     mControlImpl.OnLongPress(longPress);
291   }
292
293   /**
294    * @copydoc ConnectionTrackerInterface::SignalConnected
295    */
296   virtual void SignalConnected( SlotObserver* slotObserver, CallbackBase* callback )
297   {
298     mConnectionTracker.SignalConnected( slotObserver, callback );
299   }
300
301   /**
302    * @copydoc ConnectionTrackerInterface::SignalDisconnected
303    */
304   virtual void SignalDisconnected( SlotObserver* slotObserver, CallbackBase* callback )
305   {
306     mConnectionTracker.SignalDisconnected( slotObserver, callback );
307   }
308
309   /**
310    * @copydoc ConnectionTrackerInterface::GetConnectionCount
311    */
312   virtual std::size_t GetConnectionCount() const
313   {
314     return mConnectionTracker.GetConnectionCount();
315   }
316
317   // Background Methods
318
319   /**
320    * Only creates an instance of the background if we actually use it.
321    * @return A reference to the Background structure.
322    */
323   Background& GetBackground()
324   {
325     if ( !mBackground )
326     {
327       mBackground = new Background;
328     }
329     return *mBackground;
330   }
331
332   // Properties
333
334   /**
335    * Called when a property of an object of this type is set.
336    * @param[in] object The object whose property is set.
337    * @param[in] index The property index.
338    * @param[in] value The new property value.
339    */
340   static void SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
341   {
342     Toolkit::Control control = Toolkit::Control::DownCast( BaseHandle( object ) );
343
344     if ( control )
345     {
346       Control& controlImpl( control.GetImplementation() );
347
348       switch ( index )
349       {
350         case Toolkit::Control::PROPERTY_BACKGROUND_COLOR:
351         {
352           controlImpl.SetBackgroundColor( value.Get< Vector4 >() );
353           break;
354         }
355
356         case Toolkit::Control::PROPERTY_BACKGROUND:
357         {
358           if ( value.HasKey( "image" ) )
359           {
360             Property::Map imageMap = value.GetValue( "image" ).Get< Property::Map >();
361             Image image = Scripting::NewImage( imageMap );
362
363             if ( image )
364             {
365               controlImpl.SetBackground( image );
366             }
367           }
368           else if ( value.Get< Property::Map >().empty() )
369           {
370             // An empty map means the background is no longer required
371             controlImpl.ClearBackground();
372           }
373           break;
374         }
375
376         case Toolkit::Control::PROPERTY_WIDTH_POLICY:
377         {
378           controlImpl.mImpl->mWidthPolicy = Scripting::GetEnumeration< Toolkit::Control::SizePolicy >( value.Get< std::string >(), SIZE_POLICY_STRING_TABLE, SIZE_POLICY_STRING_TABLE_COUNT );
379           break;
380         }
381
382         case Toolkit::Control::PROPERTY_HEIGHT_POLICY:
383         {
384           controlImpl.mImpl->mHeightPolicy = Scripting::GetEnumeration< Toolkit::Control::SizePolicy >( value.Get< std::string >(), SIZE_POLICY_STRING_TABLE, SIZE_POLICY_STRING_TABLE_COUNT );
385           break;
386         }
387
388         case Toolkit::Control::PROPERTY_MINIMUM_SIZE:
389         {
390           controlImpl.SetMinimumSize( value.Get< Vector3 >() );
391           break;
392         }
393
394         case Toolkit::Control::PROPERTY_MAXIMUM_SIZE:
395         {
396           controlImpl.SetMaximumSize( value.Get< Vector3 >() );
397           break;
398         }
399
400         case Toolkit::Control::PROPERTY_KEY_INPUT_FOCUS:
401         {
402           if ( value.Get< bool >() )
403           {
404             controlImpl.SetKeyInputFocus();
405           }
406           else
407           {
408             controlImpl.ClearKeyInputFocus();
409           }
410           break;
411         }
412       }
413     }
414   }
415
416   /**
417    * Called to retrieve a property of an object of this type.
418    * @param[in] object The object whose property is to be retrieved.
419    * @param[in] index The property index.
420    * @return The current value of the property.
421    */
422   static Property::Value GetProperty( BaseObject* object, Property::Index index )
423   {
424     Property::Value value;
425
426     Toolkit::Control control = Toolkit::Control::DownCast( BaseHandle( object ) );
427
428     if ( control )
429     {
430       Control& controlImpl( control.GetImplementation() );
431
432       switch ( index )
433       {
434         case Toolkit::Control::PROPERTY_BACKGROUND_COLOR:
435         {
436           value = controlImpl.GetBackgroundColor();
437           break;
438         }
439
440         case Toolkit::Control::PROPERTY_BACKGROUND:
441         {
442           Property::Map map;
443
444           Actor actor = controlImpl.GetBackgroundActor();
445           if ( actor )
446           {
447             ImageActor imageActor = ImageActor::DownCast( actor );
448             if ( imageActor )
449             {
450               Image image = imageActor.GetImage();
451               Property::Map imageMap;
452               Scripting::CreatePropertyMap( image, imageMap );
453               map.push_back( Property::StringValuePair( "image", imageMap ) );
454             }
455           }
456
457           value = map;
458           break;
459         }
460
461         case Toolkit::Control::PROPERTY_WIDTH_POLICY:
462         {
463           value = std::string( Scripting::GetEnumerationName< Toolkit::Control::SizePolicy >( controlImpl.mImpl->mWidthPolicy, SIZE_POLICY_STRING_TABLE, SIZE_POLICY_STRING_TABLE_COUNT ) );
464           break;
465         }
466
467         case Toolkit::Control::PROPERTY_HEIGHT_POLICY:
468         {
469           value = std::string( Scripting::GetEnumerationName< Toolkit::Control::SizePolicy >( controlImpl.mImpl->mHeightPolicy, SIZE_POLICY_STRING_TABLE, SIZE_POLICY_STRING_TABLE_COUNT ) );
470           break;
471         }
472
473         case Toolkit::Control::PROPERTY_MINIMUM_SIZE:
474         {
475           value = controlImpl.mImpl->mMinimumSize;
476           break;
477         }
478
479         case Toolkit::Control::PROPERTY_MAXIMUM_SIZE:
480         {
481           value = controlImpl.mImpl->mMaximumSize;
482           break;
483         }
484
485         case Toolkit::Control::PROPERTY_KEY_INPUT_FOCUS:
486         {
487           value = controlImpl.HasKeyInputFocus();
488           break;
489         }
490       }
491     }
492
493     return value;
494   }
495
496   // Data
497
498   Control& mControlImpl;
499
500   bool mInitialized:1;
501
502   ConnectionTracker mConnectionTracker; // signal connection tracker
503
504   // Gesture Detection
505
506   PinchGestureDetector     mPinchGestureDetector;
507   PanGestureDetector       mPanGestureDetector;
508   TapGestureDetector       mTapGestureDetector;
509   LongPressGestureDetector mLongPressGestureDetector;
510
511   Vector3 mStartingPinchScale;       ///< The scale when a pinch gesture starts
512
513   // Relayout and size negotiation
514
515   bool mLockSetSize;                 ///< Used to avoid. Can't be a bitfield as a reference to this member is used in SetSizeLock helper class.
516
517   Toolkit::Control::SizePolicy mWidthPolicy;  ///< Stores the width policy.
518   Toolkit::Control::SizePolicy mHeightPolicy; ///< Stores the height policy.
519
520   Vector3 mSize;                     ///< Stores the current control's size.
521   Vector3 mSetSize;                  ///< Always stores the size set through the Actor's API. Useful when reset to the initial size is needed.
522   Vector3 mMinimumSize;              ///< Stores the control's minimum size.
523   Vector3 mMaximumSize;              ///< Stores the control's maximum size.
524
525   bool mIsKeyboardNavigationSupported;  ///< Stores whether keyboard navigation is supported by the control.
526   bool mIsKeyboardFocusGroup;        ///< Stores whether the control is a focus group.
527
528   Toolkit::Control::KeyEventSignalV2 mKeyEventSignalV2;
529
530   // Background
531   Background* mBackground;           ///< Only create the background if we use it
532
533   ControlBehaviour mFlags;           ///< Flags passed in from constructor
534
535   // Properties - these need to be members of Internal::Control::Impl as they need to functions within this class.
536   static PropertyRegistration PROPERTY_1;
537   static PropertyRegistration PROPERTY_2;
538   static PropertyRegistration PROPERTY_3;
539   static PropertyRegistration PROPERTY_4;
540   static PropertyRegistration PROPERTY_5;
541   static PropertyRegistration PROPERTY_6;
542   static PropertyRegistration PROPERTY_7;
543 };
544
545 PropertyRegistration Control::Impl::PROPERTY_1( CONTROL_TYPE, "background-color", Toolkit::Control::PROPERTY_BACKGROUND_COLOR, Property::VECTOR4, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
546 PropertyRegistration Control::Impl::PROPERTY_2( CONTROL_TYPE, "background",       Toolkit::Control::PROPERTY_BACKGROUND,       Property::MAP,     &Control::Impl::SetProperty, &Control::Impl::GetProperty );
547 PropertyRegistration Control::Impl::PROPERTY_3( CONTROL_TYPE, "width-policy",     Toolkit::Control::PROPERTY_WIDTH_POLICY,     Property::STRING,  &Control::Impl::SetProperty, &Control::Impl::GetProperty );
548 PropertyRegistration Control::Impl::PROPERTY_4( CONTROL_TYPE, "height-policy",    Toolkit::Control::PROPERTY_HEIGHT_POLICY,    Property::STRING,  &Control::Impl::SetProperty, &Control::Impl::GetProperty );
549 PropertyRegistration Control::Impl::PROPERTY_5( CONTROL_TYPE, "minimum-size",     Toolkit::Control::PROPERTY_MINIMUM_SIZE,     Property::VECTOR3, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
550 PropertyRegistration Control::Impl::PROPERTY_6( CONTROL_TYPE, "maximum-size",     Toolkit::Control::PROPERTY_MAXIMUM_SIZE,     Property::VECTOR3, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
551 PropertyRegistration Control::Impl::PROPERTY_7( CONTROL_TYPE, "key-input-focus",  Toolkit::Control::PROPERTY_KEY_INPUT_FOCUS,  Property::BOOLEAN, &Control::Impl::SetProperty, &Control::Impl::GetProperty );
552
553 Toolkit::Control Control::New()
554 {
555   // Create the implementation, temporarily owned on stack
556   IntrusivePtr<Control> controlImpl = new Control( CONTROL_BEHAVIOUR_NONE );
557
558   // Pass ownership to handle
559   Toolkit::Control handle( *controlImpl );
560
561   // Second-phase init of the implementation
562   // This can only be done after the CustomActor connection has been made...
563   controlImpl->Initialize();
564
565   return handle;
566 }
567
568 Control::~Control()
569 {
570   delete mImpl;
571 }
572
573 void Control::Initialize()
574 {
575
576   // Calling deriving classes
577   OnInitialize();
578
579   if( mImpl->mFlags & REQUIRES_STYLE_CHANGE_SIGNALS )
580   {
581     Toolkit::StyleManager styleManager = Toolkit::StyleManager::Get();
582
583     // Register for style changes
584     styleManager.StyleChangeSignal().Connect( this, &ControlImpl::DoStyleChange );
585   }
586
587   mImpl->mInitialized = true;
588 }
589
590 void Control::EnableGestureDetection(Gesture::Type type)
591 {
592   if ( (type & Gesture::Pinch) && !mImpl->mPinchGestureDetector )
593   {
594     mImpl->mPinchGestureDetector = PinchGestureDetector::New();
595     mImpl->mPinchGestureDetector.DetectedSignal().Connect(mImpl, &Impl::PinchDetected);
596     mImpl->mPinchGestureDetector.Attach(Self());
597   }
598
599   if ( (type & Gesture::Pan) && !mImpl->mPanGestureDetector )
600   {
601     mImpl->mPanGestureDetector = PanGestureDetector::New();
602     mImpl->mPanGestureDetector.DetectedSignal().Connect(mImpl, &Impl::PanDetected);
603     mImpl->mPanGestureDetector.Attach(Self());
604   }
605
606   if ( (type & Gesture::Tap) && !mImpl->mTapGestureDetector )
607   {
608     mImpl->mTapGestureDetector = TapGestureDetector::New();
609     mImpl->mTapGestureDetector.DetectedSignal().Connect(mImpl, &Impl::TapDetected);
610     mImpl->mTapGestureDetector.Attach(Self());
611   }
612
613   if ( (type & Gesture::LongPress) && !mImpl->mLongPressGestureDetector )
614   {
615     mImpl->mLongPressGestureDetector = LongPressGestureDetector::New();
616     mImpl->mLongPressGestureDetector.DetectedSignal().Connect(mImpl, &Impl::LongPressDetected);
617     mImpl->mLongPressGestureDetector.Attach(Self());
618   }
619 }
620
621 void Control::DisableGestureDetection(Gesture::Type type)
622 {
623   if ( (type & Gesture::Pinch) && mImpl->mPinchGestureDetector )
624   {
625     mImpl->mPinchGestureDetector.Detach(Self());
626     mImpl->mPinchGestureDetector.Reset();
627   }
628
629   if ( (type & Gesture::Pan) && mImpl->mPanGestureDetector )
630   {
631     mImpl->mPanGestureDetector.Detach(Self());
632     mImpl->mPanGestureDetector.Reset();
633   }
634
635   if ( (type & Gesture::Tap) && mImpl->mTapGestureDetector )
636   {
637     mImpl->mTapGestureDetector.Detach(Self());
638     mImpl->mTapGestureDetector.Reset();
639   }
640
641   if ( (type & Gesture::LongPress) && mImpl->mLongPressGestureDetector)
642   {
643     mImpl->mLongPressGestureDetector.Detach(Self());
644     mImpl->mLongPressGestureDetector.Reset();
645   }
646 }
647
648 PinchGestureDetector Control::GetPinchGestureDetector() const
649 {
650   return mImpl->mPinchGestureDetector;
651 }
652
653 PanGestureDetector Control::GetPanGestureDetector() const
654 {
655   return mImpl->mPanGestureDetector;
656 }
657
658 TapGestureDetector Control::GetTapGestureDetector() const
659 {
660   return mImpl->mTapGestureDetector;
661 }
662
663 LongPressGestureDetector Control::GetLongPressGestureDetector() const
664 {
665   return mImpl->mLongPressGestureDetector;
666 }
667
668 void Control::SetBackgroundColor( const Vector4& color )
669 {
670   Background& background( mImpl->GetBackground() );
671
672   if ( background.actor )
673   {
674     // Just set the actor color
675     background.actor.SetColor( color );
676   }
677   else
678   {
679     // Create Mesh Actor
680     MeshActor meshActor = MeshActor::New( CreateMesh() );
681
682     meshActor.SetAffectedByLighting( false );
683     SetupBackgroundActor( meshActor, Actor::SCALE, color );
684
685     // Set the background actor before adding so that we do not inform deriving classes
686     background.actor = meshActor;
687     Self().Add( meshActor );
688   }
689
690   background.color = color;
691 }
692
693 Vector4 Control::GetBackgroundColor() const
694 {
695   if ( mImpl->mBackground )
696   {
697     return mImpl->mBackground->color;
698   }
699   return Color::TRANSPARENT;
700 }
701
702 void Control::SetBackground( Image image )
703 {
704   Background& background( mImpl->GetBackground() );
705
706   if ( background.actor )
707   {
708     // Remove Current actor, unset AFTER removal so that we do not inform deriving classes
709     Self().Remove( background.actor );
710     background.actor = NULL;
711   }
712
713   ImageActor imageActor = ImageActor::New( image );
714   SetupBackgroundActor( imageActor, Actor::SIZE, background.color );
715
716   // Set the background actor before adding so that we do not inform derived classes
717   background.actor = imageActor;
718   Self().Add( imageActor );
719 }
720
721 void Control::ClearBackground()
722 {
723   if ( mImpl->mBackground )
724   {
725     Background& background( mImpl->GetBackground() );
726     Self().Remove( background.actor );
727
728     delete mImpl->mBackground;
729     mImpl->mBackground = NULL;
730   }
731 }
732
733 Actor Control::GetBackgroundActor() const
734 {
735   if ( mImpl->mBackground )
736   {
737     return mImpl->mBackground->actor;
738   }
739
740   return Actor();
741 }
742
743 void Control::OnThemeChange( Toolkit::StyleManager styleManager )
744 {
745   GetImpl( styleManager ).ApplyThemeStyle( GetOwner() );
746 }
747
748 void Control::OnPinch(PinchGesture pinch)
749 {
750   if (pinch.state == Gesture::Started)
751   {
752     mImpl->mStartingPinchScale = Self().GetCurrentScale();
753   }
754
755   Self().SetScale(mImpl->mStartingPinchScale * pinch.scale);
756 }
757
758 void Control::OnStageConnection()
759 {
760   RelayoutRequest();
761
762   // Notify derived classes.
763   OnControlStageConnection();
764 }
765
766 void Control::OnStageDisconnection()
767 {
768   // Notify derived classes
769   OnControlStageDisconnection();
770 }
771
772 void Control::OnChildAdd(Actor& child)
773 {
774   // If this is the background actor, then we do not want to relayout or inform deriving classes
775   if ( mImpl->mBackground && ( child == mImpl->mBackground->actor ) )
776   {
777     return;
778   }
779
780   // Request for relayout.
781   RelayoutRequest();
782
783   // Notify derived classes.
784   OnControlChildAdd( child );
785 }
786
787 void Control::OnChildRemove(Actor& child)
788 {
789   // If this is the background actor, then we do not want to relayout or inform deriving classes
790   if ( mImpl->mBackground && ( child == mImpl->mBackground->actor ) )
791   {
792     return;
793   }
794
795   // Request for relayout.
796   RelayoutRequest();
797
798   // Notify derived classes.
799   OnControlChildRemove( child );
800 }
801
802 void Control::OnSizeSet(const Vector3& targetSize)
803 {
804   if( ( !mImpl->mLockSetSize ) && ( targetSize != mImpl->mSetSize ) )
805   {
806     // Only updates size if set through Actor's API
807     mImpl->mSetSize = targetSize;
808   }
809
810   if( targetSize != mImpl->mSize )
811   {
812     // Update control size.
813     mImpl->mSize = targetSize;
814
815     // Notify derived classes.
816     OnControlSizeSet( targetSize );
817   }
818 }
819
820 void Control::OnSizeAnimation(Animation& animation, const Vector3& targetSize)
821 {
822   // Do Nothing
823 }
824
825 bool Control::OnTouchEvent(const TouchEvent& event)
826 {
827   return false; // Do not consume
828 }
829
830 bool Control::OnKeyEvent(const KeyEvent& event)
831 {
832   return false; // Do not consume
833 }
834
835 bool Control::OnMouseWheelEvent(const MouseWheelEvent& event)
836 {
837   return false; // Do not consume
838 }
839
840 void Control::OnKeyInputFocusGained()
841 {
842   // Do Nothing
843 }
844
845 void Control::OnKeyInputFocusLost()
846 {
847   // Do Nothing
848 }
849
850 Actor Control::GetChildByAlias(const std::string& actorAlias)
851 {
852   return Actor();
853 }
854
855 bool Control::OnAccessibilityPan(PanGesture gesture)
856 {
857   return false; // Accessibility pan gesture is not handled by default
858 }
859
860 bool Control::OnAccessibilityTouch(const TouchEvent& touchEvent)
861 {
862   return false; // Accessibility touch event is not handled by default
863 }
864
865 bool Control::OnAccessibilityValueChange(bool isIncrease)
866 {
867   return false; // Accessibility value change action is not handled by default
868 }
869
870
871 void Control::SetKeyboardNavigationSupport(bool isSupported)
872 {
873   mImpl->mIsKeyboardNavigationSupported = isSupported;
874 }
875
876 bool Control::IsKeyboardNavigationSupported()
877 {
878   return mImpl->mIsKeyboardNavigationSupported;
879 }
880
881 void Control::SetAsKeyboardFocusGroup(bool isFocusGroup)
882 {
883   mImpl->mIsKeyboardFocusGroup = isFocusGroup;
884
885   // The following line will be removed when the deprecated API in KeyboardFocusManager is deleted
886   Toolkit::KeyboardFocusManager::Get().SetAsFocusGroup(Self(), isFocusGroup);
887 }
888
889 bool Control::IsKeyboardFocusGroup()
890 {
891   return Toolkit::KeyboardFocusManager::Get().IsFocusGroup(Self());
892 }
893
894 Actor Control::GetNextKeyboardFocusableActor(Actor currentFocusedActor, Toolkit::Control::KeyboardFocusNavigationDirection direction, bool loopEnabled)
895 {
896   return Actor();
897 }
898
899 bool Control::DoAction(BaseObject* object, const std::string& actionName, const std::vector<Property::Value>& attributes)
900 {
901   bool ret = false;
902
903   return ret;
904 }
905
906 void Control::DoActivatedAction(const PropertyValueContainer& attributes)
907 {
908   OnActivated();
909 }
910
911 void Control::DoStyleChange( Toolkit::StyleManager styleManager, StyleChange change )
912 {
913   if( change.themeChange )
914   {
915     OnThemeChange( styleManager );
916   }
917   else if( change.defaultFontChange || change.defaultFontSizeChange )
918   {
919     // This OnStyleChange(StyleChange change ) is deprecated, use OnFontChange instead
920     OnStyleChange( change );
921
922     OnFontChange( change.defaultFontChange, change.defaultFontSizeChange );
923   }
924 }
925
926 Toolkit::Control::KeyEventSignalV2& Control::KeyEventSignal()
927 {
928   return mImpl->mKeyEventSignalV2;
929 }
930
931 void Control::SetSizePolicy( Toolkit::Control::SizePolicy widthPolicy, Toolkit::Control::SizePolicy heightPolicy )
932 {
933   bool relayoutRequest( false );
934
935   if ( ( mImpl->mWidthPolicy != widthPolicy ) || ( mImpl->mHeightPolicy != heightPolicy ) )
936   {
937     relayoutRequest = true;
938   }
939
940   mImpl->mWidthPolicy = widthPolicy;
941   mImpl->mHeightPolicy = heightPolicy;
942
943   // Ensure RelayoutRequest is called AFTER new policies have been set.
944   if ( relayoutRequest )
945   {
946     RelayoutRequest();
947   }
948 }
949
950 void Control::GetSizePolicy( Toolkit::Control::SizePolicy& widthPolicy, Toolkit::Control::SizePolicy& heightPolicy ) const
951 {
952   widthPolicy = mImpl->mWidthPolicy;
953   heightPolicy = mImpl->mHeightPolicy;
954 }
955
956 void Control::SetMinimumSize( const Vector3& size )
957 {
958   if ( mImpl->mMinimumSize != size )
959   {
960     mImpl->mMinimumSize = size;
961
962     // Only relayout if our control is using the minimum or range policy.
963     if ( ( mImpl->mHeightPolicy == Toolkit::Control::Minimum ) || ( mImpl->mWidthPolicy  == Toolkit::Control::Minimum ) ||
964          ( mImpl->mHeightPolicy == Toolkit::Control::Range   ) || ( mImpl->mWidthPolicy  == Toolkit::Control::Range   ) )
965     {
966       RelayoutRequest();
967     }
968   }
969 }
970
971 const Vector3& Control::GetMinimumSize() const
972 {
973   return mImpl->mMinimumSize;
974 }
975
976 void Control::SetMaximumSize( const Vector3& size )
977 {
978   if ( mImpl->mMaximumSize != size )
979   {
980     mImpl->mMaximumSize = size;
981
982     // Only relayout if our control is using the maximum or range policy.
983     if ( ( mImpl->mHeightPolicy == Toolkit::Control::Maximum ) || ( mImpl->mWidthPolicy  == Toolkit::Control::Maximum ) ||
984          ( mImpl->mHeightPolicy == Toolkit::Control::Range   ) || ( mImpl->mWidthPolicy  == Toolkit::Control::Range   ) )
985     {
986       RelayoutRequest();
987     }
988   }
989 }
990
991 const Vector3& Control::GetMaximumSize() const
992 {
993   return mImpl->mMaximumSize;
994 }
995
996 Vector3 Control::GetNaturalSize()
997 {
998   // could be overridden in derived classes.
999   return mImpl->mSetSize;
1000 }
1001
1002 float Control::GetHeightForWidth( float width )
1003 {
1004   // could be overridden in derived classes.
1005   float height( 0.0f );
1006   if ( mImpl->mSetSize.width > 0.0f )
1007   {
1008     height = mImpl->mSetSize.height * width / mImpl->mSetSize.width;
1009   }
1010   return height;
1011 }
1012
1013 float Control::GetWidthForHeight( float height )
1014 {
1015   // could be overridden in derived classes.
1016   float width( 0.0f );
1017   if ( mImpl->mSetSize.height > 0.0f )
1018   {
1019     width = mImpl->mSetSize.width * height / mImpl->mSetSize.height;
1020   }
1021   return width;
1022 }
1023
1024 const Vector3& Control::GetControlSize() const
1025 {
1026   return mImpl->mSize;
1027 }
1028
1029 const Vector3& Control::GetSizeSet() const
1030 {
1031   return mImpl->mSetSize;
1032 }
1033
1034 void Control::SetKeyInputFocus()
1035 {
1036   if( Self().OnStage() )
1037   {
1038     Toolkit::KeyInputFocusManager::Get().SetFocus(Toolkit::Control::DownCast(Self()));
1039   }
1040 }
1041
1042 bool Control::HasKeyInputFocus()
1043 {
1044   bool result = false;
1045   if( Self().OnStage() )
1046   {
1047     result = Toolkit::KeyInputFocusManager::Get().IsKeyboardListener(Toolkit::Control::DownCast(Self()));
1048   }
1049   return result;
1050 }
1051
1052 void Control::ClearKeyInputFocus()
1053 {
1054   if( Self().OnStage() )
1055   {
1056     Toolkit::KeyInputFocusManager::Get().RemoveFocus(Toolkit::Control::DownCast(Self()));
1057   }
1058 }
1059
1060 void Control::RelayoutRequest()
1061 {
1062   Internal::RelayoutController::Get().Request();
1063 }
1064
1065 void Control::Relayout( Vector2 size, ActorSizeContainer& container )
1066 {
1067   // Avoids relayout again when OnSizeSet callback arrives.
1068   {
1069     SetSizeLock lock( mImpl->mLockSetSize );
1070     Self().SetSize( size );
1071   }
1072
1073   // Only relayout controls which requested to be relaid out.
1074   OnRelaidOut( size, container );
1075 }
1076
1077 void Control::Relayout( Actor actor, Vector2 size, ActorSizeContainer& container )
1078 {
1079   if ( actor )
1080   {
1081     Toolkit::Control control( Toolkit::Control::DownCast( actor ) );
1082     if( control )
1083     {
1084       control.GetImplementation().NegotiateSize( size, container );
1085     }
1086     else
1087     {
1088       container.push_back( ActorSizePair( actor, size ) );
1089     }
1090   }
1091 }
1092
1093 void Control::OnRelaidOut( Vector2 size, ActorSizeContainer& container )
1094 {
1095   unsigned int numChildren = Self().GetChildCount();
1096
1097   for( unsigned int i=0; i<numChildren; ++i )
1098   {
1099     container.push_back( ActorSizePair( Self().GetChildAt(i), size ) );
1100   }
1101 }
1102
1103 void Control::NegotiateSize( Vector2 allocatedSize, ActorSizeContainer& container )
1104 {
1105   Vector2 size;
1106
1107   if ( mImpl->mWidthPolicy == Toolkit::Control::Fixed )
1108   {
1109     if ( mImpl->mHeightPolicy == Toolkit::Control::Fixed )
1110     {
1111       // If a control says it has a fixed size, then use the size set by the application / control.
1112       Vector2 setSize( mImpl->mSetSize );
1113       if ( setSize != Vector2::ZERO )
1114       {
1115         size = setSize;
1116
1117         // Policy is set to Fixed, so if the application / control has not set one of the dimensions,
1118         // then we should use the natural size of the control rather than the full allocation.
1119         if ( EqualsZero( size.width ) )
1120         {
1121           size.width = GetWidthForHeight( size.height );
1122         }
1123         else if ( EqualsZero( size.height ) )
1124         {
1125           size.height = GetHeightForWidth( size.width );
1126         }
1127       }
1128       else
1129       {
1130         // If that is not set then set the size to the control's natural size
1131         size = Vector2( GetNaturalSize() );
1132       }
1133     }
1134     else
1135     {
1136       // Width is fixed so if the application / control has set it, then use that.
1137       if ( !EqualsZero( mImpl->mSetSize.width ) )
1138       {
1139         size.width = mImpl->mSetSize.width;
1140       }
1141       else
1142       {
1143         // Otherwise, set the width to what has been allocated.
1144         size.width = allocatedSize.width;
1145       }
1146
1147       // Height is flexible so ask control what the height should be for our width.
1148       size.height = GetHeightForWidth( size.width );
1149
1150       // Ensure height is within our policy rules
1151       size.height = Calculate( mImpl->mHeightPolicy, mImpl->mMinimumSize.height, mImpl->mMaximumSize.height, size.height );
1152     }
1153   }
1154   else
1155   {
1156     if ( mImpl->mHeightPolicy == Toolkit::Control::Fixed )
1157     {
1158       // Height is fixed so if the application / control has set it, then use that.
1159       if ( !EqualsZero( mImpl->mSetSize.height ) )
1160       {
1161         size.height = mImpl->mSetSize.height;
1162       }
1163       else
1164       {
1165         // Otherwise, set the height to what has been allocated.
1166         size.height = allocatedSize.height;
1167       }
1168
1169       // Width is flexible so ask control what the width should be for our height.
1170       size.width = GetWidthForHeight( size.height );
1171
1172       // Ensure width is within our policy rules
1173       size.width = Calculate( mImpl->mWidthPolicy, mImpl->mMinimumSize.width, mImpl->mMaximumSize.width, size.width );
1174     }
1175     else
1176     {
1177       // Width and height are BOTH flexible.
1178       // Calculate the width and height using the policy rules.
1179       size.width = Calculate( mImpl->mWidthPolicy, mImpl->mMinimumSize.width, mImpl->mMaximumSize.width, allocatedSize.width );
1180       size.height = Calculate( mImpl->mHeightPolicy, mImpl->mMinimumSize.height, mImpl->mMaximumSize.height, allocatedSize.height );
1181     }
1182   }
1183
1184   // If the width has not been set, then set to the allocated width.
1185   // Also if the width set is greater than the allocated, then set to allocated (no exceed support).
1186   if ( EqualsZero( size.width ) || ( size.width > allocatedSize.width ) )
1187   {
1188     size.width = allocatedSize.width;
1189   }
1190
1191   // If the height has not been set, then set to the allocated height.
1192   // Also if the height set is greater than the allocated, then set to allocated (no exceed support).
1193   if ( EqualsZero( size.height ) || ( size.height > allocatedSize.height ) )
1194   {
1195     size.height = allocatedSize.height;
1196   }
1197
1198   DALI_LOG_INFO( gLogFilter, Debug::Verbose,
1199                  "%p: Natural: [%.2f, %.2f] Allocated: [%.2f, %.2f] Set: [%.2f, %.2f]\n",
1200                  Self().GetObjectPtr(),
1201                  GetNaturalSize().x, GetNaturalSize().y,
1202                  allocatedSize.x, allocatedSize.y,
1203                  size.x, size.y );
1204
1205   Relayout( size, container );
1206 }
1207
1208 bool Control::EmitKeyEventSignal( const KeyEvent& event )
1209 {
1210   // Guard against destruction during signal emission
1211   Dali::Toolkit::Control handle( GetOwner() );
1212
1213   bool consumed = false;
1214
1215   // signals are allocated dynamically when someone connects
1216   if ( !mImpl->mKeyEventSignalV2.Empty() )
1217   {
1218     consumed = mImpl->mKeyEventSignalV2.Emit( handle, event );
1219   }
1220
1221   if (!consumed)
1222   {
1223     // Notification for derived classes
1224     consumed = OnKeyEvent(event);
1225   }
1226
1227   return consumed;
1228 }
1229
1230 void Control::SignalConnected( SlotObserver* slotObserver, CallbackBase* callback )
1231 {
1232   mImpl->SignalConnected( slotObserver, callback );
1233 }
1234
1235 void Control::SignalDisconnected( SlotObserver* slotObserver, CallbackBase* callback )
1236 {
1237   mImpl->SignalDisconnected( slotObserver, callback );
1238 }
1239
1240 std::size_t Control::GetConnectionCount() const
1241 {
1242   return mImpl->GetConnectionCount();
1243 }
1244
1245 Control::Control( bool requiresTouchEvents )
1246 : CustomActorImpl( requiresTouchEvents ),
1247   mImpl(new Impl(*this))
1248 {
1249 }
1250
1251 Control::Control( ControlBehaviour behaviourFlags )
1252 : CustomActorImpl( behaviourFlags & REQUIRES_TOUCH_EVENTS ),
1253   mImpl(new Impl(*this))
1254 {
1255   mImpl->mFlags = behaviourFlags;
1256 }
1257
1258 } // namespace Internal
1259
1260 } // namespace Toolkit
1261
1262 } // namespace Dali