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