871b3d6d6df6ee608716002b3a9cd03be8af72c9
[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/actors/mesh-actor.h>
28 #include <dali/public-api/animation/constraint.h>
29 #include <dali/public-api/common/constants.h>
30 #include <dali/public-api/common/stage.h>
31 #include <dali/public-api/events/tap-gesture.h>
32 #include <dali/public-api/events/tap-gesture-detector.h>
33 #include <dali/public-api/events/pan-gesture.h>
34 #include <dali/public-api/events/pan-gesture-detector.h>
35 #include <dali/public-api/geometry/mesh.h>
36 #include <dali/public-api/geometry/mesh-data.h>
37 #include <dali/public-api/images/resource-image.h>
38 #include <dali/public-api/math/rect.h>
39 #include <dali/public-api/math/vector2.h>
40 #include <dali/public-api/math/vector4.h>
41 #include <dali/public-api/object/property-notification.h>
42 #include <dali/public-api/signals/connection-tracker.h>
43
44 // INTERNAL INCLUDES
45 #include <dali-toolkit/public-api/controls/control.h>
46 #include <dali-toolkit/public-api/controls/control-impl.h>
47 #include <dali-toolkit/public-api/controls/buttons/push-button.h>
48 #include <dali-toolkit/public-api/controls/default-controls/solid-color-actor.h>
49 #include <dali-toolkit/public-api/controls/text-controls/text-label.h>
50 #include <dali-toolkit/public-api/controls/text-controls/text-selection-popup.h>
51
52 #ifdef DEBUG_ENABLED
53 #define DECORATOR_DEBUG
54
55 #endif
56
57 namespace Dali
58 {
59 namespace Internal
60 {
61 namespace
62 {
63 #ifdef DECORATOR_DEBUG
64 Integration::Log::Filter* gLogFilter( Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_TEXT_DECORATOR") );
65 #endif
66 }
67 }
68 }
69
70
71 // Local Data
72 namespace
73 {
74
75 const char* DEFAULT_GRAB_HANDLE_IMAGE_RELEASED( DALI_IMAGE_DIR "insertpoint-icon.png" );
76 const char* DEFAULT_GRAB_HANDLE_IMAGE_PRESSED( DALI_IMAGE_DIR "insertpoint-icon-pressed.png" );
77 const char* DEFAULT_SELECTION_HANDLE_ONE( DALI_IMAGE_DIR "text-input-selection-handle-left.png" );
78 const char* DEFAULT_SELECTION_HANDLE_TWO( DALI_IMAGE_DIR "text-input-selection-handle-right.png" );
79
80 const Dali::Vector3 DEFAULT_GRAB_HANDLE_RELATIVE_SIZE( 1.5f, 2.0f, 1.0f );
81 const Dali::Vector3 DEFAULT_SELECTION_HANDLE_RELATIVE_SIZE( 1.5f, 1.5f, 1.0f );
82
83 const Dali::Vector4 LIGHT_BLUE( 0.07f, 0.41f, 0.59f, 1.0f ); // The text highlight color.
84
85 const unsigned int CURSOR_BLINK_INTERVAL = 500u; // Cursor blink interval
86 const float TO_MILLISECONDS = 1000.f;
87 const float TO_SECONDS = 1.f / TO_MILLISECONDS;
88
89 const float DISPLAYED_HIGHLIGHT_Z_OFFSET( -0.05f );
90
91 const unsigned int SCROLL_TICK_INTERVAL = 50u;
92
93 const float SCROLL_THRESHOLD = 10.f;
94 const float SCROLL_SPEED = 300.f;
95 const float SCROLL_DISTANCE = SCROLL_SPEED * SCROLL_TICK_INTERVAL * TO_SECONDS;
96
97 /**
98  * structure to hold coordinates of each quad, which will make up the mesh.
99  */
100 struct QuadCoordinates
101 {
102   /**
103    * Default constructor
104    */
105   QuadCoordinates()
106   {
107   }
108
109   /**
110    * Constructor
111    * @param[in] x1 left co-ordinate
112    * @param[in] y1 top co-ordinate
113    * @param[in] x2 right co-ordinate
114    * @param[in] y2 bottom co-ordinate
115    */
116   QuadCoordinates(float x1, float y1, float x2, float y2)
117   : min(x1, y1),
118     max(x2, y2)
119   {
120   }
121
122   Dali::Vector2 min;                          ///< top-left (minimum) position of quad
123   Dali::Vector2 max;                          ///< bottom-right (maximum) position of quad
124 };
125
126 typedef std::vector<QuadCoordinates> QuadContainer;
127
128 /**
129  * @brief Takes a bounding rectangle in the local coordinates of an actor and returns the world coordinates Bounding Box.
130  * @param[in] boundingRectangle local bounding
131  * @param[out] Vector4 World coordinate bounding Box.
132  */
133 void LocalToWorldCoordinatesBoundingBox( const Dali::Rect<int>& boundingRectangle, Dali::Vector4& boundingBox )
134 {
135   // Convert to world coordinates and store as a Vector4 to be compatible with Property Notifications.
136   Dali::Vector2 stageSize = Dali::Stage::GetCurrent().GetSize();
137
138   const float originX = boundingRectangle.x - 0.5f * stageSize.width;
139   const float originY = boundingRectangle.y - 0.5f * stageSize.height;
140
141   boundingBox = Dali::Vector4( originX,
142                                originY,
143                                originX + boundingRectangle.width,
144                                originY + boundingRectangle.height );
145 }
146
147
148 } // end of namespace
149
150 namespace Dali
151 {
152
153 namespace Toolkit
154 {
155
156 namespace Text
157 {
158
159 struct Decorator::Impl : public ConnectionTracker
160 {
161   enum ScrollDirection
162   {
163     SCROLL_NONE,
164     SCROLL_RIGHT,
165     SCROLL_LEFT,
166     SCROLL_TOP,
167     SCROLL_BOTTOM
168   };
169
170   struct CursorImpl
171   {
172     CursorImpl()
173     : color( Dali::Color::WHITE ),
174       position(),
175       cursorHeight( 0.0f ),
176       lineHeight( 0.0f )
177     {
178     }
179
180     Vector4 color;
181     Vector2 position;
182     float cursorHeight;
183     float lineHeight;
184   };
185
186   struct HandleImpl
187   {
188     HandleImpl()
189     : position(),
190       lineHeight( 0.0f ),
191       grabDisplacementX( 0.f ),
192       grabDisplacementY( 0.f ),
193       active( false ),
194       visible( false ),
195       flipped( false )
196     {
197     }
198
199     ImageActor actor;
200     Actor grabArea;
201
202     Vector2 position;
203     float lineHeight; ///< Not the handle height
204     float grabDisplacementX;
205     float grabDisplacementY;
206     bool active  : 1;
207     bool visible : 1;
208     bool flipped : 1;
209   };
210
211   Impl( Dali::Toolkit::Internal::Control& parent, Observer& observer )
212   : mTextControlParent( parent ),
213     mObserver( observer ),
214     mBoundingBox( Rect<int>() ),
215     mHighlightColor( LIGHT_BLUE ),
216     mActiveCursor( ACTIVE_CURSOR_NONE ),
217     mCursorBlinkInterval( CURSOR_BLINK_INTERVAL ),
218     mCursorBlinkDuration( 0.0f ),
219     mHandleScrolling( HANDLE_TYPE_COUNT ),
220     mScrollDirection( SCROLL_NONE ),
221     mScrollThreshold( SCROLL_THRESHOLD ),
222     mScrollSpeed( SCROLL_SPEED ),
223     mScrollDistance( SCROLL_DISTANCE ),
224     mActiveCopyPastePopup( false ),
225     mCursorBlinkStatus( true ),
226     mPrimaryCursorVisible( false ),
227     mSecondaryCursorVisible( false )
228   {
229   }
230
231   /**
232    * Relayout of the decorations owned by the decorator.
233    * @param[in] size The Size of the UI control the decorator is adding it's decorations to.
234    */
235   void Relayout( const Vector2& size )
236   {
237     // TODO - Remove this if nothing is active
238     CreateActiveLayer();
239
240     // Show or hide the cursors
241     CreateCursors();
242     if( mPrimaryCursor )
243     {
244       const CursorImpl& cursor = mCursor[PRIMARY_CURSOR];
245       mPrimaryCursorVisible = ( cursor.position.x <= size.width ) && ( cursor.position.x >= 0.f );
246       if( mPrimaryCursorVisible )
247       {
248         Vector2 position = cursor.position;
249         if( GRAB_HANDLE == mHandleScrolling )
250         {
251           if( mScrollDirection == SCROLL_RIGHT )
252           {
253             position.x = 0.f;
254           }
255           else
256           {
257             position.x = size.width;
258           }
259         }
260
261         mPrimaryCursor.SetPosition( position.x,
262                                     position.y );
263         mPrimaryCursor.SetSize( Size( 1.0f, cursor.cursorHeight ) );
264       }
265       mPrimaryCursor.SetVisible( mPrimaryCursorVisible );
266     }
267     if( mSecondaryCursor )
268     {
269       const CursorImpl& cursor = mCursor[SECONDARY_CURSOR];
270       mSecondaryCursorVisible = ( cursor.position.x <= size.width ) && ( cursor.position.x >= 0.f );
271       if( mSecondaryCursorVisible )
272       {
273         mSecondaryCursor.SetPosition( cursor.position.x,
274                                       cursor.position.y );
275         mSecondaryCursor.SetSize( Size( 1.0f, cursor.cursorHeight ) );
276       }
277       mSecondaryCursor.SetVisible( mSecondaryCursorVisible );
278     }
279
280     // Show or hide the grab handle
281     HandleImpl& grabHandle = mHandle[GRAB_HANDLE];
282     if( grabHandle.active )
283     {
284       Vector2 position = grabHandle.position;
285
286       if( GRAB_HANDLE == mHandleScrolling )
287       {
288         if( mScrollDirection == SCROLL_RIGHT )
289         {
290           position.x = 0.f;
291         }
292         else
293         {
294           position.x = size.width;
295         }
296       }
297
298       const bool isVisible = ( position.x <= size.width ) && ( position.x >= 0.f );
299
300       if( isVisible )
301       {
302         SetupTouchEvents();
303
304         CreateGrabHandle();
305
306         grabHandle.actor.SetPosition( position.x,
307                                       position.y + grabHandle.lineHeight );
308       }
309       grabHandle.actor.SetVisible( isVisible );
310     }
311     else if( grabHandle.actor )
312     {
313       UnparentAndReset( grabHandle.actor );
314     }
315
316     // Show or hide the selection handles/highlight
317     HandleImpl& primary = mHandle[ LEFT_SELECTION_HANDLE ];
318     HandleImpl& secondary = mHandle[ RIGHT_SELECTION_HANDLE ];
319     if( primary.active || secondary.active )
320     {
321       SetupTouchEvents();
322
323       CreateSelectionHandles();
324
325       primary.actor.SetPosition( primary.position.x,
326                                  primary.position.y + primary.lineHeight );
327
328       secondary.actor.SetPosition( secondary.position.x,
329                                    secondary.position.y + secondary.lineHeight );
330
331       CreateHighlight();
332       UpdateHighlight();
333     }
334     else
335     {
336       UnparentAndReset( primary.actor );
337       UnparentAndReset( secondary.actor );
338       UnparentAndReset( mHighlightMeshActor );
339     }
340
341     if ( mActiveCopyPastePopup )
342     {
343       if ( !mCopyPastePopup )
344       {
345         mCopyPastePopup = TextSelectionPopup::New();
346 #ifdef DECORATOR_DEBUG
347         mCopyPastePopup.SetName("mCopyPastePopup");
348 #endif
349         mCopyPastePopup.SetAnchorPoint( AnchorPoint::CENTER );
350         mCopyPastePopup.OnRelayoutSignal().Connect( this,  &Decorator::Impl::PopUpRelayoutComplete  ); // Position popup after size negotiation
351         mActiveLayer.Add ( mCopyPastePopup );
352       }
353     }
354     else
355     {
356      if ( mCopyPastePopup )
357      {
358        UnparentAndReset( mCopyPastePopup );
359      }
360     }
361   }
362
363   void UpdatePositions( const Vector2& scrollOffset )
364   {
365     mCursor[PRIMARY_CURSOR].position += scrollOffset;
366     mCursor[SECONDARY_CURSOR].position += scrollOffset;
367     mHandle[ GRAB_HANDLE ].position += scrollOffset;
368     mHandle[ LEFT_SELECTION_HANDLE ].position += scrollOffset;
369     mHandle[ RIGHT_SELECTION_HANDLE ].position += scrollOffset;
370
371     // TODO Highlight box??
372   }
373
374   void PopUpRelayoutComplete( Actor actor )
375   {
376     // Size negotiation for CopyPastePopup complete so can get the size and constrain position within bounding box.
377
378     mCopyPastePopup.OnRelayoutSignal().Disconnect( this, &Decorator::Impl::PopUpRelayoutComplete  );
379
380     Vector3 popupPosition( mCursor[PRIMARY_CURSOR].position.x, mCursor[PRIMARY_CURSOR].position.y -100.0f , 0.0f); //todo 100 to be an offset Property
381
382     Vector3 popupSize = Vector3( mCopyPastePopup.GetRelayoutSize( Dimension::WIDTH ), mCopyPastePopup.GetRelayoutSize( Dimension::HEIGHT ), 0.0f );
383
384     GetConstrainedPopupPosition( popupPosition, popupSize, AnchorPoint::CENTER, mActiveLayer, mBoundingBox );
385
386     SetUpPopUpPositionNotifications();
387
388     mCopyPastePopup.SetPosition( popupPosition ); //todo grabhandle(cursor) or selection handle positions to be used
389   }
390
391   void CreateCursor( ImageActor& cursor, const Vector4& color )
392   {
393     cursor = CreateSolidColorActor( color );
394     cursor.SetParentOrigin( ParentOrigin::TOP_LEFT ); // Need to set the default parent origin as CreateSolidColorActor() sets a different one.
395     cursor.SetAnchorPoint( AnchorPoint::TOP_CENTER );
396   }
397
398   // Add or Remove cursor(s) from parent
399   void CreateCursors()
400   {
401     if( mActiveCursor == ACTIVE_CURSOR_NONE )
402     {
403       UnparentAndReset( mPrimaryCursor );
404       UnparentAndReset( mSecondaryCursor );
405     }
406     else
407     {
408       /* Create Primary and or Secondary Cursor(s) if active and add to parent */
409       if ( mActiveCursor == ACTIVE_CURSOR_PRIMARY ||
410            mActiveCursor == ACTIVE_CURSOR_BOTH )
411       {
412         if ( !mPrimaryCursor )
413         {
414           CreateCursor( mPrimaryCursor, mCursor[PRIMARY_CURSOR].color );
415 #ifdef DECORATOR_DEBUG
416           mPrimaryCursor.SetName( "PrimaryCursorActor" );
417 #endif
418           mActiveLayer.Add( mPrimaryCursor );
419         }
420       }
421
422       if ( mActiveCursor == ACTIVE_CURSOR_BOTH )
423       {
424         if ( !mSecondaryCursor )
425         {
426           CreateCursor( mSecondaryCursor, mCursor[SECONDARY_CURSOR].color );
427 #ifdef DECORATOR_DEBUG
428           mSecondaryCursor.SetName( "SecondaryCursorActor" );
429 #endif
430           mActiveLayer.Add( mSecondaryCursor );
431         }
432       }
433       else
434       {
435         UnparentAndReset( mSecondaryCursor );
436       }
437     }
438   }
439
440   bool OnCursorBlinkTimerTick()
441   {
442     // Cursor blinking
443     if ( mPrimaryCursor )
444     {
445       mPrimaryCursor.SetVisible( mPrimaryCursorVisible && mCursorBlinkStatus );
446     }
447     if ( mSecondaryCursor )
448     {
449       mSecondaryCursor.SetVisible( mSecondaryCursorVisible && mCursorBlinkStatus );
450     }
451
452     mCursorBlinkStatus = !mCursorBlinkStatus;
453
454     return true;
455   }
456
457   void SetupTouchEvents()
458   {
459     if ( !mTapDetector )
460     {
461       mTapDetector = TapGestureDetector::New();
462       mTapDetector.DetectedSignal().Connect( this, &Decorator::Impl::OnTap );
463     }
464
465     if ( !mPanGestureDetector )
466     {
467       mPanGestureDetector = PanGestureDetector::New();
468       mPanGestureDetector.DetectedSignal().Connect( this, &Decorator::Impl::OnPan );
469     }
470   }
471
472   void CreateActiveLayer()
473   {
474     if( !mActiveLayer )
475     {
476       Actor parent = mTextControlParent.Self();
477
478       mActiveLayer = Layer::New();
479 #ifdef DECORATOR_DEBUG
480       mActiveLayer.SetName ( "ActiveLayerActor" );
481 #endif
482
483       mActiveLayer.SetParentOrigin( ParentOrigin::CENTER );
484       mActiveLayer.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS );
485       mActiveLayer.SetPositionInheritanceMode( USE_PARENT_POSITION );
486
487       parent.Add( mActiveLayer );
488     }
489
490     mActiveLayer.RaiseToTop();
491   }
492
493   void CreateGrabHandle()
494   {
495     HandleImpl& grabHandle = mHandle[GRAB_HANDLE];
496     if( !grabHandle.actor )
497     {
498       if( !mHandleImages[GRAB_HANDLE][HANDLE_IMAGE_RELEASED] )
499       {
500         mHandleImages[GRAB_HANDLE][HANDLE_IMAGE_RELEASED] = ResourceImage::New( DEFAULT_GRAB_HANDLE_IMAGE_RELEASED );
501       }
502       if( !mHandleImages[GRAB_HANDLE][HANDLE_IMAGE_PRESSED] )
503       {
504         mHandleImages[GRAB_HANDLE][HANDLE_IMAGE_PRESSED] = ResourceImage::New( DEFAULT_GRAB_HANDLE_IMAGE_PRESSED );
505       }
506
507       grabHandle.actor = ImageActor::New( mHandleImages[GRAB_HANDLE][HANDLE_IMAGE_RELEASED] );
508       grabHandle.actor.SetAnchorPoint( AnchorPoint::TOP_CENTER );
509       grabHandle.actor.SetDrawMode( DrawMode::OVERLAY );
510       // Area that Grab handle responds to, larger than actual handle so easier to move
511 #ifdef DECORATOR_DEBUG
512       grabHandle.actor.SetName( "GrabHandleActor" );
513       if ( Dali::Internal::gLogFilter->IsEnabledFor( Debug::Verbose ) )
514       {
515         grabHandle.grabArea = Toolkit::CreateSolidColorActor( Vector4(0.0f, 0.0f, 0.0f, 0.0f), true, Color::RED, 1 );
516         grabHandle.grabArea.SetName( "GrabArea" );
517       }
518       else
519       {
520         grabHandle.grabArea = Actor::New();
521         grabHandle.grabArea.SetName( "GrabArea" );
522       }
523 #else
524       grabHandle.grabArea = Actor::New();
525 #endif
526
527       grabHandle.grabArea.SetParentOrigin( ParentOrigin::TOP_CENTER );
528       grabHandle.grabArea.SetAnchorPoint( AnchorPoint::TOP_CENTER );
529       grabHandle.grabArea.SetResizePolicy( ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::ALL_DIMENSIONS );
530       grabHandle.grabArea.SetSizeModeFactor( DEFAULT_GRAB_HANDLE_RELATIVE_SIZE );
531       grabHandle.actor.Add( grabHandle.grabArea );
532
533       mTapDetector.Attach( grabHandle.grabArea );
534       mPanGestureDetector.Attach( grabHandle.grabArea );
535
536       mActiveLayer.Add( grabHandle.actor );
537     }
538   }
539
540   void CreateSelectionHandles()
541   {
542     HandleImpl& primary = mHandle[ LEFT_SELECTION_HANDLE ];
543     if( !primary.actor )
544     {
545       if( !mHandleImages[LEFT_SELECTION_HANDLE][HANDLE_IMAGE_RELEASED] )
546       {
547         mHandleImages[LEFT_SELECTION_HANDLE][HANDLE_IMAGE_RELEASED] = ResourceImage::New( DEFAULT_SELECTION_HANDLE_ONE );
548       }
549
550       primary.actor = ImageActor::New( mHandleImages[LEFT_SELECTION_HANDLE][HANDLE_IMAGE_RELEASED] );
551 #ifdef DECORATOR_DEBUG
552       primary.actor.SetName("SelectionHandleOne");
553 #endif
554       primary.actor.SetAnchorPoint( AnchorPoint::TOP_RIGHT ); // Change to BOTTOM_RIGHT if Look'n'Feel requires handle above text.
555       primary.actor.SetDrawMode( DrawMode::OVERLAY ); // ensure grab handle above text
556       primary.flipped = false;
557
558       primary.grabArea = Actor::New(); // Area that Grab handle responds to, larger than actual handle so easier to move
559 #ifdef DECORATOR_DEBUG
560       primary.grabArea.SetName("SelectionHandleOneGrabArea");
561 #endif
562       primary.grabArea.SetResizePolicy( ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::ALL_DIMENSIONS );
563       primary.grabArea.SetSizeModeFactor( DEFAULT_SELECTION_HANDLE_RELATIVE_SIZE );
564       primary.grabArea.SetPositionInheritanceMode( Dali::USE_PARENT_POSITION );
565
566       mTapDetector.Attach( primary.grabArea );
567       mPanGestureDetector.Attach( primary.grabArea );
568       primary.grabArea.TouchedSignal().Connect( this, &Decorator::Impl::OnHandleOneTouched );
569
570       primary.actor.Add( primary.grabArea );
571       mActiveLayer.Add( primary.actor );
572     }
573
574     HandleImpl& secondary = mHandle[ RIGHT_SELECTION_HANDLE ];
575     if( !secondary.actor )
576     {
577       if( !mHandleImages[RIGHT_SELECTION_HANDLE][HANDLE_IMAGE_RELEASED] )
578       {
579         mHandleImages[RIGHT_SELECTION_HANDLE][HANDLE_IMAGE_RELEASED] = ResourceImage::New( DEFAULT_SELECTION_HANDLE_TWO );
580       }
581
582       secondary.actor = ImageActor::New( mHandleImages[RIGHT_SELECTION_HANDLE][HANDLE_IMAGE_RELEASED] );
583 #ifdef DECORATOR_DEBUG
584       secondary.actor.SetName("SelectionHandleTwo");
585 #endif
586       secondary.actor.SetAnchorPoint( AnchorPoint::TOP_LEFT ); // Change to BOTTOM_LEFT if Look'n'Feel requires handle above text.
587       secondary.actor.SetDrawMode( DrawMode::OVERLAY ); // ensure grab handle above text
588       secondary.flipped = false;
589
590       secondary.grabArea = Actor::New(); // Area that Grab handle responds to, larger than actual handle so easier to move
591 #ifdef DECORATOR_DEBUG
592       secondary.grabArea.SetName("SelectionHandleTwoGrabArea");
593 #endif
594       secondary.grabArea.SetResizePolicy( ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::ALL_DIMENSIONS );
595       secondary.grabArea.SetSizeModeFactor( DEFAULT_SELECTION_HANDLE_RELATIVE_SIZE );
596       secondary.grabArea.SetPositionInheritanceMode( Dali::USE_PARENT_POSITION );
597
598       mTapDetector.Attach( secondary.grabArea );
599       mPanGestureDetector.Attach( secondary.grabArea );
600       secondary.grabArea.TouchedSignal().Connect( this, &Decorator::Impl::OnHandleTwoTouched );
601
602       secondary.actor.Add( secondary.grabArea );
603       mActiveLayer.Add( secondary.actor );
604     }
605   }
606
607   void CreateHighlight()
608   {
609     if ( !mHighlightMeshActor )
610     {
611       mHighlightMaterial = Material::New( "HighlightMaterial" );
612       mHighlightMaterial.SetDiffuseColor( mHighlightColor );
613
614       mHighlightMeshData.SetMaterial( mHighlightMaterial );
615       mHighlightMeshData.SetHasNormals( true );
616
617       mHighlightMesh = Mesh::New( mHighlightMeshData );
618
619       mHighlightMeshActor = MeshActor::New( mHighlightMesh );
620 #ifdef DECORATOR_DEBUG
621       mHighlightMeshActor.SetName( "HighlightMeshActor" );
622 #endif
623       mHighlightMeshActor.SetAnchorPoint( AnchorPoint::TOP_LEFT );
624       mHighlightMeshActor.SetPosition( 0.0f, 0.0f, DISPLAYED_HIGHLIGHT_Z_OFFSET );
625
626       Actor parent = mTextControlParent.Self();
627       parent.Add( mHighlightMeshActor );
628     }
629   }
630
631   void UpdateHighlight()
632   {
633     //  Construct a Mesh with a texture to be used as the highlight 'box' for selected text
634     //
635     //  Example scenarios where mesh is made from 3, 1, 2, 2 ,3 or 3 quads.
636     //
637     //   [ TOP   ]  [ TOP ]      [TOP ]  [ TOP    ]      [ TOP  ]      [ TOP  ]
638     //  [ MIDDLE ]             [BOTTOM]  [BOTTOM]      [ MIDDLE ]   [ MIDDLE  ]
639     //  [ BOTTOM]                                      [ MIDDLE ]   [ MIDDLE  ]
640     //                                                 [BOTTOM]     [ MIDDLE  ]
641     //                                                              [BOTTOM]
642     //
643     //  Each quad is created as 2 triangles.
644     //  Middle is just 1 quad regardless of its size.
645     //
646     //  (0,0)         (0,0)
647     //     0*    *2     0*       *2
648     //     TOP          TOP
649     //     3*    *1     3*       *1
650     //  4*       *1     4*     *6
651     //     MIDDLE         BOTTOM
652     //  6*       *5     7*     *5
653     //  6*    *8
654     //   BOTTOM
655     //  9*    *7
656     //
657
658     if ( mHighlightMesh && mHighlightMaterial && !mHighlightQuadList.empty() )
659     {
660       MeshData::VertexContainer vertices;
661       Dali::MeshData::FaceIndices faceIndices;
662
663       std::vector<QuadCoordinates>::iterator iter = mHighlightQuadList.begin();
664       std::vector<QuadCoordinates>::iterator endIter = mHighlightQuadList.end();
665
666       // vertex position defaults to (0 0 0)
667       MeshData::Vertex vertex;
668       // set normal for all vertices as (0 0 1) pointing outward from TextInput Actor.
669       vertex.nZ = 1.0f;
670
671       for(std::size_t v = 0; iter != endIter; ++iter,v+=4 )
672       {
673         // Add each quad geometry (a sub-selection) to the mesh data.
674
675         // 0-----1
676         // |\    |
677         // | \ A |
678         // |  \  |
679         // | B \ |
680         // |    \|
681         // 2-----3
682
683         QuadCoordinates& quad = *iter;
684         // top-left (v+0)
685         vertex.x = quad.min.x;
686         vertex.y = quad.min.y;
687         vertices.push_back( vertex );
688
689         // top-right (v+1)
690         vertex.x = quad.max.x;
691         vertex.y = quad.min.y;
692         vertices.push_back( vertex );
693
694         // bottom-left (v+2)
695         vertex.x = quad.min.x;
696         vertex.y = quad.max.y;
697         vertices.push_back( vertex );
698
699         // bottom-right (v+3)
700         vertex.x = quad.max.x;
701         vertex.y = quad.max.y;
702         vertices.push_back( vertex );
703
704         // triangle A (3, 1, 0)
705         faceIndices.push_back( v + 3 );
706         faceIndices.push_back( v + 1 );
707         faceIndices.push_back( v );
708
709         // triangle B (0, 2, 3)
710         faceIndices.push_back( v );
711         faceIndices.push_back( v + 2 );
712         faceIndices.push_back( v + 3 );
713
714         mHighlightMeshData.SetFaceIndices( faceIndices );
715       }
716
717       BoneContainer bones(0); // passed empty as bones not required
718       mHighlightMeshData.SetData( vertices, faceIndices, bones, mHighlightMaterial );
719       mHighlightMesh.UpdateMeshData( mHighlightMeshData );
720     }
721   }
722
723   void OnTap( Actor actor, const TapGesture& tap )
724   {
725     if( actor == mHandle[GRAB_HANDLE].actor )
726     {
727       // TODO
728     }
729   }
730
731   void DoPan( HandleImpl& handle, HandleType type, const PanGesture& gesture )
732   {
733     if( Gesture::Started == gesture.state )
734     {
735       handle.grabDisplacementX = handle.grabDisplacementY = 0;
736       if( mHandleImages[type][HANDLE_IMAGE_PRESSED] )
737       {
738         handle.actor.SetImage( mHandleImages[type][HANDLE_IMAGE_PRESSED] );
739       }
740     }
741
742     handle.grabDisplacementX += gesture.displacement.x;
743     handle.grabDisplacementY += gesture.displacement.y;
744
745     const float x = handle.position.x + handle.grabDisplacementX;
746     const float y = handle.position.y + handle.lineHeight*0.5f + handle.grabDisplacementY;
747
748     if( Gesture::Started    == gesture.state ||
749         Gesture::Continuing == gesture.state )
750     {
751       if( x < mScrollThreshold )
752       {
753         mScrollDirection = SCROLL_RIGHT;
754         mHandleScrolling = type;
755         StartScrollTimer();
756       }
757       else if( x > mTextControlParent.GetControlSize().width - mScrollThreshold )
758       {
759         mScrollDirection = SCROLL_LEFT;
760         mHandleScrolling = type;
761         StartScrollTimer();
762       }
763       else
764       {
765         mHandleScrolling = HANDLE_TYPE_COUNT;
766         StopScrollTimer();
767         mObserver.HandleEvent( type, HANDLE_PRESSED, x, y );
768       }
769     }
770     else if( Gesture::Finished  == gesture.state ||
771              Gesture::Cancelled == gesture.state )
772     {
773       if( mScrollTimer && mScrollTimer.IsRunning() )
774       {
775         mHandleScrolling = HANDLE_TYPE_COUNT;
776         StopScrollTimer();
777         mObserver.HandleEvent( type, HANDLE_STOP_SCROLLING, x, y );
778       }
779       else
780       {
781         mObserver.HandleEvent( type, HANDLE_RELEASED, x, y );
782       }
783       handle.actor.SetImage( mHandleImages[type][HANDLE_IMAGE_RELEASED] );
784     }
785   }
786
787   void OnPan( Actor actor, const PanGesture& gesture )
788   {
789     HandleImpl& grabHandle = mHandle[GRAB_HANDLE];
790     HandleImpl& primarySelectionHandle = mHandle[LEFT_SELECTION_HANDLE];
791     HandleImpl& secondarySelectionHandle = mHandle[RIGHT_SELECTION_HANDLE];
792
793     if( actor == grabHandle.grabArea )
794     {
795       DoPan( grabHandle, GRAB_HANDLE, gesture );
796     }
797     else if( actor == primarySelectionHandle.grabArea )
798     {
799       DoPan( primarySelectionHandle, LEFT_SELECTION_HANDLE, gesture );
800     }
801     else if( actor == secondarySelectionHandle.grabArea )
802     {
803       DoPan( secondarySelectionHandle, RIGHT_SELECTION_HANDLE, gesture );
804     }
805   }
806
807   bool OnHandleOneTouched( Actor actor, const TouchEvent& touch )
808   {
809     // TODO
810     return false;
811   }
812
813   bool OnHandleTwoTouched( Actor actor, const TouchEvent& touch )
814   {
815     // TODO
816     return false;
817   }
818
819   // Popup
820
821   float AlternatePopUpPositionRelativeToCursor()
822   {
823     float alternativePosition=0.0f;;
824
825     if ( mPrimaryCursor ) // Secondary cursor not used for paste
826     {
827       Cursor cursor = PRIMARY_CURSOR;
828       alternativePosition = mCursor[cursor].position.y;
829     }
830
831     const float popupHeight = 120.0f; // todo Set as a MaxSize Property in Control or retrieve from CopyPastePopup class.
832
833     if( mHandle[GRAB_HANDLE].active )
834     {
835       // If grab handle enabled then position pop-up below the grab handle.
836       const Vector2 grabHandleSize( 59.0f, 56.0f ); // todo
837       const float BOTTOM_HANDLE_BOTTOM_OFFSET = 1.5; //todo Should be a property
838       alternativePosition +=  grabHandleSize.height  + popupHeight + BOTTOM_HANDLE_BOTTOM_OFFSET ;
839     }
840     else
841     {
842       alternativePosition += popupHeight;
843     }
844
845     return alternativePosition;
846   }
847
848   void PopUpLeavesVerticalBoundary( PropertyNotification& source )
849   {
850     float alternativeYPosition=0.0f;
851     // todo use AlternatePopUpPositionRelativeToSelectionHandles() if text is highlighted
852     // if can't be positioned above, then position below row.
853     alternativeYPosition = AlternatePopUpPositionRelativeToCursor();
854
855     mCopyPastePopup.SetY( alternativeYPosition );
856   }
857
858
859   void SetUpPopUpPositionNotifications( )
860   {
861     // Note Property notifications ignore any set anchor point so conditions must allow for this.  Default is Top Left.
862
863     // Exceeding vertical boundary
864
865     Vector4 worldCoordinatesBoundingBox;
866     LocalToWorldCoordinatesBoundingBox( mBoundingBox, worldCoordinatesBoundingBox );
867
868     float popupHeight = mCopyPastePopup.GetRelayoutSize( Dimension::HEIGHT);
869
870     PropertyNotification verticalExceedNotification = mCopyPastePopup.AddPropertyNotification( Actor::Property::WORLD_POSITION_Y,
871                                                       OutsideCondition( worldCoordinatesBoundingBox.y + popupHeight/2,
872                                                                         worldCoordinatesBoundingBox.w - popupHeight/2 ) );
873
874     verticalExceedNotification.NotifySignal().Connect( this, &Decorator::Impl::PopUpLeavesVerticalBoundary );
875   }
876
877   void GetConstrainedPopupPosition( Vector3& requiredPopupPosition, Vector3& popupSize, Vector3 anchorPoint, Actor& parent, Rect<int>& boundingBox )
878   {
879     DALI_ASSERT_DEBUG ( "Popup parent not on stage" && parent.OnStage() )
880
881     // Parent must already by added to Stage for these Get calls to work
882     Vector3 parentAnchorPoint = parent.GetCurrentAnchorPoint();
883     Vector3 parentWorldPositionLeftAnchor = parent.GetCurrentWorldPosition() - parent.GetCurrentSize()*parentAnchorPoint;
884     Vector3 popupWorldPosition = parentWorldPositionLeftAnchor + requiredPopupPosition;  // Parent World position plus popup local position gives World Position
885     Vector3 popupDistanceFromAnchorPoint = popupSize*anchorPoint;
886
887     // Bounding rectangle is supplied as screen coordinates, bounding will be done in world coordinates.
888     Vector4 boundingRectangleWorld;
889     LocalToWorldCoordinatesBoundingBox( boundingBox, boundingRectangleWorld );
890
891     // Calculate distance to move popup (in local space) so fits within the boundary
892     float xOffSetToKeepWithinBounds = 0.0f;
893     if( popupWorldPosition.x - popupDistanceFromAnchorPoint.x < boundingRectangleWorld.x )
894     {
895       xOffSetToKeepWithinBounds = boundingRectangleWorld.x - ( popupWorldPosition.x - popupDistanceFromAnchorPoint.x );
896     }
897     else if ( popupWorldPosition.x +  popupDistanceFromAnchorPoint.x > boundingRectangleWorld.z )
898     {
899       xOffSetToKeepWithinBounds = boundingRectangleWorld.z - ( popupWorldPosition.x +  popupDistanceFromAnchorPoint.x );
900     }
901
902     // Ensure initial display of Popup is in alternative position if can not fit above. As Property notification will be a frame behind.
903     if ( popupWorldPosition.y - popupDistanceFromAnchorPoint.y < boundingRectangleWorld.y )
904     {
905       requiredPopupPosition.y = AlternatePopUpPositionRelativeToCursor();
906     }
907
908     requiredPopupPosition.x = requiredPopupPosition.x + xOffSetToKeepWithinBounds;
909   }
910
911   void SetScrollThreshold( float threshold )
912   {
913     mScrollThreshold = threshold;
914   }
915
916   float GetScrollThreshold() const
917   {
918     return mScrollThreshold;
919   }
920
921   void SetScrollSpeed( float speed )
922   {
923     mScrollSpeed = speed;
924     mScrollDistance = speed * SCROLL_TICK_INTERVAL * TO_SECONDS;
925   }
926
927   float GetScrollSpeed() const
928   {
929     return mScrollSpeed;
930   }
931
932   /**
933    * Creates and starts a timer to scroll the text when handles are close to the edges of the text.
934    *
935    * It only starts the timer if it's already created.
936    */
937   void StartScrollTimer()
938   {
939     if( !mScrollTimer )
940     {
941       mScrollTimer = Timer::New( SCROLL_TICK_INTERVAL );
942       mScrollTimer.TickSignal().Connect( this, &Decorator::Impl::OnScrollTimerTick );
943     }
944
945     if( !mScrollTimer.IsRunning() )
946     {
947       mScrollTimer.Start();
948     }
949   }
950
951   /**
952    * Stops the timer used to scroll the text.
953    */
954   void StopScrollTimer()
955   {
956     if( mScrollTimer )
957     {
958       mScrollTimer.Stop();
959     }
960   }
961
962   /**
963    * Callback called by the timer used to scroll the text.
964    *
965    * It calculates and sets a new scroll position.
966    */
967   bool OnScrollTimerTick()
968   {
969     if( HANDLE_TYPE_COUNT != mHandleScrolling )
970     {
971       mObserver.HandleEvent( mHandleScrolling,
972                              HANDLE_SCROLLING,
973                              mScrollDirection == SCROLL_RIGHT ? mScrollDistance : -mScrollDistance,
974                              0.f );
975     }
976
977     return true;
978   }
979
980   Internal::Control&  mTextControlParent;
981   Observer&           mObserver;
982
983   TapGestureDetector  mTapDetector;
984   PanGestureDetector  mPanGestureDetector;
985   Timer               mCursorBlinkTimer;          ///< Timer to signal cursor to blink
986   Timer               mScrollTimer;               ///< Timer used to scroll the text when the grab handle is moved close to the edges.
987
988   Layer               mActiveLayer;               ///< Layer for active handles and alike that ensures they are above all else.
989   ImageActor          mPrimaryCursor;
990   ImageActor          mSecondaryCursor;
991   MeshActor           mHighlightMeshActor;        ///< Mesh Actor to display highlight
992   TextSelectionPopup  mCopyPastePopup;
993
994   Image               mHandleImages[HANDLE_TYPE_COUNT][HANDLE_IMAGE_TYPE_COUNT];
995   Image               mCursorImage;
996   Mesh                mHighlightMesh;             ///< Mesh for highlight
997   MeshData            mHighlightMeshData;         ///< Mesh Data for highlight
998   Material            mHighlightMaterial;         ///< Material used for highlight
999
1000   CursorImpl          mCursor[CURSOR_COUNT];
1001   HandleImpl          mHandle[HANDLE_TYPE_COUNT];
1002   QuadContainer       mHighlightQuadList;         ///< Sub-selections that combine to create the complete selection highlight
1003
1004   Rect<int>           mBoundingBox;
1005   Vector4             mHighlightColor;            ///< Color of the highlight
1006
1007   unsigned int        mActiveCursor;
1008   unsigned int        mCursorBlinkInterval;
1009   float               mCursorBlinkDuration;
1010   HandleType          mHandleScrolling;         ///< The handle which is scrolling.
1011   ScrollDirection     mScrollDirection;         ///< The direction of the scroll.
1012   float               mScrollThreshold;         ///< Defines a square area inside the control, close to the edge. A cursor entering this area will trigger scroll events.
1013   float               mScrollSpeed;             ///< The scroll speed in pixels per second.
1014   float               mScrollDistance;          ///< Distance the text scrolls during a scroll interval.
1015   unsigned int        mScrollInterval;          ///< Time in milliseconds of a scroll interval.
1016
1017   bool                mActiveCopyPastePopup   : 1;
1018   bool                mCursorBlinkStatus      : 1; ///< Flag to switch between blink on and blink off.
1019   bool                mPrimaryCursorVisible   : 1; ///< Whether the primary cursor is visible.
1020   bool                mSecondaryCursorVisible : 1; ///< Whether the secondary cursor is visible.
1021 };
1022
1023 DecoratorPtr Decorator::New( Internal::Control& parent, Observer& observer )
1024 {
1025   return DecoratorPtr( new Decorator(parent, observer) );
1026 }
1027
1028 void Decorator::SetBoundingBox( const Rect<int>& boundingBox )
1029 {
1030   mImpl->mBoundingBox = boundingBox;
1031 }
1032
1033 const Rect<int>& Decorator::GetBoundingBox() const
1034 {
1035   return mImpl->mBoundingBox;
1036 }
1037
1038 void Decorator::Relayout( const Vector2& size )
1039 {
1040   mImpl->Relayout( size );
1041 }
1042
1043 void Decorator::UpdatePositions( const Vector2& scrollOffset )
1044 {
1045   mImpl->UpdatePositions( scrollOffset );
1046 }
1047
1048 /** Cursor **/
1049
1050 void Decorator::SetActiveCursor( ActiveCursor activeCursor )
1051 {
1052   mImpl->mActiveCursor = activeCursor;
1053 }
1054
1055 unsigned int Decorator::GetActiveCursor() const
1056 {
1057   return mImpl->mActiveCursor;
1058 }
1059
1060 void Decorator::SetPosition( Cursor cursor, float x, float y, float cursorHeight, float lineHeight )
1061 {
1062   mImpl->mCursor[cursor].position.x = x;
1063   mImpl->mCursor[cursor].position.y = y;
1064   mImpl->mCursor[cursor].cursorHeight = cursorHeight;
1065   mImpl->mCursor[cursor].lineHeight = lineHeight;
1066 }
1067
1068 void Decorator::GetPosition( Cursor cursor, float& x, float& y, float& cursorHeight, float& lineHeight ) const
1069 {
1070   x = mImpl->mCursor[cursor].position.x;
1071   y = mImpl->mCursor[cursor].position.y;
1072   cursorHeight = mImpl->mCursor[cursor].cursorHeight;
1073   lineHeight = mImpl->mCursor[cursor].lineHeight;
1074 }
1075
1076 const Vector2& Decorator::GetPosition( Cursor cursor ) const
1077 {
1078   return mImpl->mCursor[cursor].position;
1079 }
1080
1081 void Decorator::SetColor( Cursor cursor, const Dali::Vector4& color )
1082 {
1083   mImpl->mCursor[cursor].color = color;
1084 }
1085
1086 const Dali::Vector4& Decorator::GetColor( Cursor cursor ) const
1087 {
1088   return mImpl->mCursor[cursor].color;
1089 }
1090
1091 void Decorator::StartCursorBlink()
1092 {
1093   if ( !mImpl->mCursorBlinkTimer )
1094   {
1095     mImpl->mCursorBlinkTimer = Timer::New( mImpl->mCursorBlinkInterval );
1096     mImpl->mCursorBlinkTimer.TickSignal().Connect( mImpl, &Decorator::Impl::OnCursorBlinkTimerTick );
1097   }
1098
1099   if ( !mImpl->mCursorBlinkTimer.IsRunning() )
1100   {
1101     mImpl->mCursorBlinkTimer.Start();
1102   }
1103 }
1104
1105 void Decorator::StopCursorBlink()
1106 {
1107   if ( mImpl->mCursorBlinkTimer )
1108   {
1109     mImpl->mCursorBlinkTimer.Stop();
1110   }
1111 }
1112
1113 void Decorator::SetCursorBlinkInterval( float seconds )
1114 {
1115   mImpl->mCursorBlinkInterval = static_cast<unsigned int>( seconds * TO_MILLISECONDS ); // Convert to milliseconds
1116 }
1117
1118 float Decorator::GetCursorBlinkInterval() const
1119 {
1120   return static_cast<float>( mImpl->mCursorBlinkInterval ) * TO_SECONDS;
1121 }
1122
1123 void Decorator::SetCursorBlinkDuration( float seconds )
1124 {
1125   mImpl->mCursorBlinkDuration = seconds;
1126 }
1127
1128 float Decorator::GetCursorBlinkDuration() const
1129 {
1130   return mImpl->mCursorBlinkDuration;
1131 }
1132
1133 /** Handles **/
1134
1135 void Decorator::SetHandleActive( HandleType handleType, bool active )
1136 {
1137   mImpl->mHandle[handleType].active = active;
1138 }
1139
1140 bool Decorator::IsHandleActive( HandleType handleType ) const
1141 {
1142   return mImpl->mHandle[handleType].active ;
1143 }
1144
1145 void Decorator::SetHandleImage( HandleType handleType, HandleImageType handleImageType, Dali::Image image )
1146 {
1147   mImpl->mHandleImages[handleType][handleImageType] = image;
1148 }
1149
1150 Dali::Image Decorator::GetHandleImage( HandleType handleType, HandleImageType handleImageType ) const
1151 {
1152   return mImpl->mHandleImages[handleType][handleImageType];
1153 }
1154
1155 void Decorator::SetPosition( HandleType handleType, float x, float y, float height )
1156 {
1157   // Adjust grab handle displacement
1158   Impl::HandleImpl& handle = mImpl->mHandle[handleType];
1159
1160   handle.grabDisplacementX -= x - handle.position.x;
1161   handle.grabDisplacementY -= y - handle.position.y;
1162
1163   handle.position.x = x;
1164   handle.position.y = y;
1165   handle.lineHeight = height;
1166 }
1167
1168 void Decorator::GetPosition( HandleType handleType, float& x, float& y, float& height ) const
1169 {
1170   Impl::HandleImpl& handle = mImpl->mHandle[handleType];
1171
1172   x = handle.position.x;
1173   y = handle.position.y;
1174   height = handle.lineHeight;
1175 }
1176
1177 void Decorator::AddHighlight( float x1, float y1, float x2, float y2 )
1178 {
1179   mImpl->mHighlightQuadList.push_back( QuadCoordinates(x1, y1, x2, y2) );
1180 }
1181
1182 void Decorator::ClearHighlights()
1183 {
1184   mImpl->mHighlightQuadList.clear();
1185 }
1186
1187 void Decorator::SetHighlightColor( const Vector4& color )
1188 {
1189   mImpl->mHighlightColor = color;
1190 }
1191
1192 const Vector4& Decorator::GetHighlightColor() const
1193 {
1194   return mImpl->mHighlightColor;
1195 }
1196
1197 void Decorator::SetPopupActive( bool active )
1198 {
1199   mImpl->mActiveCopyPastePopup = active;
1200 }
1201
1202 bool Decorator::IsPopupActive() const
1203 {
1204   return mImpl->mActiveCopyPastePopup ;
1205 }
1206
1207 /** Scroll **/
1208
1209 void Decorator::SetScrollThreshold( float threshold )
1210 {
1211   mImpl->SetScrollThreshold( threshold );
1212 }
1213
1214 float Decorator::GetScrollThreshold() const
1215 {
1216   return mImpl->GetScrollThreshold();
1217 }
1218
1219 void Decorator::SetScrollSpeed( float speed )
1220 {
1221   mImpl->SetScrollSpeed( speed );
1222 }
1223
1224 float Decorator::GetScrollSpeed() const
1225 {
1226   return mImpl->GetScrollSpeed();
1227 }
1228
1229 Decorator::~Decorator()
1230 {
1231   delete mImpl;
1232 }
1233
1234 Decorator::Decorator( Dali::Toolkit::Internal::Control& parent, Observer& observer )
1235 : mImpl( NULL )
1236 {
1237   mImpl = new Decorator::Impl( parent, observer );
1238 }
1239
1240 } // namespace Text
1241
1242 } // namespace Toolkit
1243
1244 } // namespace Dali