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