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