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