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