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