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