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