Text Selection Popup Fade-in/Fade-out animation
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / text / decorator / text-decorator.cpp
1 /*
2  * Copyright (c) 2015 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/internal/text/decorator/text-decorator.h>
20
21 // EXTERNAL INCLUDES
22 #include <dali/integration-api/debug.h>
23
24 #include <dali/public-api/adaptor-framework/timer.h>
25 #include <dali/public-api/actors/layer.h>
26 #include <dali/public-api/common/stage.h>
27 #include <dali/public-api/events/touch-event.h>
28 #include <dali/public-api/events/pan-gesture.h>
29 #include <dali/public-api/images/resource-image.h>
30 #include <dali/public-api/object/property-notification.h>
31
32 #include <dali/devel-api/rendering/geometry.h>
33 #include <dali/devel-api/rendering/renderer.h>
34
35 // INTERNAL INCLUDES
36 #include <dali-toolkit/public-api/controls/control-depth-index-ranges.h>
37 #include <dali-toolkit/public-api/controls/default-controls/solid-color-actor.h>
38
39 #ifdef DEBUG_ENABLED
40 #define DECORATOR_DEBUG
41
42 #endif
43
44 #define MAKE_SHADER(A)#A
45
46 namespace
47 {
48 const char* VERTEX_SHADER = MAKE_SHADER(
49 attribute mediump vec2    aPosition;
50 uniform   mediump mat4    uMvpMatrix;
51 uniform   mediump vec3    uSize;
52
53 void main()
54 {
55   mediump vec4 position = vec4( aPosition, 0.0, 1.0 );
56   position.xyz *= uSize;
57   gl_Position = uMvpMatrix * position;
58 }
59 );
60
61 const char* FRAGMENT_SHADER = MAKE_SHADER(
62 uniform      lowp vec4 uColor;
63
64 void main()
65 {
66   gl_FragColor = uColor;
67 }
68 );
69 }
70
71 namespace Dali
72 {
73 namespace Internal
74 {
75 namespace
76 {
77 #ifdef DECORATOR_DEBUG
78 Integration::Log::Filter* gLogFilter( Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_TEXT_DECORATOR") );
79 #endif
80 }
81 }
82 }
83
84
85 // Local Data
86 namespace
87 {
88
89 const char* DEFAULT_GRAB_HANDLE_IMAGE_RELEASED( DALI_IMAGE_DIR "cursor_handler_center.png" );
90 const char* DEFAULT_SELECTION_HANDLE_ONE_RELEASED( DALI_IMAGE_DIR "selection_handle_left.png" );
91 const char* DEFAULT_SELECTION_HANDLE_TWO_RELEASED( DALI_IMAGE_DIR "selection_handle_right.png" );
92
93 const int DEFAULT_POPUP_OFFSET( -100.0f ); // Vertical offset of Popup from cursor or handles position.
94
95 const Dali::Vector3 DEFAULT_GRAB_HANDLE_RELATIVE_SIZE( 1.25f, 1.5f, 1.0f );
96 const Dali::Vector3 DEFAULT_SELECTION_HANDLE_RELATIVE_SIZE( 1.25f, 1.5f, 1.0f );
97
98 const Dali::Vector4 LIGHT_BLUE( 0.75f, 0.96f, 1.f, 1.f ); // The text highlight color. TODO: due some problems, maybe with the blending function in the text clipping, the color is fully opaque.
99
100 const Dali::Vector4 HANDLE_COLOR( 0.0f, (183.0f / 255.0f), (229.0f / 255.0f), 1.0f  );
101
102 const unsigned int CURSOR_BLINK_INTERVAL = 500u; // Cursor blink interval
103 const float TO_MILLISECONDS = 1000.f;
104 const float TO_SECONDS = 1.f / TO_MILLISECONDS;
105
106 const unsigned int SCROLL_TICK_INTERVAL = 50u;
107
108 const float SCROLL_THRESHOLD = 10.f;
109 const float SCROLL_SPEED = 300.f;
110 const float SCROLL_DISTANCE = SCROLL_SPEED * SCROLL_TICK_INTERVAL * TO_SECONDS;
111
112 /**
113  * structure to hold coordinates of each quad, which will make up the mesh.
114  */
115 struct QuadCoordinates
116 {
117   /**
118    * Default constructor
119    */
120   QuadCoordinates()
121   {
122   }
123
124   /**
125    * Constructor
126    * @param[in] x1 left co-ordinate
127    * @param[in] y1 top co-ordinate
128    * @param[in] x2 right co-ordinate
129    * @param[in] y2 bottom co-ordinate
130    */
131   QuadCoordinates(float x1, float y1, float x2, float y2)
132   : min(x1, y1),
133     max(x2, y2)
134   {
135   }
136
137   Dali::Vector2 min;                          ///< top-left (minimum) position of quad
138   Dali::Vector2 max;                          ///< bottom-right (maximum) position of quad
139 };
140
141 typedef std::vector<QuadCoordinates> QuadContainer;
142
143 /**
144  * @brief Takes a bounding rectangle in the local coordinates of an actor and returns the world coordinates Bounding Box.
145  * @param[in] boundingRectangle local bounding
146  * @param[out] Vector4 World coordinate bounding Box.
147  */
148 void LocalToWorldCoordinatesBoundingBox( const Dali::Rect<int>& boundingRectangle, Dali::Vector4& boundingBox )
149 {
150   // Convert to world coordinates and store as a Vector4 to be compatible with Property Notifications.
151   Dali::Vector2 stageSize = Dali::Stage::GetCurrent().GetSize();
152
153   const float originX = boundingRectangle.x - 0.5f * stageSize.width;
154   const float originY = boundingRectangle.y - 0.5f * stageSize.height;
155
156   boundingBox = Dali::Vector4( originX,
157                                originY,
158                                originX + boundingRectangle.width,
159                                originY + boundingRectangle.height );
160 }
161
162
163 } // end of namespace
164
165 namespace Dali
166 {
167
168 namespace Toolkit
169 {
170
171 namespace Text
172 {
173
174 struct Decorator::Impl : public ConnectionTracker
175 {
176   enum ScrollDirection
177   {
178     SCROLL_NONE,
179     SCROLL_RIGHT,
180     SCROLL_LEFT,
181     SCROLL_TOP,
182     SCROLL_BOTTOM
183   };
184
185   struct CursorImpl
186   {
187     CursorImpl()
188     : color( Dali::Color::BLACK ),
189       position(),
190       cursorHeight( 0.0f ),
191       lineHeight( 0.0f )
192     {
193     }
194
195     Vector4 color;
196     Vector2 position;
197     float cursorHeight;
198     float lineHeight;
199   };
200
201   struct HandleImpl
202   {
203     HandleImpl()
204     : position(),
205       lineHeight( 0.0f ),
206       grabDisplacementX( 0.f ),
207       grabDisplacementY( 0.f ),
208       active( false ),
209       visible( false ),
210       pressed( false ),
211       flipped( false )
212     {
213     }
214
215     ImageActor actor;
216     Actor grabArea;
217
218     Vector2 position;
219     float lineHeight; ///< Not the handle height
220     float grabDisplacementX;
221     float grabDisplacementY;
222     bool active  : 1;
223     bool visible : 1;
224     bool pressed : 1;
225     bool flipped : 1;
226   };
227
228   struct PopupImpl
229   {
230     PopupImpl()
231     : position(),
232       offset( DEFAULT_POPUP_OFFSET )
233     {
234     }
235
236     TextSelectionPopup actor;
237     Vector3 position;
238     int offset;
239   };
240
241   Impl( ControllerInterface& controller,
242         TextSelectionPopupCallbackInterface& callbackInterface )
243   : mController( controller ),
244     mEnabledPopupButtons( TextSelectionPopup::NONE ),
245     mTextSelectionPopupCallbackInterface( callbackInterface ),
246     mHandleColor( HANDLE_COLOR ),
247     mBoundingBox( Rect<int>() ),
248     mHighlightColor( LIGHT_BLUE ),
249     mHighlightPosition( Vector2::ZERO ),
250     mActiveCursor( ACTIVE_CURSOR_NONE ),
251     mCursorBlinkInterval( CURSOR_BLINK_INTERVAL ),
252     mCursorBlinkDuration( 0.0f ),
253     mHandleScrolling( HANDLE_TYPE_COUNT ),
254     mScrollDirection( SCROLL_NONE ),
255     mScrollThreshold( SCROLL_THRESHOLD ),
256     mScrollSpeed( SCROLL_SPEED ),
257     mScrollDistance( SCROLL_DISTANCE ),
258     mTextDepth( 0u ),
259     mActiveCopyPastePopup( false ),
260     mCursorBlinkStatus( true ),
261     mPrimaryCursorVisible( false ),
262     mSecondaryCursorVisible( false ),
263     mSwapSelectionHandles( false ),
264     mNotifyEndOfScroll( false )
265   {
266     mQuadVertexFormat[ "aPosition" ] = Property::VECTOR2;
267     mQuadIndexFormat[ "indices" ] = Property::INTEGER;
268     mHighlightMaterial = Material::New( Shader::New( VERTEX_SHADER, FRAGMENT_SHADER ) );
269   }
270
271   /**
272    * Relayout of the decorations owned by the decorator.
273    * @param[in] size The Size of the UI control the decorator is adding it's decorations to.
274    */
275   void Relayout( const Vector2& size )
276   {
277     // TODO - Remove this if nothing is active
278     CreateActiveLayer();
279
280     // Show or hide the cursors
281     CreateCursors();
282
283     if( mPrimaryCursor )
284     {
285       const CursorImpl& cursor = mCursor[PRIMARY_CURSOR];
286       mPrimaryCursorVisible = ( cursor.position.x <= size.width ) && ( cursor.position.x >= 0.f );
287       if( mPrimaryCursorVisible )
288       {
289         Vector2 position = cursor.position;
290
291         mPrimaryCursor.SetPosition( position.x,
292                                     position.y );
293         mPrimaryCursor.SetSize( Size( 1.0f, cursor.cursorHeight ) );
294       }
295       mPrimaryCursor.SetVisible( mPrimaryCursorVisible );
296     }
297     if( mSecondaryCursor )
298     {
299       const CursorImpl& cursor = mCursor[SECONDARY_CURSOR];
300       mSecondaryCursorVisible = ( cursor.position.x <= size.width ) && ( cursor.position.x >= 0.f );
301       if( mSecondaryCursorVisible )
302       {
303         mSecondaryCursor.SetPosition( cursor.position.x,
304                                       cursor.position.y );
305         mSecondaryCursor.SetSize( Size( 1.0f, cursor.cursorHeight ) );
306       }
307       mSecondaryCursor.SetVisible( mSecondaryCursorVisible );
308     }
309
310     // Show or hide the grab handle
311     HandleImpl& grabHandle = mHandle[GRAB_HANDLE];
312     if( grabHandle.active )
313     {
314       Vector2 position = grabHandle.position;
315
316       const bool isVisible = ( position.x <= size.width ) && ( position.x >= 0.f );
317
318       if( isVisible )
319       {
320         SetupTouchEvents();
321
322         CreateGrabHandle();
323
324         grabHandle.actor.SetPosition( position.x,
325                                       grabHandle.lineHeight ); // TODO : Fix for multiline.
326       }
327       grabHandle.actor.SetVisible( isVisible );
328     }
329     else if( grabHandle.actor )
330     {
331       grabHandle.actor.Unparent();
332     }
333
334     // Show or hide the selection handles/highlight
335     HandleImpl& primary = mHandle[ LEFT_SELECTION_HANDLE ];
336     HandleImpl& secondary = mHandle[ RIGHT_SELECTION_HANDLE ];
337     if( primary.active || secondary.active )
338     {
339       Vector2 primaryPosition = primary.position;
340       Vector2 secondaryPosition = secondary.position;
341
342       const bool isPrimaryVisible = ( primaryPosition.x <= size.width ) && ( primaryPosition.x >= 0.f );
343       const bool isSecondaryVisible = ( secondaryPosition.x <= size.width ) && ( secondaryPosition.x >= 0.f );
344
345       if( isPrimaryVisible || isSecondaryVisible )
346       {
347         SetupTouchEvents();
348
349         CreateSelectionHandles();
350
351         if( isPrimaryVisible )
352         {
353           primary.actor.SetPosition( primaryPosition.x,
354                                      primary.lineHeight ); // TODO : Fix for multiline.
355         }
356
357         if( isSecondaryVisible )
358         {
359           secondary.actor.SetPosition( secondaryPosition.x,
360                                        secondary.lineHeight ); // TODO : Fix for multiline.
361         }
362       }
363       primary.actor.SetVisible( isPrimaryVisible );
364       secondary.actor.SetVisible( isSecondaryVisible );
365
366       CreateHighlight();
367       UpdateHighlight();
368     }
369     else
370     {
371       if( primary.actor )
372       {
373         primary.actor.Unparent();
374       }
375       if( secondary.actor )
376       {
377         secondary.actor.Unparent();
378       }
379       if( mHighlightActor )
380       {
381         mHighlightActor.Unparent();
382       }
383     }
384
385     if( mActiveCopyPastePopup )
386     {
387       ShowPopup();
388     }
389     else
390     {
391       if( mCopyPastePopup.actor )
392       {
393         mCopyPastePopup.actor.HidePopup();
394       }
395     }
396   }
397
398   void UpdatePositions( const Vector2& scrollOffset )
399   {
400     mCursor[PRIMARY_CURSOR].position += scrollOffset;
401     mCursor[SECONDARY_CURSOR].position += scrollOffset;
402     mHandle[ GRAB_HANDLE ].position += scrollOffset;
403     mHandle[ LEFT_SELECTION_HANDLE ].position += scrollOffset;
404     mHandle[ RIGHT_SELECTION_HANDLE ].position += scrollOffset;
405     mHighlightPosition += scrollOffset;
406     DeterminePositionPopup();
407   }
408
409   void ShowPopup()
410   {
411     if ( !mCopyPastePopup.actor )
412     {
413       return;
414     }
415
416     if( !mCopyPastePopup.actor.GetParent() )
417     {
418       mActiveLayer.Add( mCopyPastePopup.actor );
419     }
420
421     mCopyPastePopup.actor.RaiseAbove( mActiveLayer );
422     mCopyPastePopup.actor.ShowPopup();
423   }
424
425   void DeterminePositionPopup()
426   {
427     if ( !mActiveCopyPastePopup )
428     {
429       return;
430     }
431
432     if ( mHandle[LEFT_SELECTION_HANDLE].active || mHandle[RIGHT_SELECTION_HANDLE].active )
433     {
434       float minHandleXPosition = std::min (  mHandle[LEFT_SELECTION_HANDLE].position.x, mHandle[RIGHT_SELECTION_HANDLE].position.x );
435       float maxHandleXPosition = std::max (  mHandle[LEFT_SELECTION_HANDLE].position.x, mHandle[RIGHT_SELECTION_HANDLE].position.x );
436
437       float minHandleYPosition = std::min (  mHandle[LEFT_SELECTION_HANDLE].position.y, mHandle[RIGHT_SELECTION_HANDLE].position.y );
438
439       mCopyPastePopup.position.x = minHandleXPosition + ( ( maxHandleXPosition - minHandleXPosition ) *0.5f );
440       mCopyPastePopup.position.y = minHandleYPosition + mCopyPastePopup.offset;
441     }
442     else
443     {
444       mCopyPastePopup.position = Vector3( mCursor[PRIMARY_CURSOR].position.x, mCursor[PRIMARY_CURSOR].position.y -100.0f , 0.0f ); //todo 100 to be an offset Property
445     }
446
447     Vector3 popupSize = Vector3( mCopyPastePopup.actor.GetRelayoutSize( Dimension::WIDTH ), mCopyPastePopup.actor.GetRelayoutSize( Dimension::HEIGHT ), 0.0f );
448
449     GetConstrainedPopupPosition( mCopyPastePopup.position, popupSize, AnchorPoint::CENTER, mActiveLayer, mBoundingBox );
450
451     SetUpPopupPositionNotifications();
452
453     mCopyPastePopup.actor.SetPosition( mCopyPastePopup.position );
454   }
455
456   void PopupRelayoutComplete( Actor actor )
457   {
458     // Size negotiation for CopyPastePopup complete so can get the size and constrain position within bounding box.
459
460     DeterminePositionPopup();
461   }
462
463   void CreateCursor( ImageActor& cursor, const Vector4& color )
464   {
465     cursor = CreateSolidColorActor( color );
466     cursor.SetSortModifier( DECORATION_DEPTH_INDEX );
467     cursor.SetParentOrigin( ParentOrigin::TOP_LEFT ); // Need to set the default parent origin as CreateSolidColorActor() sets a different one.
468     cursor.SetAnchorPoint( AnchorPoint::TOP_CENTER );
469   }
470
471   // Add or Remove cursor(s) from parent
472   void CreateCursors()
473   {
474     if( mActiveCursor == ACTIVE_CURSOR_NONE )
475     {
476       if( mPrimaryCursor )
477       {
478         mPrimaryCursor.Unparent();
479       }
480       if( mSecondaryCursor )
481       {
482         mSecondaryCursor.Unparent();
483       }
484     }
485     else
486     {
487       // Create Primary and or Secondary Cursor(s) if active and add to parent
488       if ( mActiveCursor == ACTIVE_CURSOR_PRIMARY ||
489            mActiveCursor == ACTIVE_CURSOR_BOTH )
490       {
491         if ( !mPrimaryCursor )
492         {
493           CreateCursor( mPrimaryCursor, mCursor[PRIMARY_CURSOR].color );
494 #ifdef DECORATOR_DEBUG
495           mPrimaryCursor.SetName( "PrimaryCursorActor" );
496 #endif
497         }
498
499         if( !mPrimaryCursor.GetParent() )
500         {
501           mActiveLayer.Add( mPrimaryCursor );
502         }
503       }
504
505       if ( mActiveCursor == ACTIVE_CURSOR_BOTH )
506       {
507         if ( !mSecondaryCursor )
508         {
509           CreateCursor( mSecondaryCursor, mCursor[SECONDARY_CURSOR].color );
510 #ifdef DECORATOR_DEBUG
511           mSecondaryCursor.SetName( "SecondaryCursorActor" );
512 #endif
513         }
514
515         if( !mSecondaryCursor.GetParent() )
516         {
517           mActiveLayer.Add( mSecondaryCursor );
518         }
519       }
520       else
521       {
522         if( mSecondaryCursor )
523         {
524           mSecondaryCursor.Unparent();
525         }
526       }
527     }
528   }
529
530   bool OnCursorBlinkTimerTick()
531   {
532     // Cursor blinking
533     if ( mPrimaryCursor )
534     {
535       mPrimaryCursor.SetVisible( mPrimaryCursorVisible && mCursorBlinkStatus );
536     }
537     if ( mSecondaryCursor )
538     {
539       mSecondaryCursor.SetVisible( mSecondaryCursorVisible && mCursorBlinkStatus );
540     }
541
542     mCursorBlinkStatus = !mCursorBlinkStatus;
543
544     return true;
545   }
546
547   void SetupTouchEvents()
548   {
549     if ( !mTapDetector )
550     {
551       mTapDetector = TapGestureDetector::New();
552       mTapDetector.DetectedSignal().Connect( this, &Decorator::Impl::OnTap );
553     }
554
555     if ( !mPanGestureDetector )
556     {
557       mPanGestureDetector = PanGestureDetector::New();
558       mPanGestureDetector.DetectedSignal().Connect( this, &Decorator::Impl::OnPan );
559     }
560   }
561
562   void CreateActiveLayer()
563   {
564     if( !mActiveLayer )
565     {
566       mActiveLayer = Layer::New();
567 #ifdef DECORATOR_DEBUG
568       mActiveLayer.SetName ( "ActiveLayerActor" );
569 #endif
570
571       mActiveLayer.SetParentOrigin( ParentOrigin::CENTER );
572       mActiveLayer.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS );
573       mActiveLayer.SetPositionInheritanceMode( USE_PARENT_POSITION );
574
575       // Add the active layer telling the controller it doesn't need clipping.
576       mController.AddDecoration( mActiveLayer, false );
577     }
578
579     mActiveLayer.RaiseToTop();
580   }
581
582   void CreateGrabHandle()
583   {
584     HandleImpl& grabHandle = mHandle[GRAB_HANDLE];
585     if( !grabHandle.actor )
586     {
587       if( !mHandleImages[GRAB_HANDLE][HANDLE_IMAGE_RELEASED] )
588       {
589         mHandleImages[GRAB_HANDLE][HANDLE_IMAGE_RELEASED] = ResourceImage::New( DEFAULT_GRAB_HANDLE_IMAGE_RELEASED );
590       }
591
592       grabHandle.actor = ImageActor::New( mHandleImages[GRAB_HANDLE][HANDLE_IMAGE_RELEASED] );
593       grabHandle.actor.SetSortModifier( DECORATION_DEPTH_INDEX );
594       grabHandle.actor.SetAnchorPoint( AnchorPoint::TOP_CENTER );
595       // Area that Grab handle responds to, larger than actual handle so easier to move
596 #ifdef DECORATOR_DEBUG
597       grabHandle.actor.SetName( "GrabHandleActor" );
598       if ( Dali::Internal::gLogFilter->IsEnabledFor( Debug::Verbose ) )
599       {
600         grabHandle.grabArea = Toolkit::CreateSolidColorActor( Vector4(0.0f, 0.0f, 0.0f, 0.0f), true, Color::RED, 1 );
601         grabHandle.grabArea.SetName( "GrabArea" );
602       }
603       else
604       {
605         grabHandle.grabArea = Actor::New();
606         grabHandle.grabArea.SetName( "GrabArea" );
607       }
608 #else
609       grabHandle.grabArea = Actor::New();
610 #endif
611
612       grabHandle.grabArea.SetParentOrigin( ParentOrigin::TOP_CENTER );
613       grabHandle.grabArea.SetAnchorPoint( AnchorPoint::TOP_CENTER );
614       grabHandle.grabArea.SetResizePolicy( ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::ALL_DIMENSIONS );
615       grabHandle.grabArea.SetSizeModeFactor( DEFAULT_GRAB_HANDLE_RELATIVE_SIZE );
616       grabHandle.actor.Add( grabHandle.grabArea );
617       grabHandle.actor.SetColor( mHandleColor );
618
619       grabHandle.grabArea.TouchedSignal().Connect( this, &Decorator::Impl::OnGrabHandleTouched );
620       mTapDetector.Attach( grabHandle.grabArea );
621       mPanGestureDetector.Attach( grabHandle.grabArea );
622
623       mActiveLayer.Add( grabHandle.actor );
624     }
625
626     if( !grabHandle.actor.GetParent() )
627     {
628       mActiveLayer.Add( grabHandle.actor );
629     }
630   }
631
632   void CreateSelectionHandles()
633   {
634     HandleImpl& primary = mHandle[ LEFT_SELECTION_HANDLE ];
635     if( !primary.actor )
636     {
637       if( !mHandleImages[LEFT_SELECTION_HANDLE][HANDLE_IMAGE_RELEASED] )
638       {
639         mHandleImages[LEFT_SELECTION_HANDLE][HANDLE_IMAGE_RELEASED] = ResourceImage::New( DEFAULT_SELECTION_HANDLE_ONE_RELEASED );
640       }
641
642       primary.actor = ImageActor::New( mHandleImages[LEFT_SELECTION_HANDLE][HANDLE_IMAGE_RELEASED] );
643 #ifdef DECORATOR_DEBUG
644       primary.actor.SetName("SelectionHandleOne");
645 #endif
646       primary.actor.SetAnchorPoint( AnchorPoint::TOP_RIGHT ); // Change to BOTTOM_RIGHT if Look'n'Feel requires handle above text.
647       primary.actor.SetSortModifier( DECORATION_DEPTH_INDEX );
648       primary.flipped = false;
649       primary.actor.SetColor( mHandleColor );
650
651       primary.grabArea = Actor::New(); // Area that Grab handle responds to, larger than actual handle so easier to move
652 #ifdef DECORATOR_DEBUG
653       primary.grabArea.SetName("SelectionHandleOneGrabArea");
654 #endif
655       primary.grabArea.SetResizePolicy( ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::ALL_DIMENSIONS );
656       primary.grabArea.SetParentOrigin( ParentOrigin::TOP_CENTER );
657       primary.grabArea.SetAnchorPoint( AnchorPoint::TOP_CENTER );
658       primary.grabArea.SetSizeModeFactor( DEFAULT_SELECTION_HANDLE_RELATIVE_SIZE );
659
660       mTapDetector.Attach( primary.grabArea );
661       mPanGestureDetector.Attach( primary.grabArea );
662       primary.grabArea.TouchedSignal().Connect( this, &Decorator::Impl::OnHandleOneTouched );
663
664       primary.actor.Add( primary.grabArea );
665     }
666
667     if( !primary.actor.GetParent() )
668     {
669       mActiveLayer.Add( primary.actor );
670     }
671
672     HandleImpl& secondary = mHandle[ RIGHT_SELECTION_HANDLE ];
673     if( !secondary.actor )
674     {
675       if( !mHandleImages[RIGHT_SELECTION_HANDLE][HANDLE_IMAGE_RELEASED] )
676       {
677         mHandleImages[RIGHT_SELECTION_HANDLE][HANDLE_IMAGE_RELEASED] = ResourceImage::New( DEFAULT_SELECTION_HANDLE_TWO_RELEASED );
678       }
679
680       secondary.actor = ImageActor::New( mHandleImages[RIGHT_SELECTION_HANDLE][HANDLE_IMAGE_RELEASED] );
681 #ifdef DECORATOR_DEBUG
682       secondary.actor.SetName("SelectionHandleTwo");
683 #endif
684       secondary.actor.SetAnchorPoint( AnchorPoint::TOP_LEFT ); // Change to BOTTOM_LEFT if Look'n'Feel requires handle above text.
685       secondary.actor.SetSortModifier( DECORATION_DEPTH_INDEX );
686       secondary.flipped = false;
687       secondary.actor.SetColor( mHandleColor );
688
689       secondary.grabArea = Actor::New(); // Area that Grab handle responds to, larger than actual handle so easier to move
690 #ifdef DECORATOR_DEBUG
691       secondary.grabArea.SetName("SelectionHandleTwoGrabArea");
692 #endif
693       secondary.grabArea.SetResizePolicy( ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::ALL_DIMENSIONS );
694       secondary.grabArea.SetParentOrigin( ParentOrigin::TOP_CENTER );
695       secondary.grabArea.SetAnchorPoint( AnchorPoint::TOP_CENTER );
696       secondary.grabArea.SetSizeModeFactor( DEFAULT_SELECTION_HANDLE_RELATIVE_SIZE );
697
698       mTapDetector.Attach( secondary.grabArea );
699       mPanGestureDetector.Attach( secondary.grabArea );
700       secondary.grabArea.TouchedSignal().Connect( this, &Decorator::Impl::OnHandleTwoTouched );
701
702       secondary.actor.Add( secondary.grabArea );
703     }
704
705     if( !secondary.actor.GetParent() )
706     {
707       mActiveLayer.Add( secondary.actor );
708     }
709   }
710
711   void CreateHighlight()
712   {
713     if( !mHighlightActor )
714     {
715       mHighlightActor = Actor::New();
716
717 #ifdef DECORATOR_DEBUG
718       mHighlightActor.SetName( "HighlightActor" );
719 #endif
720       mHighlightActor.SetAnchorPoint( AnchorPoint::TOP_LEFT );
721       mHighlightActor.SetSize( 1.0f, 1.0f );
722       mHighlightActor.SetColor( mHighlightColor );
723       mHighlightActor.SetColorMode( USE_OWN_COLOR );
724     }
725
726     // Add the highlight box telling the controller it needs clipping.
727     mController.AddDecoration( mHighlightActor, true );
728   }
729
730   void UpdateHighlight()
731   {
732     if ( mHighlightActor )
733     {
734       if( !mHighlightQuadList.empty() )
735       {
736         Vector< Vector2 > vertices;
737         Vector< unsigned int> indices;
738         Vector2 vertex;
739
740         std::vector<QuadCoordinates>::iterator iter = mHighlightQuadList.begin();
741         std::vector<QuadCoordinates>::iterator endIter = mHighlightQuadList.end();
742
743         for( std::size_t v = 0; iter != endIter; ++iter,v+=4 )
744         {
745
746           QuadCoordinates& quad = *iter;
747
748           // top-left (v+0)
749           vertex.x = quad.min.x;
750           vertex.y = quad.min.y;
751           vertices.PushBack( vertex );
752
753           // top-right (v+1)
754           vertex.x = quad.max.x;
755           vertex.y = quad.min.y;
756           vertices.PushBack( vertex );
757
758           // bottom-left (v+2)
759           vertex.x = quad.min.x;
760           vertex.y = quad.max.y;
761           vertices.PushBack( vertex );
762
763           // bottom-right (v+3)
764           vertex.x = quad.max.x;
765           vertex.y = quad.max.y;
766           vertices.PushBack( vertex );
767
768           // triangle A (3, 1, 0)
769           indices.PushBack( v + 3 );
770           indices.PushBack( v + 1 );
771           indices.PushBack( v );
772
773           // triangle B (0, 2, 3)
774           indices.PushBack( v );
775           indices.PushBack( v + 2 );
776           indices.PushBack( v + 3 );
777         }
778
779         if( mQuadVertices )
780         {
781           mQuadVertices.SetSize( vertices.Size() );
782         }
783         else
784         {
785           mQuadVertices = PropertyBuffer::New( mQuadVertexFormat, vertices.Size() );
786         }
787
788         if( mQuadIndices )
789         {
790           mQuadIndices.SetSize( indices.Size() );
791         }
792         else
793         {
794           mQuadIndices = PropertyBuffer::New( mQuadIndexFormat, indices.Size() );
795         }
796
797         mQuadVertices.SetData( &vertices[ 0 ] );
798         mQuadIndices.SetData( &indices[ 0 ] );
799
800         if( !mQuadGeometry )
801         {
802           mQuadGeometry = Geometry::New();
803           mQuadGeometry.AddVertexBuffer( mQuadVertices );
804         }
805         mQuadGeometry.SetIndexBuffer( mQuadIndices );
806
807         if( !mHighlightRenderer )
808         {
809           mHighlightRenderer = Dali::Renderer::New( mQuadGeometry, mHighlightMaterial );
810           mHighlightActor.AddRenderer( mHighlightRenderer );
811         }
812       }
813
814       mHighlightActor.SetPosition( mHighlightPosition.x,
815                                    mHighlightPosition.y );
816
817       mHighlightQuadList.clear();
818
819       mHighlightRenderer.SetDepthIndex( mTextDepth - 2u ); // text is rendered at mTextDepth and text's shadow at mTextDepth -1u.
820     }
821   }
822
823   void OnTap( Actor actor, const TapGesture& tap )
824   {
825     if( actor == mHandle[GRAB_HANDLE].actor )
826     {
827       // TODO
828     }
829   }
830
831   void DoPan( HandleImpl& handle, HandleType type, const PanGesture& gesture )
832   {
833     if( Gesture::Started == gesture.state )
834     {
835       handle.grabDisplacementX = handle.grabDisplacementY = 0;
836     }
837
838     handle.grabDisplacementX += gesture.displacement.x;
839     handle.grabDisplacementY += gesture.displacement.y;
840
841     const float x = handle.position.x + handle.grabDisplacementX;
842     const float y = handle.position.y + handle.lineHeight*0.5f + handle.grabDisplacementY;
843
844     if( Gesture::Started    == gesture.state ||
845         Gesture::Continuing == gesture.state )
846     {
847       Vector2 targetSize;
848       mController.GetTargetSize( targetSize );
849
850       if( x < mScrollThreshold )
851       {
852         mScrollDirection = SCROLL_RIGHT;
853         mHandleScrolling = type;
854         StartScrollTimer();
855       }
856       else if( x > targetSize.width - mScrollThreshold )
857       {
858         mScrollDirection = SCROLL_LEFT;
859         mHandleScrolling = type;
860         StartScrollTimer();
861       }
862       else
863       {
864         mHandleScrolling = HANDLE_TYPE_COUNT;
865         StopScrollTimer();
866         mController.DecorationEvent( type, HANDLE_PRESSED, x, y );
867       }
868     }
869     else if( Gesture::Finished  == gesture.state ||
870              Gesture::Cancelled == gesture.state )
871     {
872       if( mScrollTimer &&
873           ( mScrollTimer.IsRunning() || mNotifyEndOfScroll ) )
874       {
875         mNotifyEndOfScroll = false;
876         mHandleScrolling = HANDLE_TYPE_COUNT;
877         StopScrollTimer();
878         mController.DecorationEvent( type, HANDLE_STOP_SCROLLING, x, y );
879       }
880       else
881       {
882         mController.DecorationEvent( type, HANDLE_RELEASED, x, y );
883       }
884
885       if( GRAB_HANDLE == type )
886       {
887         handle.actor.SetImage( mHandleImages[type][HANDLE_IMAGE_RELEASED] );
888       }
889       else
890       {
891         HandleType selectionHandleType = type;
892
893         if( mSwapSelectionHandles != handle.flipped )
894         {
895           selectionHandleType = ( LEFT_SELECTION_HANDLE == type ) ? RIGHT_SELECTION_HANDLE : LEFT_SELECTION_HANDLE;
896         }
897
898         handle.actor.SetImage( mHandleImages[selectionHandleType][HANDLE_IMAGE_RELEASED] );
899       }
900       handle.pressed = false;
901     }
902   }
903
904   void OnPan( Actor actor, const PanGesture& gesture )
905   {
906     HandleImpl& grabHandle = mHandle[GRAB_HANDLE];
907     HandleImpl& primarySelectionHandle = mHandle[LEFT_SELECTION_HANDLE];
908     HandleImpl& secondarySelectionHandle = mHandle[RIGHT_SELECTION_HANDLE];
909
910     if( actor == grabHandle.grabArea )
911     {
912       DoPan( grabHandle, GRAB_HANDLE, gesture );
913     }
914     else if( actor == primarySelectionHandle.grabArea )
915     {
916       DoPan( primarySelectionHandle, LEFT_SELECTION_HANDLE, gesture );
917     }
918     else if( actor == secondarySelectionHandle.grabArea )
919     {
920       DoPan( secondarySelectionHandle, RIGHT_SELECTION_HANDLE, gesture );
921     }
922   }
923
924   bool OnGrabHandleTouched( Actor actor, const TouchEvent& event )
925   {
926     // Switch between pressed/release grab-handle images
927     if( event.GetPointCount() > 0 &&
928         mHandle[GRAB_HANDLE].actor )
929     {
930       const TouchPoint& point = event.GetPoint(0);
931
932       if( TouchPoint::Down == point.state )
933       {
934         mHandle[GRAB_HANDLE].pressed = true;
935         Image imagePressed = mHandleImages[GRAB_HANDLE][HANDLE_IMAGE_PRESSED];
936         if( imagePressed )
937         {
938           mHandle[GRAB_HANDLE].actor.SetImage( imagePressed );
939         }
940       }
941       else if( ( TouchPoint::Up == point.state ) ||
942                ( TouchPoint::Interrupted == point.state ) )
943       {
944         mHandle[GRAB_HANDLE].pressed = false;
945         Image imageReleased = mHandleImages[GRAB_HANDLE][HANDLE_IMAGE_RELEASED];
946         if( imageReleased )
947         {
948           mHandle[GRAB_HANDLE].actor.SetImage( imageReleased );
949         }
950       }
951     }
952
953     // Consume to avoid pop-ups accidentally closing, when handle is outside of pop-up area
954     return true;
955   }
956
957   bool OnHandleOneTouched( Actor actor, const TouchEvent& event )
958   {
959     // Switch between pressed/release selection handle images
960     if( event.GetPointCount() > 0 &&
961         mHandle[LEFT_SELECTION_HANDLE].actor )
962     {
963       const TouchPoint& point = event.GetPoint(0);
964
965       const bool flip = mSwapSelectionHandles != mHandle[LEFT_SELECTION_HANDLE].flipped;
966       if( TouchPoint::Down == point.state )
967       {
968         mHandle[LEFT_SELECTION_HANDLE].pressed = true;
969         Image imagePressed = mHandleImages[flip ? RIGHT_SELECTION_HANDLE : LEFT_SELECTION_HANDLE][HANDLE_IMAGE_PRESSED];
970         if( imagePressed )
971         {
972           mHandle[LEFT_SELECTION_HANDLE].actor.SetImage( imagePressed );
973         }
974       }
975       else if( ( TouchPoint::Up == point.state ) ||
976                ( TouchPoint::Interrupted == point.state ) )
977       {
978         mHandle[LEFT_SELECTION_HANDLE].pressed = false;
979         Image imageReleased = mHandleImages[flip ? RIGHT_SELECTION_HANDLE : LEFT_SELECTION_HANDLE][HANDLE_IMAGE_RELEASED];
980         if( imageReleased )
981         {
982           mHandle[LEFT_SELECTION_HANDLE].actor.SetImage( imageReleased );
983         }
984       }
985     }
986
987     // Consume to avoid pop-ups accidentally closing, when handle is outside of pop-up area
988     return true;
989   }
990
991   bool OnHandleTwoTouched( Actor actor, const TouchEvent& event )
992   {
993     // Switch between pressed/release selection handle images
994     if( event.GetPointCount() > 0 &&
995         mHandle[RIGHT_SELECTION_HANDLE].actor )
996     {
997       const TouchPoint& point = event.GetPoint(0);
998
999       const bool flip = mSwapSelectionHandles != mHandle[RIGHT_SELECTION_HANDLE].flipped;
1000       if( TouchPoint::Down == point.state )
1001       {
1002         Image imagePressed = mHandleImages[flip ? LEFT_SELECTION_HANDLE : RIGHT_SELECTION_HANDLE][HANDLE_IMAGE_PRESSED];
1003         mHandle[RIGHT_SELECTION_HANDLE].pressed = true;
1004         if( imagePressed )
1005         {
1006           mHandle[RIGHT_SELECTION_HANDLE].actor.SetImage( imagePressed );
1007         }
1008       }
1009       else if( ( TouchPoint::Up == point.state ) ||
1010                ( TouchPoint::Interrupted == point.state ) )
1011       {
1012         Image imageReleased = mHandleImages[flip ? LEFT_SELECTION_HANDLE : RIGHT_SELECTION_HANDLE][HANDLE_IMAGE_RELEASED];
1013         mHandle[RIGHT_SELECTION_HANDLE].pressed = false;
1014         if( imageReleased )
1015         {
1016           mHandle[RIGHT_SELECTION_HANDLE].actor.SetImage( imageReleased );
1017         }
1018       }
1019     }
1020
1021     // Consume to avoid pop-ups accidentally closing, when handle is outside of pop-up area
1022     return true;
1023   }
1024
1025   // Popup
1026
1027   float AlternatePopUpPositionRelativeToCursor()
1028   {
1029     float alternativePosition=0.0f;;
1030
1031     if ( mPrimaryCursor ) // Secondary cursor not used for paste
1032     {
1033       Cursor cursor = PRIMARY_CURSOR;
1034       alternativePosition = mCursor[cursor].position.y;
1035     }
1036
1037     const float popupHeight = 120.0f; // todo Set as a MaxSize Property in Control or retrieve from CopyPastePopup class.
1038
1039     if( mHandle[GRAB_HANDLE].active )
1040     {
1041       // If grab handle enabled then position pop-up below the grab handle.
1042       const Vector2 grabHandleSize( 59.0f, 56.0f ); // todo
1043       const float BOTTOM_HANDLE_BOTTOM_OFFSET = 1.5; //todo Should be a property
1044       alternativePosition +=  grabHandleSize.height  + popupHeight + BOTTOM_HANDLE_BOTTOM_OFFSET ;
1045     }
1046     else
1047     {
1048       alternativePosition += popupHeight;
1049     }
1050
1051     return alternativePosition;
1052   }
1053
1054   void PopUpLeavesVerticalBoundary( PropertyNotification& source )
1055   {
1056     float alternativeYPosition=0.0f;
1057     // todo use AlternatePopUpPositionRelativeToSelectionHandles() if text is highlighted
1058     // if can't be positioned above, then position below row.
1059     alternativeYPosition = AlternatePopUpPositionRelativeToCursor();
1060
1061     mCopyPastePopup.actor.SetY( alternativeYPosition );
1062   }
1063
1064
1065   void SetUpPopupPositionNotifications( )
1066   {
1067     // Note Property notifications ignore any set anchor point so conditions must allow for this.  Default is Top Left.
1068
1069     // Exceeding vertical boundary
1070
1071     Vector4 worldCoordinatesBoundingBox;
1072     LocalToWorldCoordinatesBoundingBox( mBoundingBox, worldCoordinatesBoundingBox );
1073
1074     float popupHeight = mCopyPastePopup.actor.GetRelayoutSize( Dimension::HEIGHT);
1075
1076     PropertyNotification verticalExceedNotification = mCopyPastePopup.actor.AddPropertyNotification( Actor::Property::WORLD_POSITION_Y,
1077                                                       OutsideCondition( worldCoordinatesBoundingBox.y + popupHeight * 0.5f,
1078                                                                         worldCoordinatesBoundingBox.w - popupHeight * 0.5f ) );
1079
1080     verticalExceedNotification.NotifySignal().Connect( this, &Decorator::Impl::PopUpLeavesVerticalBoundary );
1081   }
1082
1083   void GetConstrainedPopupPosition( Vector3& requiredPopupPosition, Vector3& popupSize, Vector3 anchorPoint, Actor& parent, Rect<int>& boundingBox )
1084   {
1085     DALI_ASSERT_DEBUG ( "Popup parent not on stage" && parent.OnStage() )
1086
1087     // Parent must already by added to Stage for these Get calls to work
1088     Vector3 parentAnchorPoint = parent.GetCurrentAnchorPoint();
1089     Vector3 parentWorldPositionLeftAnchor = parent.GetCurrentWorldPosition() - parent.GetCurrentSize()*parentAnchorPoint;
1090     Vector3 popupWorldPosition = parentWorldPositionLeftAnchor + requiredPopupPosition;  // Parent World position plus popup local position gives World Position
1091     Vector3 popupDistanceFromAnchorPoint = popupSize*anchorPoint;
1092
1093     // Bounding rectangle is supplied as screen coordinates, bounding will be done in world coordinates.
1094     Vector4 boundingRectangleWorld;
1095     LocalToWorldCoordinatesBoundingBox( boundingBox, boundingRectangleWorld );
1096
1097     // Calculate distance to move popup (in local space) so fits within the boundary
1098     float xOffSetToKeepWithinBounds = 0.0f;
1099     if( popupWorldPosition.x - popupDistanceFromAnchorPoint.x < boundingRectangleWorld.x )
1100     {
1101       xOffSetToKeepWithinBounds = boundingRectangleWorld.x - ( popupWorldPosition.x - popupDistanceFromAnchorPoint.x );
1102     }
1103     else if ( popupWorldPosition.x +  popupDistanceFromAnchorPoint.x > boundingRectangleWorld.z )
1104     {
1105       xOffSetToKeepWithinBounds = boundingRectangleWorld.z - ( popupWorldPosition.x +  popupDistanceFromAnchorPoint.x );
1106     }
1107
1108     // Ensure initial display of Popup is in alternative position if can not fit above. As Property notification will be a frame behind.
1109     if ( popupWorldPosition.y - popupDistanceFromAnchorPoint.y < boundingRectangleWorld.y )
1110     {
1111       requiredPopupPosition.y = AlternatePopUpPositionRelativeToCursor();
1112     }
1113
1114     requiredPopupPosition.x = requiredPopupPosition.x + xOffSetToKeepWithinBounds;
1115
1116     // Prevent pixel mis-alignment by rounding down.
1117     requiredPopupPosition.x = static_cast<int>( requiredPopupPosition.x );
1118     requiredPopupPosition.y = static_cast<int>( requiredPopupPosition.y );
1119
1120   }
1121
1122   void FlipSelectionHandleImages()
1123   {
1124     SetupTouchEvents();
1125
1126     CreateSelectionHandles();
1127
1128     HandleImpl& leftHandle = mHandle[LEFT_SELECTION_HANDLE];
1129     HandleImpl& rightHandle = mHandle[RIGHT_SELECTION_HANDLE];
1130
1131     // If handle pressed and pressed image exists then use pressed image else stick with released image
1132     const HandleImageType leftImageType = ( leftHandle.pressed && mHandleImages[LEFT_SELECTION_HANDLE][HANDLE_IMAGE_PRESSED] ) ? HANDLE_IMAGE_PRESSED : HANDLE_IMAGE_RELEASED;
1133     const HandleImageType rightImageType = ( rightHandle.pressed && mHandleImages[RIGHT_SELECTION_HANDLE][HANDLE_IMAGE_PRESSED] ) ? HANDLE_IMAGE_PRESSED : HANDLE_IMAGE_RELEASED;
1134
1135     const bool leftFlipped = mSwapSelectionHandles != leftHandle.flipped;
1136     const bool rightFlipped = mSwapSelectionHandles != rightHandle.flipped;
1137
1138     leftHandle.actor.SetImage( leftFlipped ? mHandleImages[RIGHT_SELECTION_HANDLE][leftImageType] : mHandleImages[LEFT_SELECTION_HANDLE][leftImageType] );
1139
1140     leftHandle.actor.SetAnchorPoint( leftFlipped ? AnchorPoint::TOP_LEFT : AnchorPoint::TOP_RIGHT );
1141
1142     rightHandle.actor.SetImage( rightFlipped ? mHandleImages[LEFT_SELECTION_HANDLE][rightImageType] : mHandleImages[RIGHT_SELECTION_HANDLE][rightImageType] );
1143
1144     rightHandle.actor.SetAnchorPoint( rightFlipped ? AnchorPoint::TOP_RIGHT : AnchorPoint::TOP_LEFT );
1145   }
1146
1147   void SetScrollThreshold( float threshold )
1148   {
1149     mScrollThreshold = threshold;
1150   }
1151
1152   float GetScrollThreshold() const
1153   {
1154     return mScrollThreshold;
1155   }
1156
1157   void SetScrollSpeed( float speed )
1158   {
1159     mScrollSpeed = speed;
1160     mScrollDistance = speed * SCROLL_TICK_INTERVAL * TO_SECONDS;
1161   }
1162
1163   float GetScrollSpeed() const
1164   {
1165     return mScrollSpeed;
1166   }
1167
1168   void NotifyEndOfScroll()
1169   {
1170     StopScrollTimer();
1171
1172     if( mScrollTimer )
1173     {
1174       mNotifyEndOfScroll = true;
1175     }
1176   }
1177
1178   /**
1179    * Creates and starts a timer to scroll the text when handles are close to the edges of the text.
1180    *
1181    * It only starts the timer if it's already created.
1182    */
1183   void StartScrollTimer()
1184   {
1185     if( !mScrollTimer )
1186     {
1187       mScrollTimer = Timer::New( SCROLL_TICK_INTERVAL );
1188       mScrollTimer.TickSignal().Connect( this, &Decorator::Impl::OnScrollTimerTick );
1189     }
1190
1191     if( !mScrollTimer.IsRunning() )
1192     {
1193       mScrollTimer.Start();
1194     }
1195   }
1196
1197   /**
1198    * Stops the timer used to scroll the text.
1199    */
1200   void StopScrollTimer()
1201   {
1202     if( mScrollTimer )
1203     {
1204       mScrollTimer.Stop();
1205     }
1206   }
1207
1208   /**
1209    * Callback called by the timer used to scroll the text.
1210    *
1211    * It calculates and sets a new scroll position.
1212    */
1213   bool OnScrollTimerTick()
1214   {
1215     if( HANDLE_TYPE_COUNT != mHandleScrolling )
1216     {
1217       mController.DecorationEvent( mHandleScrolling,
1218                                    HANDLE_SCROLLING,
1219                                    mScrollDirection == SCROLL_RIGHT ? mScrollDistance : -mScrollDistance,
1220                                    0.f );
1221     }
1222
1223     return true;
1224   }
1225
1226   ControllerInterface& mController;
1227
1228   TapGestureDetector  mTapDetector;
1229   PanGestureDetector  mPanGestureDetector;
1230   Timer               mCursorBlinkTimer;          ///< Timer to signal cursor to blink
1231   Timer               mScrollTimer;               ///< Timer used to scroll the text when the grab handle is moved close to the edges.
1232
1233   Layer               mActiveLayer;               ///< Layer for active handles and alike that ensures they are above all else.
1234   ImageActor          mPrimaryCursor;
1235   ImageActor          mSecondaryCursor;
1236
1237   Actor               mHighlightActor;        ///< Actor to display highlight
1238   Renderer            mHighlightRenderer;
1239   Material            mHighlightMaterial;         ///< Material used for highlight
1240   Property::Map       mQuadVertexFormat;
1241   Property::Map       mQuadIndexFormat;
1242   PopupImpl           mCopyPastePopup;
1243   TextSelectionPopup::Buttons mEnabledPopupButtons; /// Bit mask of currently enabled Popup buttons
1244   TextSelectionPopupCallbackInterface& mTextSelectionPopupCallbackInterface;
1245
1246   Image               mHandleImages[HANDLE_TYPE_COUNT][HANDLE_IMAGE_TYPE_COUNT];
1247   Vector4             mHandleColor;
1248
1249   CursorImpl          mCursor[CURSOR_COUNT];
1250   HandleImpl          mHandle[HANDLE_TYPE_COUNT];
1251
1252   PropertyBuffer      mQuadVertices;
1253   PropertyBuffer      mQuadIndices;
1254   Geometry            mQuadGeometry;
1255   QuadContainer       mHighlightQuadList;         ///< Sub-selections that combine to create the complete selection highlight
1256
1257   Rect<int>           mBoundingBox;
1258   Vector4             mHighlightColor;            ///< Color of the highlight
1259   Vector2             mHighlightPosition;         ///< The position of the highlight actor.
1260
1261   unsigned int        mActiveCursor;
1262   unsigned int        mCursorBlinkInterval;
1263   float               mCursorBlinkDuration;
1264   HandleType          mHandleScrolling;         ///< The handle which is scrolling.
1265   ScrollDirection     mScrollDirection;         ///< The direction of the scroll.
1266   float               mScrollThreshold;         ///< Defines a square area inside the control, close to the edge. A cursor entering this area will trigger scroll events.
1267   float               mScrollSpeed;             ///< The scroll speed in pixels per second.
1268   float               mScrollDistance;          ///< Distance the text scrolls during a scroll interval.
1269   int                 mTextDepth;               ///< The depth used to render the text.
1270
1271   bool                mActiveCopyPastePopup   : 1;
1272   bool                mCursorBlinkStatus      : 1; ///< Flag to switch between blink on and blink off.
1273   bool                mPrimaryCursorVisible   : 1; ///< Whether the primary cursor is visible.
1274   bool                mSecondaryCursorVisible : 1; ///< Whether the secondary cursor is visible.
1275   bool                mSwapSelectionHandles   : 1; ///< Whether to swap the selection handle images.
1276   bool                mNotifyEndOfScroll      : 1; ///< Whether to notify the end of the scroll.
1277 };
1278
1279 DecoratorPtr Decorator::New( ControllerInterface& controller,
1280                              TextSelectionPopupCallbackInterface& callbackInterface )
1281 {
1282   return DecoratorPtr( new Decorator( controller,
1283                                       callbackInterface ) );
1284 }
1285
1286 void Decorator::SetBoundingBox( const Rect<int>& boundingBox )
1287 {
1288   mImpl->mBoundingBox = boundingBox;
1289 }
1290
1291 const Rect<int>& Decorator::GetBoundingBox() const
1292 {
1293   return mImpl->mBoundingBox;
1294 }
1295
1296 void Decorator::Relayout( const Vector2& size )
1297 {
1298   mImpl->Relayout( size );
1299 }
1300
1301 void Decorator::UpdatePositions( const Vector2& scrollOffset )
1302 {
1303   mImpl->UpdatePositions( scrollOffset );
1304 }
1305
1306 /** Cursor **/
1307
1308 void Decorator::SetActiveCursor( ActiveCursor activeCursor )
1309 {
1310   mImpl->mActiveCursor = activeCursor;
1311 }
1312
1313 unsigned int Decorator::GetActiveCursor() const
1314 {
1315   return mImpl->mActiveCursor;
1316 }
1317
1318 void Decorator::SetPosition( Cursor cursor, float x, float y, float cursorHeight, float lineHeight )
1319 {
1320   mImpl->mCursor[cursor].position.x = x;
1321   mImpl->mCursor[cursor].position.y = y;
1322   mImpl->mCursor[cursor].cursorHeight = cursorHeight;
1323   mImpl->mCursor[cursor].lineHeight = lineHeight;
1324 }
1325
1326 void Decorator::GetPosition( Cursor cursor, float& x, float& y, float& cursorHeight, float& lineHeight ) const
1327 {
1328   x = mImpl->mCursor[cursor].position.x;
1329   y = mImpl->mCursor[cursor].position.y;
1330   cursorHeight = mImpl->mCursor[cursor].cursorHeight;
1331   lineHeight = mImpl->mCursor[cursor].lineHeight;
1332 }
1333
1334 const Vector2& Decorator::GetPosition( Cursor cursor ) const
1335 {
1336   return mImpl->mCursor[cursor].position;
1337 }
1338
1339 void Decorator::SetCursorColor( Cursor cursor, const Dali::Vector4& color )
1340 {
1341   mImpl->mCursor[cursor].color = color;
1342 }
1343
1344 const Dali::Vector4& Decorator::GetColor( Cursor cursor ) const
1345 {
1346   return mImpl->mCursor[cursor].color;
1347 }
1348
1349 void Decorator::StartCursorBlink()
1350 {
1351   if ( !mImpl->mCursorBlinkTimer )
1352   {
1353     mImpl->mCursorBlinkTimer = Timer::New( mImpl->mCursorBlinkInterval );
1354     mImpl->mCursorBlinkTimer.TickSignal().Connect( mImpl, &Decorator::Impl::OnCursorBlinkTimerTick );
1355   }
1356
1357   if ( !mImpl->mCursorBlinkTimer.IsRunning() )
1358   {
1359     mImpl->mCursorBlinkTimer.Start();
1360   }
1361 }
1362
1363 void Decorator::StopCursorBlink()
1364 {
1365   if ( mImpl->mCursorBlinkTimer )
1366   {
1367     mImpl->mCursorBlinkTimer.Stop();
1368   }
1369 }
1370
1371 void Decorator::SetCursorBlinkInterval( float seconds )
1372 {
1373   mImpl->mCursorBlinkInterval = static_cast<unsigned int>( seconds * TO_MILLISECONDS ); // Convert to milliseconds
1374 }
1375
1376 float Decorator::GetCursorBlinkInterval() const
1377 {
1378   return static_cast<float>( mImpl->mCursorBlinkInterval ) * TO_SECONDS;
1379 }
1380
1381 void Decorator::SetCursorBlinkDuration( float seconds )
1382 {
1383   mImpl->mCursorBlinkDuration = seconds;
1384 }
1385
1386 float Decorator::GetCursorBlinkDuration() const
1387 {
1388   return mImpl->mCursorBlinkDuration;
1389 }
1390
1391 /** Handles **/
1392
1393 void Decorator::SetHandleActive( HandleType handleType, bool active )
1394 {
1395   mImpl->mHandle[handleType].active = active;
1396
1397   if( !active )
1398   {
1399     // TODO: this is a work-around.
1400     // The problem is the handle actor does not receive the touch event with the Interrupt
1401     // state when the power button is pressed and the application goes to background.
1402     mImpl->mHandle[handleType].pressed = false;
1403     Image imageReleased = mImpl->mHandleImages[handleType][HANDLE_IMAGE_RELEASED];
1404     ImageActor imageActor = mImpl->mHandle[handleType].actor;
1405     if( imageReleased && imageActor )
1406     {
1407        imageActor.SetImage( imageReleased );
1408     }
1409   }
1410 }
1411
1412 bool Decorator::IsHandleActive( HandleType handleType ) const
1413 {
1414   return mImpl->mHandle[handleType].active ;
1415 }
1416
1417 void Decorator::SetHandleImage( HandleType handleType, HandleImageType handleImageType, Dali::Image image )
1418 {
1419   mImpl->mHandleImages[handleType][handleImageType] = image;
1420 }
1421
1422 Dali::Image Decorator::GetHandleImage( HandleType handleType, HandleImageType handleImageType ) const
1423 {
1424   return mImpl->mHandleImages[handleType][handleImageType];
1425 }
1426
1427 void Decorator::SetHandleColor( const Vector4& color )
1428 {
1429   mImpl->mHandleColor = color;
1430 }
1431
1432 const Vector4& Decorator::GetHandleColor() const
1433 {
1434   return mImpl->mHandleColor;
1435 }
1436
1437 void Decorator::SetPosition( HandleType handleType, float x, float y, float height )
1438 {
1439   // Adjust grab handle displacement
1440   Impl::HandleImpl& handle = mImpl->mHandle[handleType];
1441
1442   handle.grabDisplacementX -= x - handle.position.x;
1443   handle.grabDisplacementY -= y - handle.position.y;
1444
1445   handle.position.x = x;
1446   handle.position.y = y;
1447   handle.lineHeight = height;
1448 }
1449
1450 void Decorator::GetPosition( HandleType handleType, float& x, float& y, float& height ) const
1451 {
1452   Impl::HandleImpl& handle = mImpl->mHandle[handleType];
1453
1454   x = handle.position.x;
1455   y = handle.position.y;
1456   height = handle.lineHeight;
1457 }
1458
1459 const Vector2& Decorator::GetPosition( HandleType handleType ) const
1460 {
1461   return mImpl->mHandle[handleType].position;
1462 }
1463
1464 void Decorator::SwapSelectionHandlesEnabled( bool enable )
1465 {
1466   mImpl->mSwapSelectionHandles = enable;
1467
1468   mImpl->FlipSelectionHandleImages();
1469 }
1470
1471 void Decorator::AddHighlight( float x1, float y1, float x2, float y2 )
1472 {
1473   mImpl->mHighlightQuadList.push_back( QuadCoordinates(x1, y1, x2, y2) );
1474 }
1475
1476 void Decorator::ClearHighlights()
1477 {
1478   mImpl->mHighlightQuadList.clear();
1479   mImpl->mHighlightPosition = Vector2::ZERO;
1480 }
1481
1482 void Decorator::SetHighlightColor( const Vector4& color )
1483 {
1484   mImpl->mHighlightColor = color;
1485 }
1486
1487 const Vector4& Decorator::GetHighlightColor() const
1488 {
1489   return mImpl->mHighlightColor;
1490 }
1491
1492 void Decorator::SetTextDepth( int textDepth )
1493 {
1494   mImpl->mTextDepth = textDepth;
1495 }
1496
1497 void Decorator::SetPopupActive( bool active )
1498 {
1499   mImpl->mActiveCopyPastePopup = active;
1500 }
1501
1502 bool Decorator::IsPopupActive() const
1503 {
1504   return mImpl->mActiveCopyPastePopup ;
1505 }
1506
1507 void Decorator::SetEnabledPopupButtons( TextSelectionPopup::Buttons& enabledButtonsBitMask )
1508 {
1509    mImpl->mEnabledPopupButtons = enabledButtonsBitMask;
1510
1511    if ( !mImpl->mCopyPastePopup.actor )
1512    {
1513      mImpl->mCopyPastePopup.actor = TextSelectionPopup::New( &mImpl->mTextSelectionPopupCallbackInterface );
1514 #ifdef DECORATOR_DEBUG
1515      mImpl->mCopyPastePopup.actor.SetName("mCopyPastePopup");
1516 #endif
1517      mImpl->mCopyPastePopup.actor.SetAnchorPoint( AnchorPoint::CENTER );
1518      mImpl->mCopyPastePopup.actor.OnRelayoutSignal().Connect( mImpl,  &Decorator::Impl::PopupRelayoutComplete  ); // Position popup after size negotiation
1519    }
1520
1521    mImpl->mCopyPastePopup.actor.EnableButtons( mImpl->mEnabledPopupButtons );
1522 }
1523
1524 TextSelectionPopup::Buttons& Decorator::GetEnabledPopupButtons()
1525 {
1526   return mImpl->mEnabledPopupButtons;
1527 }
1528
1529 /** Scroll **/
1530
1531 void Decorator::SetScrollThreshold( float threshold )
1532 {
1533   mImpl->SetScrollThreshold( threshold );
1534 }
1535
1536 float Decorator::GetScrollThreshold() const
1537 {
1538   return mImpl->GetScrollThreshold();
1539 }
1540
1541 void Decorator::SetScrollSpeed( float speed )
1542 {
1543   mImpl->SetScrollSpeed( speed );
1544 }
1545
1546 float Decorator::GetScrollSpeed() const
1547 {
1548   return mImpl->GetScrollSpeed();
1549 }
1550
1551 void Decorator::NotifyEndOfScroll()
1552 {
1553   mImpl->NotifyEndOfScroll();
1554 }
1555
1556 Decorator::~Decorator()
1557 {
1558   delete mImpl;
1559 }
1560
1561 Decorator::Decorator( ControllerInterface& controller,
1562                       TextSelectionPopupCallbackInterface& callbackInterface )
1563 : mImpl( NULL )
1564 {
1565   mImpl = new Decorator::Impl( controller, callbackInterface );
1566 }
1567
1568 } // namespace Text
1569
1570 } // namespace Toolkit
1571
1572 } // namespace Dali