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