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