7934b6f1aa8c8073444a424c6520b387ba326280
[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         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.SetSizeModeFactor( DEFAULT_SELECTION_HANDLE_RELATIVE_SIZE );
654       primary.grabArea.SetPositionInheritanceMode( Dali::USE_PARENT_POSITION );
655
656       mTapDetector.Attach( primary.grabArea );
657       mPanGestureDetector.Attach( primary.grabArea );
658       primary.grabArea.TouchedSignal().Connect( this, &Decorator::Impl::OnHandleOneTouched );
659
660       primary.actor.Add( primary.grabArea );
661       mActiveLayer.Add( primary.actor );
662     }
663
664     HandleImpl& secondary = mHandle[ RIGHT_SELECTION_HANDLE ];
665     if( !secondary.actor )
666     {
667       if( !mHandleImages[RIGHT_SELECTION_HANDLE][HANDLE_IMAGE_RELEASED] )
668       {
669         mHandleImages[RIGHT_SELECTION_HANDLE][HANDLE_IMAGE_RELEASED] = ResourceImage::New( DEFAULT_SELECTION_HANDLE_TWO_RELEASED );
670       }
671       if( !mHandleImages[RIGHT_SELECTION_HANDLE][HANDLE_IMAGE_PRESSED] )
672       {
673         mHandleImages[RIGHT_SELECTION_HANDLE][HANDLE_IMAGE_PRESSED] = ResourceImage::New( DEFAULT_SELECTION_HANDLE_TWO_PRESSED );
674       }
675
676       secondary.actor = ImageActor::New( mHandleImages[RIGHT_SELECTION_HANDLE][HANDLE_IMAGE_RELEASED] );
677 #ifdef DECORATOR_DEBUG
678       secondary.actor.SetName("SelectionHandleTwo");
679 #endif
680       secondary.actor.SetAnchorPoint( AnchorPoint::TOP_LEFT ); // Change to BOTTOM_LEFT if Look'n'Feel requires handle above text.
681       secondary.actor.SetDrawMode( DrawMode::OVERLAY ); // ensure grab handle above text
682       secondary.flipped = false;
683
684       secondary.grabArea = Actor::New(); // Area that Grab handle responds to, larger than actual handle so easier to move
685 #ifdef DECORATOR_DEBUG
686       secondary.grabArea.SetName("SelectionHandleTwoGrabArea");
687 #endif
688       secondary.grabArea.SetResizePolicy( ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::ALL_DIMENSIONS );
689       secondary.grabArea.SetSizeModeFactor( DEFAULT_SELECTION_HANDLE_RELATIVE_SIZE );
690       secondary.grabArea.SetPositionInheritanceMode( Dali::USE_PARENT_POSITION );
691
692       mTapDetector.Attach( secondary.grabArea );
693       mPanGestureDetector.Attach( secondary.grabArea );
694       secondary.grabArea.TouchedSignal().Connect( this, &Decorator::Impl::OnHandleTwoTouched );
695
696       secondary.actor.Add( secondary.grabArea );
697       mActiveLayer.Add( secondary.actor );
698     }
699   }
700
701   void CreateHighlight()
702   {
703     if ( !mHighlightMeshActor )
704     {
705       mHighlightMaterial = Material::New( "HighlightMaterial" );
706       mHighlightMaterial.SetDiffuseColor( mHighlightColor );
707
708       mHighlightMeshData.SetMaterial( mHighlightMaterial );
709       mHighlightMeshData.SetHasNormals( true );
710
711       mHighlightMesh = Mesh::New( mHighlightMeshData );
712
713       mHighlightMeshActor = MeshActor::New( mHighlightMesh );
714 #ifdef DECORATOR_DEBUG
715       mHighlightMeshActor.SetName( "HighlightMeshActor" );
716 #endif
717       mHighlightMeshActor.SetAnchorPoint( AnchorPoint::TOP_LEFT );
718
719       // Add the highlight box telling the controller it needs clipping.
720       mController.AddDecoration( mHighlightMeshActor, true );
721     }
722
723     mHighlightMeshActor.SetPosition( mHighlightPosition.x, mHighlightPosition.y, DISPLAYED_HIGHLIGHT_Z_OFFSET );
724   }
725
726   void UpdateHighlight()
727   {
728     //  Construct a Mesh with a texture to be used as the highlight 'box' for selected text
729     //
730     //  Example scenarios where mesh is made from 3, 1, 2, 2 ,3 or 3 quads.
731     //
732     //   [ TOP   ]  [ TOP ]      [TOP ]  [ TOP    ]      [ TOP  ]      [ TOP  ]
733     //  [ MIDDLE ]             [BOTTOM]  [BOTTOM]      [ MIDDLE ]   [ MIDDLE  ]
734     //  [ BOTTOM]                                      [ MIDDLE ]   [ MIDDLE  ]
735     //                                                 [BOTTOM]     [ MIDDLE  ]
736     //                                                              [BOTTOM]
737     //
738     //  Each quad is created as 2 triangles.
739     //  Middle is just 1 quad regardless of its size.
740     //
741     //  (0,0)         (0,0)
742     //     0*    *2     0*       *2
743     //     TOP          TOP
744     //     3*    *1     3*       *1
745     //  4*       *1     4*     *6
746     //     MIDDLE         BOTTOM
747     //  6*       *5     7*     *5
748     //  6*    *8
749     //   BOTTOM
750     //  9*    *7
751     //
752
753     if ( mHighlightMesh && mHighlightMaterial && !mHighlightQuadList.empty() )
754     {
755       MeshData::VertexContainer vertices;
756       Dali::MeshData::FaceIndices faceIndices;
757
758       std::vector<QuadCoordinates>::iterator iter = mHighlightQuadList.begin();
759       std::vector<QuadCoordinates>::iterator endIter = mHighlightQuadList.end();
760
761       // vertex position defaults to (0 0 0)
762       MeshData::Vertex vertex;
763       // set normal for all vertices as (0 0 1) pointing outward from TextInput Actor.
764       vertex.nZ = 1.0f;
765
766       for(std::size_t v = 0; iter != endIter; ++iter,v+=4 )
767       {
768         // Add each quad geometry (a sub-selection) to the mesh data.
769
770         // 0-----1
771         // |\    |
772         // | \ A |
773         // |  \  |
774         // | B \ |
775         // |    \|
776         // 2-----3
777
778         QuadCoordinates& quad = *iter;
779         // top-left (v+0)
780         vertex.x = quad.min.x;
781         vertex.y = quad.min.y;
782         vertices.push_back( vertex );
783
784         // top-right (v+1)
785         vertex.x = quad.max.x;
786         vertex.y = quad.min.y;
787         vertices.push_back( vertex );
788
789         // bottom-left (v+2)
790         vertex.x = quad.min.x;
791         vertex.y = quad.max.y;
792         vertices.push_back( vertex );
793
794         // bottom-right (v+3)
795         vertex.x = quad.max.x;
796         vertex.y = quad.max.y;
797         vertices.push_back( vertex );
798
799         // triangle A (3, 1, 0)
800         faceIndices.push_back( v + 3 );
801         faceIndices.push_back( v + 1 );
802         faceIndices.push_back( v );
803
804         // triangle B (0, 2, 3)
805         faceIndices.push_back( v );
806         faceIndices.push_back( v + 2 );
807         faceIndices.push_back( v + 3 );
808
809         mHighlightMeshData.SetFaceIndices( faceIndices );
810       }
811
812       BoneContainer bones(0); // passed empty as bones not required
813       mHighlightMeshData.SetData( vertices, faceIndices, bones, mHighlightMaterial );
814       mHighlightMesh.UpdateMeshData( mHighlightMeshData );
815     }
816   }
817
818   void OnTap( Actor actor, const TapGesture& tap )
819   {
820     if( actor == mHandle[GRAB_HANDLE].actor )
821     {
822       // TODO
823     }
824   }
825
826   void DoPan( HandleImpl& handle, HandleType type, const PanGesture& gesture )
827   {
828     if( Gesture::Started == gesture.state )
829     {
830       handle.grabDisplacementX = handle.grabDisplacementY = 0;
831     }
832
833     handle.grabDisplacementX += gesture.displacement.x;
834     handle.grabDisplacementY += gesture.displacement.y;
835
836     const float x = handle.position.x + handle.grabDisplacementX;
837     const float y = handle.position.y + handle.lineHeight*0.5f + handle.grabDisplacementY;
838
839     if( Gesture::Started    == gesture.state ||
840         Gesture::Continuing == gesture.state )
841     {
842       Vector2 targetSize;
843       mController.GetTargetSize( targetSize );
844
845       if( x < mScrollThreshold )
846       {
847         mScrollDirection = SCROLL_RIGHT;
848         mHandleScrolling = type;
849         StartScrollTimer();
850       }
851       else if( x > targetSize.width - mScrollThreshold )
852       {
853         mScrollDirection = SCROLL_LEFT;
854         mHandleScrolling = type;
855         StartScrollTimer();
856       }
857       else
858       {
859         mHandleScrolling = HANDLE_TYPE_COUNT;
860         StopScrollTimer();
861         mController.DecorationEvent( type, HANDLE_PRESSED, x, y );
862       }
863     }
864     else if( Gesture::Finished  == gesture.state ||
865              Gesture::Cancelled == gesture.state )
866     {
867       if( mScrollTimer && mScrollTimer.IsRunning() )
868       {
869         mHandleScrolling = HANDLE_TYPE_COUNT;
870         StopScrollTimer();
871         mController.DecorationEvent( type, HANDLE_STOP_SCROLLING, x, y );
872       }
873       else
874       {
875         mController.DecorationEvent( type, HANDLE_RELEASED, x, y );
876       }
877
878       if( GRAB_HANDLE == type )
879       {
880         handle.actor.SetImage( mHandleImages[type][HANDLE_IMAGE_RELEASED] );
881       }
882       else
883       {
884         HandleType selectionHandleType = type;
885
886         if( mSwapSelectionHandles != handle.flipped )
887         {
888           selectionHandleType = ( LEFT_SELECTION_HANDLE == type ) ? RIGHT_SELECTION_HANDLE : LEFT_SELECTION_HANDLE;
889         }
890
891         handle.actor.SetImage( mHandleImages[selectionHandleType][HANDLE_IMAGE_RELEASED] );
892       }
893       handle.pressed = false;
894     }
895   }
896
897   void OnPan( Actor actor, const PanGesture& gesture )
898   {
899     HandleImpl& grabHandle = mHandle[GRAB_HANDLE];
900     HandleImpl& primarySelectionHandle = mHandle[LEFT_SELECTION_HANDLE];
901     HandleImpl& secondarySelectionHandle = mHandle[RIGHT_SELECTION_HANDLE];
902
903     if( actor == grabHandle.grabArea )
904     {
905       DoPan( grabHandle, GRAB_HANDLE, gesture );
906     }
907     else if( actor == primarySelectionHandle.grabArea )
908     {
909       DoPan( primarySelectionHandle, LEFT_SELECTION_HANDLE, gesture );
910     }
911     else if( actor == secondarySelectionHandle.grabArea )
912     {
913       DoPan( secondarySelectionHandle, RIGHT_SELECTION_HANDLE, gesture );
914     }
915   }
916
917   bool OnGrabHandleTouched( Actor actor, const TouchEvent& event )
918   {
919     // Switch between pressed/release grab-handle images
920     if( event.GetPointCount() > 0 &&
921         mHandle[GRAB_HANDLE].actor )
922     {
923       const TouchPoint& point = event.GetPoint(0);
924
925       if( TouchPoint::Down == point.state )
926       {
927         mHandle[GRAB_HANDLE].pressed = true;
928         Image imagePressed = mHandleImages[GRAB_HANDLE][HANDLE_IMAGE_PRESSED];
929         if( imagePressed )
930         {
931           mHandle[GRAB_HANDLE].actor.SetImage( imagePressed );
932         }
933       }
934       else if( TouchPoint::Up == point.state )
935       {
936         mHandle[GRAB_HANDLE].pressed = false;
937         Image imageReleased = mHandleImages[GRAB_HANDLE][HANDLE_IMAGE_RELEASED];
938         if( imageReleased )
939         {
940           mHandle[GRAB_HANDLE].actor.SetImage( imageReleased );
941         }
942       }
943     }
944
945     // Consume to avoid pop-ups accidentally closing, when handle is outside of pop-up area
946     return true;
947   }
948
949   bool OnHandleOneTouched( Actor actor, const TouchEvent& event )
950   {
951     // Switch between pressed/release selection handle images
952     if( event.GetPointCount() > 0 &&
953         mHandle[LEFT_SELECTION_HANDLE].actor )
954     {
955       const TouchPoint& point = event.GetPoint(0);
956
957       const bool flip = mSwapSelectionHandles != mHandle[LEFT_SELECTION_HANDLE].flipped;
958       if( TouchPoint::Down == point.state )
959       {
960         mHandle[LEFT_SELECTION_HANDLE].pressed = true;
961         Image imagePressed = mHandleImages[flip ? RIGHT_SELECTION_HANDLE : LEFT_SELECTION_HANDLE][HANDLE_IMAGE_PRESSED];
962         if( imagePressed )
963         {
964           mHandle[LEFT_SELECTION_HANDLE].actor.SetImage( imagePressed );
965         }
966       }
967       else if( TouchPoint::Up == point.state )
968       {
969         mHandle[LEFT_SELECTION_HANDLE].pressed = false;
970         Image imageReleased = mHandleImages[flip ? RIGHT_SELECTION_HANDLE : LEFT_SELECTION_HANDLE][HANDLE_IMAGE_RELEASED];
971         if( imageReleased )
972         {
973           mHandle[LEFT_SELECTION_HANDLE].actor.SetImage( imageReleased );
974         }
975       }
976     }
977
978     // Consume to avoid pop-ups accidentally closing, when handle is outside of pop-up area
979     return true;
980   }
981
982   bool OnHandleTwoTouched( Actor actor, const TouchEvent& event )
983   {
984     // Switch between pressed/release selection handle images
985     if( event.GetPointCount() > 0 &&
986         mHandle[RIGHT_SELECTION_HANDLE].actor )
987     {
988       const TouchPoint& point = event.GetPoint(0);
989
990       const bool flip = mSwapSelectionHandles != mHandle[RIGHT_SELECTION_HANDLE].flipped;
991       if( TouchPoint::Down == point.state )
992       {
993         Image imagePressed = mHandleImages[flip ? LEFT_SELECTION_HANDLE : RIGHT_SELECTION_HANDLE][HANDLE_IMAGE_PRESSED];
994         mHandle[RIGHT_SELECTION_HANDLE].pressed = true;
995         if( imagePressed )
996         {
997           mHandle[RIGHT_SELECTION_HANDLE].actor.SetImage( imagePressed );
998         }
999       }
1000       else if( TouchPoint::Up == point.state )
1001       {
1002         Image imageReleased = mHandleImages[flip ? LEFT_SELECTION_HANDLE : RIGHT_SELECTION_HANDLE][HANDLE_IMAGE_RELEASED];
1003         mHandle[RIGHT_SELECTION_HANDLE].pressed = false;
1004         if( imageReleased )
1005         {
1006           mHandle[RIGHT_SELECTION_HANDLE].actor.SetImage( imageReleased );
1007         }
1008       }
1009     }
1010
1011     // Consume to avoid pop-ups accidentally closing, when handle is outside of pop-up area
1012     return true;
1013   }
1014
1015   // Popup
1016
1017   float AlternatePopUpPositionRelativeToCursor()
1018   {
1019     float alternativePosition=0.0f;;
1020
1021     if ( mPrimaryCursor ) // Secondary cursor not used for paste
1022     {
1023       Cursor cursor = PRIMARY_CURSOR;
1024       alternativePosition = mCursor[cursor].position.y;
1025     }
1026
1027     const float popupHeight = 120.0f; // todo Set as a MaxSize Property in Control or retrieve from CopyPastePopup class.
1028
1029     if( mHandle[GRAB_HANDLE].active )
1030     {
1031       // If grab handle enabled then position pop-up below the grab handle.
1032       const Vector2 grabHandleSize( 59.0f, 56.0f ); // todo
1033       const float BOTTOM_HANDLE_BOTTOM_OFFSET = 1.5; //todo Should be a property
1034       alternativePosition +=  grabHandleSize.height  + popupHeight + BOTTOM_HANDLE_BOTTOM_OFFSET ;
1035     }
1036     else
1037     {
1038       alternativePosition += popupHeight;
1039     }
1040
1041     return alternativePosition;
1042   }
1043
1044   void PopUpLeavesVerticalBoundary( PropertyNotification& source )
1045   {
1046     float alternativeYPosition=0.0f;
1047     // todo use AlternatePopUpPositionRelativeToSelectionHandles() if text is highlighted
1048     // if can't be positioned above, then position below row.
1049     alternativeYPosition = AlternatePopUpPositionRelativeToCursor();
1050
1051     mCopyPastePopup.actor.SetY( alternativeYPosition );
1052   }
1053
1054
1055   void SetUpPopupPositionNotifications( )
1056   {
1057     // Note Property notifications ignore any set anchor point so conditions must allow for this.  Default is Top Left.
1058
1059     // Exceeding vertical boundary
1060
1061     Vector4 worldCoordinatesBoundingBox;
1062     LocalToWorldCoordinatesBoundingBox( mBoundingBox, worldCoordinatesBoundingBox );
1063
1064     float popupHeight = mCopyPastePopup.actor.GetRelayoutSize( Dimension::HEIGHT);
1065
1066     PropertyNotification verticalExceedNotification = mCopyPastePopup.actor.AddPropertyNotification( Actor::Property::WORLD_POSITION_Y,
1067                                                       OutsideCondition( worldCoordinatesBoundingBox.y + popupHeight * 0.5f,
1068                                                                         worldCoordinatesBoundingBox.w - popupHeight * 0.5f ) );
1069
1070     verticalExceedNotification.NotifySignal().Connect( this, &Decorator::Impl::PopUpLeavesVerticalBoundary );
1071   }
1072
1073   void GetConstrainedPopupPosition( Vector3& requiredPopupPosition, Vector3& popupSize, Vector3 anchorPoint, Actor& parent, Rect<int>& boundingBox )
1074   {
1075     DALI_ASSERT_DEBUG ( "Popup parent not on stage" && parent.OnStage() )
1076
1077     // Parent must already by added to Stage for these Get calls to work
1078     Vector3 parentAnchorPoint = parent.GetCurrentAnchorPoint();
1079     Vector3 parentWorldPositionLeftAnchor = parent.GetCurrentWorldPosition() - parent.GetCurrentSize()*parentAnchorPoint;
1080     Vector3 popupWorldPosition = parentWorldPositionLeftAnchor + requiredPopupPosition;  // Parent World position plus popup local position gives World Position
1081     Vector3 popupDistanceFromAnchorPoint = popupSize*anchorPoint;
1082
1083     // Bounding rectangle is supplied as screen coordinates, bounding will be done in world coordinates.
1084     Vector4 boundingRectangleWorld;
1085     LocalToWorldCoordinatesBoundingBox( boundingBox, boundingRectangleWorld );
1086
1087     // Calculate distance to move popup (in local space) so fits within the boundary
1088     float xOffSetToKeepWithinBounds = 0.0f;
1089     if( popupWorldPosition.x - popupDistanceFromAnchorPoint.x < boundingRectangleWorld.x )
1090     {
1091       xOffSetToKeepWithinBounds = boundingRectangleWorld.x - ( popupWorldPosition.x - popupDistanceFromAnchorPoint.x );
1092     }
1093     else if ( popupWorldPosition.x +  popupDistanceFromAnchorPoint.x > boundingRectangleWorld.z )
1094     {
1095       xOffSetToKeepWithinBounds = boundingRectangleWorld.z - ( popupWorldPosition.x +  popupDistanceFromAnchorPoint.x );
1096     }
1097
1098     // Ensure initial display of Popup is in alternative position if can not fit above. As Property notification will be a frame behind.
1099     if ( popupWorldPosition.y - popupDistanceFromAnchorPoint.y < boundingRectangleWorld.y )
1100     {
1101       requiredPopupPosition.y = AlternatePopUpPositionRelativeToCursor();
1102     }
1103
1104     requiredPopupPosition.x = requiredPopupPosition.x + xOffSetToKeepWithinBounds;
1105
1106     // Prevent pixel mis-alignment by rounding down.
1107     requiredPopupPosition.x = static_cast<int>( requiredPopupPosition.x );
1108     requiredPopupPosition.y = static_cast<int>( requiredPopupPosition.y );
1109
1110   }
1111
1112   void FlipSelectionHandleImages()
1113   {
1114     SetupTouchEvents();
1115
1116     CreateSelectionHandles();
1117
1118     HandleImpl& leftHandle = mHandle[LEFT_SELECTION_HANDLE];
1119     HandleImpl& rightHandle = mHandle[RIGHT_SELECTION_HANDLE];
1120
1121     const HandleImageType leftImageType = leftHandle.pressed ? HANDLE_IMAGE_PRESSED : HANDLE_IMAGE_RELEASED;
1122     const HandleImageType rightImageType = rightHandle.pressed ? HANDLE_IMAGE_PRESSED : HANDLE_IMAGE_RELEASED;
1123     const bool leftFlipped = mSwapSelectionHandles != leftHandle.flipped;
1124     const bool rightFlipped = mSwapSelectionHandles != rightHandle.flipped;
1125
1126     leftHandle.actor.SetImage( leftFlipped ? mHandleImages[RIGHT_SELECTION_HANDLE][leftImageType] : mHandleImages[LEFT_SELECTION_HANDLE][leftImageType] );
1127
1128     leftHandle.actor.SetAnchorPoint( leftFlipped ? AnchorPoint::TOP_LEFT : AnchorPoint::TOP_RIGHT );
1129
1130     rightHandle.actor.SetImage( rightFlipped ? mHandleImages[LEFT_SELECTION_HANDLE][rightImageType] : mHandleImages[RIGHT_SELECTION_HANDLE][rightImageType] );
1131
1132     rightHandle.actor.SetAnchorPoint( rightFlipped ? AnchorPoint::TOP_RIGHT : AnchorPoint::TOP_LEFT );
1133   }
1134
1135   void SetScrollThreshold( float threshold )
1136   {
1137     mScrollThreshold = threshold;
1138   }
1139
1140   float GetScrollThreshold() const
1141   {
1142     return mScrollThreshold;
1143   }
1144
1145   void SetScrollSpeed( float speed )
1146   {
1147     mScrollSpeed = speed;
1148     mScrollDistance = speed * SCROLL_TICK_INTERVAL * TO_SECONDS;
1149   }
1150
1151   float GetScrollSpeed() const
1152   {
1153     return mScrollSpeed;
1154   }
1155
1156   /**
1157    * Creates and starts a timer to scroll the text when handles are close to the edges of the text.
1158    *
1159    * It only starts the timer if it's already created.
1160    */
1161   void StartScrollTimer()
1162   {
1163     if( !mScrollTimer )
1164     {
1165       mScrollTimer = Timer::New( SCROLL_TICK_INTERVAL );
1166       mScrollTimer.TickSignal().Connect( this, &Decorator::Impl::OnScrollTimerTick );
1167     }
1168
1169     if( !mScrollTimer.IsRunning() )
1170     {
1171       mScrollTimer.Start();
1172     }
1173   }
1174
1175   /**
1176    * Stops the timer used to scroll the text.
1177    */
1178   void StopScrollTimer()
1179   {
1180     if( mScrollTimer )
1181     {
1182       mScrollTimer.Stop();
1183     }
1184   }
1185
1186   /**
1187    * Callback called by the timer used to scroll the text.
1188    *
1189    * It calculates and sets a new scroll position.
1190    */
1191   bool OnScrollTimerTick()
1192   {
1193     if( HANDLE_TYPE_COUNT != mHandleScrolling )
1194     {
1195       mController.DecorationEvent( mHandleScrolling,
1196                                    HANDLE_SCROLLING,
1197                                    mScrollDirection == SCROLL_RIGHT ? mScrollDistance : -mScrollDistance,
1198                                    0.f );
1199     }
1200
1201     return true;
1202   }
1203
1204   ControllerInterface& mController;
1205
1206   TapGestureDetector  mTapDetector;
1207   PanGestureDetector  mPanGestureDetector;
1208   Timer               mCursorBlinkTimer;          ///< Timer to signal cursor to blink
1209   Timer               mScrollTimer;               ///< Timer used to scroll the text when the grab handle is moved close to the edges.
1210
1211   Layer               mActiveLayer;               ///< Layer for active handles and alike that ensures they are above all else.
1212   ImageActor          mPrimaryCursor;
1213   ImageActor          mSecondaryCursor;
1214   MeshActor           mHighlightMeshActor;        ///< Mesh Actor to display highlight
1215
1216   PopupImpl           mCopyPastePopup;
1217   TextSelectionPopup::Buttons mEnabledPopupButtons; /// Bit mask of currently enabled Popup buttons
1218   TextSelectionPopupCallbackInterface& mTextSelectionPopupCallbackInterface;
1219
1220   Image               mHandleImages[HANDLE_TYPE_COUNT][HANDLE_IMAGE_TYPE_COUNT];
1221   Image               mCursorImage;
1222   Mesh                mHighlightMesh;             ///< Mesh for highlight
1223   MeshData            mHighlightMeshData;         ///< Mesh Data for highlight
1224   Material            mHighlightMaterial;         ///< Material used for highlight
1225
1226   CursorImpl          mCursor[CURSOR_COUNT];
1227   HandleImpl          mHandle[HANDLE_TYPE_COUNT];
1228   QuadContainer       mHighlightQuadList;         ///< Sub-selections that combine to create the complete selection highlight
1229   Vector2             mHighlightPosition;         ///< The position of the highlight actor.
1230
1231   Rect<int>           mBoundingBox;
1232   Vector4             mHighlightColor;            ///< Color of the highlight
1233
1234   unsigned int        mActiveCursor;
1235   unsigned int        mCursorBlinkInterval;
1236   float               mCursorBlinkDuration;
1237   HandleType          mHandleScrolling;         ///< The handle which is scrolling.
1238   ScrollDirection     mScrollDirection;         ///< The direction of the scroll.
1239   float               mScrollThreshold;         ///< Defines a square area inside the control, close to the edge. A cursor entering this area will trigger scroll events.
1240   float               mScrollSpeed;             ///< The scroll speed in pixels per second.
1241   float               mScrollDistance;          ///< Distance the text scrolls during a scroll interval.
1242   unsigned int        mScrollInterval;          ///< Time in milliseconds of a scroll interval.
1243
1244   bool                mActiveCopyPastePopup   : 1;
1245   bool                mCursorBlinkStatus      : 1; ///< Flag to switch between blink on and blink off.
1246   bool                mPrimaryCursorVisible   : 1; ///< Whether the primary cursor is visible.
1247   bool                mSecondaryCursorVisible : 1; ///< Whether the secondary cursor is visible.
1248   bool                mSwapSelectionHandles   : 1; ///< Whether to swap the selection handle images.
1249 };
1250
1251 DecoratorPtr Decorator::New( ControllerInterface& controller,
1252                              TextSelectionPopupCallbackInterface& callbackInterface )
1253 {
1254   return DecoratorPtr( new Decorator( controller,
1255                                       callbackInterface ) );
1256 }
1257
1258 void Decorator::SetBoundingBox( const Rect<int>& boundingBox )
1259 {
1260   mImpl->mBoundingBox = boundingBox;
1261 }
1262
1263 const Rect<int>& Decorator::GetBoundingBox() const
1264 {
1265   return mImpl->mBoundingBox;
1266 }
1267
1268 void Decorator::Relayout( const Vector2& size )
1269 {
1270   mImpl->Relayout( size );
1271 }
1272
1273 void Decorator::UpdatePositions( const Vector2& scrollOffset )
1274 {
1275   mImpl->UpdatePositions( scrollOffset );
1276 }
1277
1278 /** Cursor **/
1279
1280 void Decorator::SetActiveCursor( ActiveCursor activeCursor )
1281 {
1282   mImpl->mActiveCursor = activeCursor;
1283 }
1284
1285 unsigned int Decorator::GetActiveCursor() const
1286 {
1287   return mImpl->mActiveCursor;
1288 }
1289
1290 void Decorator::SetPosition( Cursor cursor, float x, float y, float cursorHeight, float lineHeight )
1291 {
1292   mImpl->mCursor[cursor].position.x = x;
1293   mImpl->mCursor[cursor].position.y = y;
1294   mImpl->mCursor[cursor].cursorHeight = cursorHeight;
1295   mImpl->mCursor[cursor].lineHeight = lineHeight;
1296 }
1297
1298 void Decorator::GetPosition( Cursor cursor, float& x, float& y, float& cursorHeight, float& lineHeight ) const
1299 {
1300   x = mImpl->mCursor[cursor].position.x;
1301   y = mImpl->mCursor[cursor].position.y;
1302   cursorHeight = mImpl->mCursor[cursor].cursorHeight;
1303   lineHeight = mImpl->mCursor[cursor].lineHeight;
1304 }
1305
1306 const Vector2& Decorator::GetPosition( Cursor cursor ) const
1307 {
1308   return mImpl->mCursor[cursor].position;
1309 }
1310
1311 void Decorator::SetColor( Cursor cursor, const Dali::Vector4& color )
1312 {
1313   mImpl->mCursor[cursor].color = color;
1314 }
1315
1316 const Dali::Vector4& Decorator::GetColor( Cursor cursor ) const
1317 {
1318   return mImpl->mCursor[cursor].color;
1319 }
1320
1321 void Decorator::StartCursorBlink()
1322 {
1323   if ( !mImpl->mCursorBlinkTimer )
1324   {
1325     mImpl->mCursorBlinkTimer = Timer::New( mImpl->mCursorBlinkInterval );
1326     mImpl->mCursorBlinkTimer.TickSignal().Connect( mImpl, &Decorator::Impl::OnCursorBlinkTimerTick );
1327   }
1328
1329   if ( !mImpl->mCursorBlinkTimer.IsRunning() )
1330   {
1331     mImpl->mCursorBlinkTimer.Start();
1332   }
1333 }
1334
1335 void Decorator::StopCursorBlink()
1336 {
1337   if ( mImpl->mCursorBlinkTimer )
1338   {
1339     mImpl->mCursorBlinkTimer.Stop();
1340   }
1341 }
1342
1343 void Decorator::SetCursorBlinkInterval( float seconds )
1344 {
1345   mImpl->mCursorBlinkInterval = static_cast<unsigned int>( seconds * TO_MILLISECONDS ); // Convert to milliseconds
1346 }
1347
1348 float Decorator::GetCursorBlinkInterval() const
1349 {
1350   return static_cast<float>( mImpl->mCursorBlinkInterval ) * TO_SECONDS;
1351 }
1352
1353 void Decorator::SetCursorBlinkDuration( float seconds )
1354 {
1355   mImpl->mCursorBlinkDuration = seconds;
1356 }
1357
1358 float Decorator::GetCursorBlinkDuration() const
1359 {
1360   return mImpl->mCursorBlinkDuration;
1361 }
1362
1363 /** Handles **/
1364
1365 void Decorator::SetHandleActive( HandleType handleType, bool active )
1366 {
1367   mImpl->mHandle[handleType].active = active;
1368 }
1369
1370 bool Decorator::IsHandleActive( HandleType handleType ) const
1371 {
1372   return mImpl->mHandle[handleType].active ;
1373 }
1374
1375 void Decorator::SetHandleImage( HandleType handleType, HandleImageType handleImageType, Dali::Image image )
1376 {
1377   mImpl->mHandleImages[handleType][handleImageType] = image;
1378 }
1379
1380 Dali::Image Decorator::GetHandleImage( HandleType handleType, HandleImageType handleImageType ) const
1381 {
1382   return mImpl->mHandleImages[handleType][handleImageType];
1383 }
1384
1385 void Decorator::SetPosition( HandleType handleType, float x, float y, float height )
1386 {
1387   // Adjust grab handle displacement
1388   Impl::HandleImpl& handle = mImpl->mHandle[handleType];
1389
1390   handle.grabDisplacementX -= x - handle.position.x;
1391   handle.grabDisplacementY -= y - handle.position.y;
1392
1393   handle.position.x = x;
1394   handle.position.y = y;
1395   handle.lineHeight = height;
1396 }
1397
1398 void Decorator::GetPosition( HandleType handleType, float& x, float& y, float& height ) const
1399 {
1400   Impl::HandleImpl& handle = mImpl->mHandle[handleType];
1401
1402   x = handle.position.x;
1403   y = handle.position.y;
1404   height = handle.lineHeight;
1405 }
1406
1407 const Vector2& Decorator::GetPosition( HandleType handleType ) const
1408 {
1409   return mImpl->mHandle[handleType].position;
1410 }
1411
1412 void Decorator::SwapSelectionHandlesEnabled( bool enable )
1413 {
1414   mImpl->mSwapSelectionHandles = enable;
1415
1416   mImpl->FlipSelectionHandleImages();
1417 }
1418
1419 void Decorator::AddHighlight( float x1, float y1, float x2, float y2 )
1420 {
1421   mImpl->mHighlightQuadList.push_back( QuadCoordinates(x1, y1, x2, y2) );
1422 }
1423
1424 void Decorator::ClearHighlights()
1425 {
1426   mImpl->mHighlightQuadList.clear();
1427   mImpl->mHighlightPosition = Vector2::ZERO;
1428 }
1429
1430 void Decorator::SetHighlightColor( const Vector4& color )
1431 {
1432   mImpl->mHighlightColor = color;
1433 }
1434
1435 const Vector4& Decorator::GetHighlightColor() const
1436 {
1437   return mImpl->mHighlightColor;
1438 }
1439
1440 void Decorator::SetPopupActive( bool active )
1441 {
1442   mImpl->mActiveCopyPastePopup = active;
1443 }
1444
1445 bool Decorator::IsPopupActive() const
1446 {
1447   return mImpl->mActiveCopyPastePopup ;
1448 }
1449
1450 void Decorator::SetEnabledPopupButtons( TextSelectionPopup::Buttons& enabledButtonsBitMask )
1451 {
1452    mImpl->mEnabledPopupButtons = enabledButtonsBitMask;
1453 }
1454
1455 TextSelectionPopup::Buttons& Decorator::GetEnabledPopupButtons()
1456 {
1457   return mImpl->mEnabledPopupButtons;
1458 }
1459
1460 /** Scroll **/
1461
1462 void Decorator::SetScrollThreshold( float threshold )
1463 {
1464   mImpl->SetScrollThreshold( threshold );
1465 }
1466
1467 float Decorator::GetScrollThreshold() const
1468 {
1469   return mImpl->GetScrollThreshold();
1470 }
1471
1472 void Decorator::SetScrollSpeed( float speed )
1473 {
1474   mImpl->SetScrollSpeed( speed );
1475 }
1476
1477 float Decorator::GetScrollSpeed() const
1478 {
1479   return mImpl->GetScrollSpeed();
1480 }
1481
1482 Decorator::~Decorator()
1483 {
1484   delete mImpl;
1485 }
1486
1487 Decorator::Decorator( ControllerInterface& controller,
1488                       TextSelectionPopupCallbackInterface& callbackInterface )
1489 : mImpl( NULL )
1490 {
1491   mImpl = new Decorator::Impl( controller, callbackInterface );
1492 }
1493
1494 } // namespace Text
1495
1496 } // namespace Toolkit
1497
1498 } // namespace Dali