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