692b9a39c689cb7b34a1dbdbbcd4565e109f133c
[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
58 namespace Dali
59 {
60 namespace Internal
61 {
62 namespace
63 {
64 #ifdef DECORATOR_DEBUG
65 Integration::Log::Filter* gLogFilter( Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_TEXT_DECORATOR") );
66 #endif
67 }
68 }
69 }
70
71
72 // Local Data
73 namespace
74 {
75
76 const char* DEFAULT_GRAB_HANDLE_IMAGE( DALI_IMAGE_DIR "insertpoint-icon.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 //const char* DEFAULT_SELECTION_HANDLE_ONE_PRESSED( DALI_IMAGE_DIR "text-input-selection-handle-left-press.png" );
80 //const char* DEFAULT_SELECTION_HANDLE_TWO_PRESSED( DALI_IMAGE_DIR "text-input-selection-handle-right-press.png" );
81
82 const Dali::Vector3 DEFAULT_GRAB_HANDLE_RELATIVE_SIZE( 1.5f, 2.0f, 1.0f );
83 const Dali::Vector3 DEFAULT_SELECTION_HANDLE_RELATIVE_SIZE( 1.5f, 1.5f, 1.0f );
84
85 const std::size_t CURSOR_BLINK_INTERVAL = 500; // Cursor blink interval
86 const std::size_t MILLISECONDS = 1000;
87
88 const float DISPLAYED_HIGHLIGHT_Z_OFFSET( -0.05f );
89
90 /**
91  * structure to hold coordinates of each quad, which will make up the mesh.
92  */
93 struct QuadCoordinates
94 {
95   /**
96    * Default constructor
97    */
98   QuadCoordinates()
99   {
100   }
101
102   /**
103    * Constructor
104    * @param[in] x1 left co-ordinate
105    * @param[in] y1 top co-ordinate
106    * @param[in] x2 right co-ordinate
107    * @param[in] y2 bottom co-ordinate
108    */
109   QuadCoordinates(float x1, float y1, float x2, float y2)
110   : min(x1, y1),
111     max(x2, y2)
112   {
113   }
114
115   Dali::Vector2 min;                          ///< top-left (minimum) position of quad
116   Dali::Vector2 max;                          ///< bottom-right (maximum) position of quad
117 };
118
119 typedef std::vector<QuadCoordinates> QuadContainer;
120
121 /**
122  * @brief Takes a bounding rectangle in the local coordinates of an actor and returns the world coordinates Bounding Box.
123  * @param[in] boundingRectangle local bounding
124  * @param[out] Vector4 World coordinate bounding Box.
125  */
126 void LocalToWorldCoordinatesBoundingBox( const Dali::Rect<int>& boundingRectangle, Dali::Vector4& boundingBox )
127 {
128   // Convert to world coordinates and store as a Vector4 to be compatible with Property Notifications.
129   Dali::Vector2 stageSize = Dali::Stage::GetCurrent().GetSize();
130
131   const float originX = boundingRectangle.x - 0.5f * stageSize.width;
132   const float originY = boundingRectangle.y - 0.5f * stageSize.height;
133
134   boundingBox = Dali::Vector4( originX,
135                                originY,
136                                originX + boundingRectangle.width,
137                                originY + boundingRectangle.height );
138 }
139
140
141 } // end of namespace
142
143 namespace Dali
144 {
145
146 namespace Toolkit
147 {
148
149 namespace Text
150 {
151
152 struct Decorator::Impl : public ConnectionTracker
153 {
154   struct CursorImpl
155   {
156     CursorImpl()
157     : x(0.0f),
158       y(0.0f),
159       cursorHeight(0.0f),
160       lineHeight(0.0f),
161       color(Dali::Color::WHITE)
162     {
163     }
164
165     float x;
166     float y;
167     float cursorHeight;
168     float lineHeight;
169
170     Vector4 color;
171   };
172
173   struct SelectionHandleImpl
174   {
175     SelectionHandleImpl()
176     : x(0.0f),
177       y(0.0f),
178       lineHeight(0.0f),
179       flipped(false)
180     {
181     }
182
183     float x;
184     float y;
185     float lineHeight; ///< Not the handle height
186     bool flipped;
187
188     ImageActor actor;
189     Actor grabArea;
190
191     Image pressedImage;
192     Image releasedImage;
193   };
194
195   Impl( Dali::Toolkit::Internal::Control& parent, Observer& observer )
196   : mTextControlParent(parent),
197     mObserver(observer),
198     mActiveCursor(ACTIVE_CURSOR_NONE),
199     mActiveGrabHandle(false),
200     mActiveSelection( false ),
201     mActiveCopyPastePopup( false ),
202     mCursorBlinkInterval( CURSOR_BLINK_INTERVAL ),
203     mCursorBlinkDuration( 0.0f ),
204     mCursorBlinkStatus( true ),
205     mGrabDisplacementX( 0.0f ),
206     mGrabDisplacementY( 0.0f ),
207     mHighlightColor( 0.07f, 0.41f, 0.59f, 1.0f ), // light blue
208     mBoundingBox( Rect<int>() )
209   {
210   }
211
212   /**
213    * Relayout of the decorations owned by the decorator.
214    * @param[in] size The Size of the UI control the decorater is adding it's decorations to.
215    */
216   void Relayout( const Vector2& size, const Vector2& scrollPosition )
217   {
218     // TODO - Remove this if nothing is active
219     CreateActiveLayer();
220
221     // Show or hide the cursors
222     CreateCursors();
223     if( mPrimaryCursor )
224     {
225       mPrimaryCursor.SetPosition( mCursor[PRIMARY_CURSOR].x + scrollPosition.x,
226                                   mCursor[PRIMARY_CURSOR].y + scrollPosition.y );
227       mPrimaryCursor.SetSize( Size( 1.0f, mCursor[PRIMARY_CURSOR].cursorHeight ) );
228     }
229     if( mSecondaryCursor )
230     {
231       mSecondaryCursor.SetPosition( mCursor[SECONDARY_CURSOR].x + scrollPosition.x,
232                                     mCursor[SECONDARY_CURSOR].y + scrollPosition.y );
233       mSecondaryCursor.SetSize( Size( 1.0f, mCursor[SECONDARY_CURSOR].cursorHeight ) );
234     }
235
236     // Show or hide the grab handle
237     if( mActiveGrabHandle )
238     {
239       SetupTouchEvents();
240
241       CreateGrabHandle();
242
243       mGrabHandle.SetPosition( mCursor[PRIMARY_CURSOR].x + scrollPosition.x,
244                                mCursor[PRIMARY_CURSOR].lineHeight + scrollPosition.y );
245     }
246     else if( mGrabHandle )
247     {
248       UnparentAndReset( mGrabHandle );
249     }
250
251     // Show or hide the selection handles/highlight
252     if( mActiveSelection )
253     {
254       SetupTouchEvents();
255
256       CreateSelectionHandles();
257
258       SelectionHandleImpl& primary = mSelectionHandle[ PRIMARY_SELECTION_HANDLE ];
259       primary.actor.SetPosition( primary.x + scrollPosition.x,
260                                  primary.lineHeight + scrollPosition.y );
261
262       SelectionHandleImpl& secondary = mSelectionHandle[ SECONDARY_SELECTION_HANDLE ];
263       secondary.actor.SetPosition( secondary.x + scrollPosition.x,
264                                    secondary.lineHeight + scrollPosition.y );
265
266       CreateHighlight();
267       UpdateHighlight();
268     }
269     else
270     {
271       UnparentAndReset( mSelectionHandle[ PRIMARY_SELECTION_HANDLE ].actor );
272       UnparentAndReset( mSelectionHandle[ SECONDARY_SELECTION_HANDLE ].actor );
273       UnparentAndReset( mHighlightMeshActor );
274     }
275
276     if ( mActiveCopyPastePopup )
277     {
278       if ( !mCopyPastePopup )
279       {
280         mCopyPastePopup = TextSelectionPopup::New();
281 #ifdef DECORATOR_DEBUG
282         mCopyPastePopup.SetName("mCopyPastePopup");
283 #endif
284         mCopyPastePopup.SetAnchorPoint( AnchorPoint::CENTER );
285         mCopyPastePopup.OnRelayoutSignal().Connect( this,  &Decorator::Impl::PopUpRelayoutComplete  ); // Position popup after size negotiation
286         mActiveLayer.Add ( mCopyPastePopup );
287       }
288     }
289     else
290     {
291      if ( mCopyPastePopup )
292      {
293        UnparentAndReset( mCopyPastePopup );
294      }
295     }
296   }
297
298   void PopUpRelayoutComplete( Actor actor )
299   {
300     // Size negotiation for CopyPastePopup complete so can get the size and constrain position within bounding box.
301
302     mCopyPastePopup.OnRelayoutSignal().Disconnect( this, &Decorator::Impl::PopUpRelayoutComplete  );
303
304     Vector3 popupPosition( mCursor[PRIMARY_CURSOR].x, mCursor[PRIMARY_CURSOR].y -100.0f , 0.0f); //todo 100 to be an offset Property
305
306     Vector3 popupSize = Vector3( mCopyPastePopup.GetRelayoutSize( Dimension::WIDTH ), mCopyPastePopup.GetRelayoutSize( Dimension::HEIGHT ), 0.0f );
307
308     GetConstrainedPopupPosition( popupPosition, popupSize, AnchorPoint::CENTER, mActiveLayer, mBoundingBox );
309
310     SetUpPopUpPositionNotifications();
311
312     mCopyPastePopup.SetPosition( popupPosition ); //todo grabhandle(cursor) or selection handle positions to be used
313   }
314
315   void CreateCursor( ImageActor& cursor )
316   {
317     cursor = CreateSolidColorActor( Color::WHITE );
318     cursor.SetParentOrigin( ParentOrigin::TOP_LEFT ); // Need to set the default parent origin as CreateSolidColorActor() sets a different one.
319     cursor.SetAnchorPoint( AnchorPoint::TOP_CENTER );
320   }
321
322   // Add or Remove cursor(s) from parent
323   void CreateCursors()
324   {
325     if( mActiveCursor == ACTIVE_CURSOR_NONE )
326     {
327       UnparentAndReset( mPrimaryCursor );
328       UnparentAndReset( mSecondaryCursor );
329     }
330     else
331     {
332       /* Create Primary and or Secondary Cursor(s) if active and add to parent */
333       if ( mActiveCursor == ACTIVE_CURSOR_PRIMARY ||
334            mActiveCursor == ACTIVE_CURSOR_BOTH )
335       {
336         if ( !mPrimaryCursor )
337         {
338           CreateCursor( mPrimaryCursor );
339 #ifdef DECORATOR_DEBUG
340           mPrimaryCursor.SetName( "PrimaryCursorActor" );
341 #endif
342           mActiveLayer.Add( mPrimaryCursor);
343         }
344       }
345
346       if ( mActiveCursor == ACTIVE_CURSOR_BOTH )
347       {
348         if ( !mSecondaryCursor )
349         {
350           CreateCursor( mSecondaryCursor );
351 #ifdef DECORATOR_DEBUG
352           mSecondaryCursor.SetName( "SecondaryCursorActor" );
353 #endif
354           mActiveLayer.Add( mSecondaryCursor);
355         }
356       }
357       else
358       {
359         UnparentAndReset( mSecondaryCursor );
360       }
361     }
362   }
363
364   bool OnCursorBlinkTimerTick()
365   {
366     // Cursor blinking
367     if ( mPrimaryCursor )
368     {
369       mPrimaryCursor.SetVisible( mCursorBlinkStatus );
370     }
371     if ( mSecondaryCursor )
372     {
373       mSecondaryCursor.SetVisible( mCursorBlinkStatus );
374     }
375
376     mCursorBlinkStatus = !mCursorBlinkStatus;
377
378     return true;
379   }
380
381   void SetupTouchEvents()
382   {
383     if ( !mTapDetector )
384     {
385       mTapDetector = TapGestureDetector::New();
386       mTapDetector.DetectedSignal().Connect( this, &Decorator::Impl::OnTap );
387     }
388
389     if ( !mPanGestureDetector )
390     {
391       mPanGestureDetector = PanGestureDetector::New();
392       mPanGestureDetector.DetectedSignal().Connect( this, &Decorator::Impl::OnPan );
393     }
394   }
395
396   void CreateActiveLayer()
397   {
398     if( !mActiveLayer )
399     {
400       Actor parent = mTextControlParent.Self();
401
402       mActiveLayer = Layer::New();
403 #ifdef DECORATOR_DEBUG
404       mActiveLayer.SetName ( "ActiveLayerActor" );
405 #endif
406
407       mActiveLayer.SetParentOrigin( ParentOrigin::CENTER );
408       mActiveLayer.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS );
409       mActiveLayer.SetPositionInheritanceMode( USE_PARENT_POSITION );
410
411       parent.Add( mActiveLayer );
412     }
413
414     mActiveLayer.RaiseToTop();
415   }
416
417   void CreateGrabHandle()
418   {
419     if( !mGrabHandle )
420     {
421       if ( !mGrabHandleImage )
422       {
423         mGrabHandleImage = ResourceImage::New( DEFAULT_GRAB_HANDLE_IMAGE );
424       }
425
426       mGrabHandle = ImageActor::New( mGrabHandleImage );
427       mGrabHandle.SetAnchorPoint( AnchorPoint::TOP_CENTER );
428       mGrabHandle.SetDrawMode( DrawMode::OVERLAY );
429       // Area that Grab handle responds to, larger than actual handle so easier to move
430 #ifdef DECORATOR_DEBUG
431       mGrabHandle.SetName( "GrabHandleActor" );
432       if ( Dali::Internal::gLogFilter->IsEnabledFor( Debug::Verbose ) )
433       {
434         mGrabArea = Toolkit::CreateSolidColorActor( Vector4(0.0f, 0.0f, 0.0f, 0.0f), true, Color::RED, 1 );
435         mGrabArea.SetName( "GrabArea" );
436       }
437       else
438       {
439         mGrabArea = Actor::New();
440         mGrabArea.SetName( "GrabArea" );
441       }
442 #else
443       mGrabArea = Actor::New();
444 #endif
445
446       mGrabArea.SetParentOrigin( ParentOrigin::TOP_CENTER );
447       mGrabArea.SetAnchorPoint( AnchorPoint::TOP_CENTER );
448       mGrabArea.SetResizePolicy( ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::ALL_DIMENSIONS );
449       mGrabArea.SetSizeModeFactor( DEFAULT_GRAB_HANDLE_RELATIVE_SIZE );
450       mGrabHandle.Add( mGrabArea );
451
452       mTapDetector.Attach( mGrabArea );
453       mPanGestureDetector.Attach( mGrabArea );
454
455       mActiveLayer.Add( mGrabHandle );
456     }
457   }
458
459   void CreateSelectionHandles()
460   {
461     SelectionHandleImpl& primary = mSelectionHandle[ PRIMARY_SELECTION_HANDLE ];
462     if ( !primary.actor )
463     {
464       if ( !primary.releasedImage )
465       {
466         primary.releasedImage = ResourceImage::New( DEFAULT_SELECTION_HANDLE_ONE );
467       }
468
469       primary.actor = ImageActor::New( primary.releasedImage );
470 #ifdef DECORATOR_DEBUG
471       primary.actor.SetName("SelectionHandleOne");
472 #endif
473       primary.actor.SetAnchorPoint( AnchorPoint::TOP_RIGHT ); // Change to BOTTOM_RIGHT if Look'n'Feel requires handle above text.
474       primary.actor.SetDrawMode( DrawMode::OVERLAY ); // ensure grab handle above text
475       primary.flipped = false;
476
477       primary.grabArea = Actor::New(); // Area that Grab handle responds to, larger than actual handle so easier to move
478 #ifdef DECORATOR_DEBUG
479       primary.grabArea.SetName("SelectionHandleOneGrabArea");
480 #endif
481       primary.grabArea.SetResizePolicy( ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::ALL_DIMENSIONS );
482       primary.grabArea.SetSizeModeFactor( DEFAULT_SELECTION_HANDLE_RELATIVE_SIZE );
483       primary.grabArea.SetPositionInheritanceMode( Dali::USE_PARENT_POSITION );
484
485       mTapDetector.Attach( primary.grabArea );
486       mPanGestureDetector.Attach( primary.grabArea );
487       primary.grabArea.TouchedSignal().Connect( this, &Decorator::Impl::OnHandleOneTouched );
488
489       primary.actor.Add( primary.grabArea );
490       mActiveLayer.Add( primary.actor );
491     }
492
493     SelectionHandleImpl& secondary = mSelectionHandle[ SECONDARY_SELECTION_HANDLE ];
494     if ( !secondary.actor )
495     {
496       if ( !secondary.releasedImage )
497       {
498         secondary.releasedImage = ResourceImage::New( DEFAULT_SELECTION_HANDLE_TWO );
499       }
500
501       secondary.actor = ImageActor::New( secondary.releasedImage );
502 #ifdef DECORATOR_DEBUG
503       secondary.actor.SetName("SelectionHandleTwo");
504 #endif
505       secondary.actor.SetAnchorPoint( AnchorPoint::TOP_LEFT ); // Change to BOTTOM_LEFT if Look'n'Feel requires handle above text.
506       secondary.actor.SetDrawMode( DrawMode::OVERLAY ); // ensure grab handle above text
507       secondary.flipped = false;
508
509       secondary.grabArea = Actor::New(); // Area that Grab handle responds to, larger than actual handle so easier to move
510 #ifdef DECORATOR_DEBUG
511       secondary.grabArea.SetName("SelectionHandleTwoGrabArea");
512 #endif
513       secondary.grabArea.SetResizePolicy( ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::ALL_DIMENSIONS );
514       secondary.grabArea.SetSizeModeFactor( DEFAULT_SELECTION_HANDLE_RELATIVE_SIZE );
515       secondary.grabArea.SetPositionInheritanceMode( Dali::USE_PARENT_POSITION );
516
517       mTapDetector.Attach( secondary.grabArea );
518       mPanGestureDetector.Attach( secondary.grabArea );
519       secondary.grabArea.TouchedSignal().Connect( this, &Decorator::Impl::OnHandleTwoTouched );
520
521       secondary.actor.Add( secondary.grabArea );
522       mActiveLayer.Add( secondary.actor );
523     }
524
525     //SetUpHandlePropertyNotifications(); TODO
526   }
527
528   void CreateHighlight()
529   {
530     if ( !mHighlightMeshActor )
531     {
532       mHighlightMaterial = Material::New( "HighlightMaterial" );
533       mHighlightMaterial.SetDiffuseColor( mHighlightColor );
534
535       mHighlightMeshData.SetMaterial( mHighlightMaterial );
536       mHighlightMeshData.SetHasNormals( true );
537
538       mHighlightMesh = Mesh::New( mHighlightMeshData );
539
540       mHighlightMeshActor = MeshActor::New( mHighlightMesh );
541 #ifdef DECORATOR_DEBUG
542       mHighlightMeshActor.SetName( "HighlightMeshActor" );
543 #endif
544       mHighlightMeshActor.SetAnchorPoint( AnchorPoint::TOP_LEFT );
545       mHighlightMeshActor.SetPosition( 0.0f, 0.0f, DISPLAYED_HIGHLIGHT_Z_OFFSET );
546
547       Actor parent = mTextControlParent.Self();
548       parent.Add( mHighlightMeshActor );
549     }
550   }
551
552   void UpdateHighlight()
553   {
554     //  Construct a Mesh with a texture to be used as the highlight 'box' for selected text
555     //
556     //  Example scenarios where mesh is made from 3, 1, 2, 2 ,3 or 3 quads.
557     //
558     //   [ TOP   ]  [ TOP ]      [TOP ]  [ TOP    ]      [ TOP  ]      [ TOP  ]
559     //  [ MIDDLE ]             [BOTTOM]  [BOTTOM]      [ MIDDLE ]   [ MIDDLE  ]
560     //  [ BOTTOM]                                      [ MIDDLE ]   [ MIDDLE  ]
561     //                                                 [BOTTOM]     [ MIDDLE  ]
562     //                                                              [BOTTOM]
563     //
564     //  Each quad is created as 2 triangles.
565     //  Middle is just 1 quad regardless of its size.
566     //
567     //  (0,0)         (0,0)
568     //     0*    *2     0*       *2
569     //     TOP          TOP
570     //     3*    *1     3*       *1
571     //  4*       *1     4*     *6
572     //     MIDDLE         BOTTOM
573     //  6*       *5     7*     *5
574     //  6*    *8
575     //   BOTTOM
576     //  9*    *7
577     //
578
579     if ( mHighlightMesh && mHighlightMaterial && !mHighlightQuadList.empty() )
580     {
581       MeshData::VertexContainer vertices;
582       Dali::MeshData::FaceIndices faceIndices;
583
584       std::vector<QuadCoordinates>::iterator iter = mHighlightQuadList.begin();
585       std::vector<QuadCoordinates>::iterator endIter = mHighlightQuadList.end();
586
587       // vertex position defaults to (0 0 0)
588       MeshData::Vertex vertex;
589       // set normal for all vertices as (0 0 1) pointing outward from TextInput Actor.
590       vertex.nZ = 1.0f;
591
592       for(std::size_t v = 0; iter != endIter; ++iter,v+=4 )
593       {
594         // Add each quad geometry (a sub-selection) to the mesh data.
595
596         // 0-----1
597         // |\    |
598         // | \ A |
599         // |  \  |
600         // | B \ |
601         // |    \|
602         // 2-----3
603
604         QuadCoordinates& quad = *iter;
605         // top-left (v+0)
606         vertex.x = quad.min.x;
607         vertex.y = quad.min.y;
608         vertices.push_back( vertex );
609
610         // top-right (v+1)
611         vertex.x = quad.max.x;
612         vertex.y = quad.min.y;
613         vertices.push_back( vertex );
614
615         // bottom-left (v+2)
616         vertex.x = quad.min.x;
617         vertex.y = quad.max.y;
618         vertices.push_back( vertex );
619
620         // bottom-right (v+3)
621         vertex.x = quad.max.x;
622         vertex.y = quad.max.y;
623         vertices.push_back( vertex );
624
625         // triangle A (3, 1, 0)
626         faceIndices.push_back( v + 3 );
627         faceIndices.push_back( v + 1 );
628         faceIndices.push_back( v );
629
630         // triangle B (0, 2, 3)
631         faceIndices.push_back( v );
632         faceIndices.push_back( v + 2 );
633         faceIndices.push_back( v + 3 );
634
635         mHighlightMeshData.SetFaceIndices( faceIndices );
636       }
637
638       BoneContainer bones(0); // passed empty as bones not required
639       mHighlightMeshData.SetData( vertices, faceIndices, bones, mHighlightMaterial );
640       mHighlightMesh.UpdateMeshData( mHighlightMeshData );
641     }
642   }
643
644   void OnTap( Actor actor, const TapGesture& tap )
645   {
646     if( actor == mGrabHandle )
647     {
648       // TODO
649     }
650   }
651
652   void OnPan( Actor actor, const PanGesture& gesture )
653   {
654     if( actor == mGrabArea )
655     {
656       if( Gesture::Started == gesture.state )
657       {
658         mGrabDisplacementX = mGrabDisplacementY = 0;
659       }
660
661       mGrabDisplacementX += gesture.displacement.x;
662       mGrabDisplacementY += gesture.displacement.y;
663
664       float x = mCursor[PRIMARY_CURSOR].x + mGrabDisplacementX;
665       float y = mCursor[PRIMARY_CURSOR].y + mCursor[PRIMARY_CURSOR].lineHeight*0.5f + mGrabDisplacementY;
666
667       if( Gesture::Started    == gesture.state ||
668           Gesture::Continuing == gesture.state )
669       {
670         mObserver.GrabHandleEvent( GRAB_HANDLE_PRESSED, x, y );
671       }
672       else if( Gesture::Finished  == gesture.state ||
673                Gesture::Cancelled == gesture.state )
674       {
675         mObserver.GrabHandleEvent( GRAB_HANDLE_RELEASED, x, y );
676       }
677     }
678   }
679
680   bool OnHandleOneTouched( Actor actor, const TouchEvent& touch )
681   {
682     // TODO
683     return false;
684   }
685
686   bool OnHandleTwoTouched( Actor actor, const TouchEvent& touch )
687   {
688     // TODO
689     return false;
690   }
691
692   // Popup
693
694   float AlternatePopUpPositionRelativeToCursor()
695   {
696     float alternativePosition=0.0f;;
697
698     if ( mPrimaryCursor ) // Secondary cursor not used for paste
699     {
700       Cursor cursor = PRIMARY_CURSOR;
701       alternativePosition = mCursor[cursor].y;
702     }
703
704     const float popupHeight = 120.0f; // todo Set as a MaxSize Property in Control or retrieve from CopyPastePopup class.
705
706     if (  mActiveGrabHandle )
707     {
708       // If grab handle enabled then position pop-up below the grab handle.
709       const Vector2 grabHandleSize( 59.0f, 56.0f ); // todo
710       const float BOTTOM_HANDLE_BOTTOM_OFFSET = 1.5; //todo Should be a property
711       alternativePosition +=  grabHandleSize.height  + popupHeight + BOTTOM_HANDLE_BOTTOM_OFFSET ;
712     }
713     else
714     {
715       alternativePosition += popupHeight;
716     }
717
718     return alternativePosition;
719   }
720
721   void PopUpLeavesVerticalBoundary( PropertyNotification& source )
722   {
723     float alternativeYPosition=0.0f;
724   // todo
725   //  if( mHighlightMeshActor ) // Text Selection mode
726   //  {
727   //    alternativePosition = AlternatePopUpPositionRelativeToSelectionHandles();
728   //  }
729   //  else // Not in Text Selection mode
730   //  {
731     // if can't be positioned above, then position below row.
732     alternativeYPosition = AlternatePopUpPositionRelativeToCursor();
733    // }
734     mCopyPastePopup.SetY( alternativeYPosition );
735   }
736
737
738   void SetUpPopUpPositionNotifications( )
739   {
740     // Note Property notifications ignore any set anchor point so conditions must allow for this.  Default is Top Left.
741
742     // Exceeding vertical boundary
743
744     Vector4 worldCoordinatesBoundingBox;
745     LocalToWorldCoordinatesBoundingBox( mBoundingBox, worldCoordinatesBoundingBox );
746
747     float popupHeight = mCopyPastePopup.GetRelayoutSize( Dimension::HEIGHT);
748
749     PropertyNotification verticalExceedNotification = mCopyPastePopup.AddPropertyNotification( Actor::Property::WORLD_POSITION_Y,
750                                                       OutsideCondition( worldCoordinatesBoundingBox.y + popupHeight/2,
751                                                                         worldCoordinatesBoundingBox.w - popupHeight/2 ) );
752
753     verticalExceedNotification.NotifySignal().Connect( this, &Decorator::Impl::PopUpLeavesVerticalBoundary );
754   }
755
756   void GetConstrainedPopupPosition( Vector3& requiredPopupPosition, Vector3& popupSize, Vector3 anchorPoint, Actor& parent, Rect<int>& boundingBox )
757   {
758     DALI_ASSERT_DEBUG ( "Popup parent not on stage" && parent.OnStage() )
759
760     // Parent must already by added to Stage for these Get calls to work
761     Vector3 parentAnchorPoint = parent.GetCurrentAnchorPoint();
762     Vector3 parentWorldPositionLeftAnchor = parent.GetCurrentWorldPosition() - parent.GetCurrentSize()*parentAnchorPoint;
763     Vector3 popupWorldPosition = parentWorldPositionLeftAnchor + requiredPopupPosition;  // Parent World position plus popup local position gives World Position
764     Vector3 popupDistanceFromAnchorPoint = popupSize*anchorPoint;
765
766     // Bounding rectangle is supplied as screen coordinates, bounding will be done in world coordinates.
767     Vector4 boundingRectangleWorld;
768     LocalToWorldCoordinatesBoundingBox( boundingBox, boundingRectangleWorld );
769
770     // Calculate distance to move popup (in local space) so fits within the boundary
771     float xOffSetToKeepWithinBounds = 0.0f;
772     if( popupWorldPosition.x - popupDistanceFromAnchorPoint.x < boundingRectangleWorld.x )
773     {
774       xOffSetToKeepWithinBounds = boundingRectangleWorld.x - ( popupWorldPosition.x - popupDistanceFromAnchorPoint.x );
775     }
776     else if ( popupWorldPosition.x +  popupDistanceFromAnchorPoint.x > boundingRectangleWorld.z )
777     {
778       xOffSetToKeepWithinBounds = boundingRectangleWorld.z - ( popupWorldPosition.x +  popupDistanceFromAnchorPoint.x );
779     }
780
781     // Ensure initial display of Popup is in alternative position if can not fit above. As Property notification will be a frame behind.
782     if ( popupWorldPosition.y - popupDistanceFromAnchorPoint.y < boundingRectangleWorld.y )
783     {
784       requiredPopupPosition.y = AlternatePopUpPositionRelativeToCursor();
785     }
786
787     requiredPopupPosition.x = requiredPopupPosition.x + xOffSetToKeepWithinBounds;
788   }
789
790   Internal::Control& mTextControlParent;
791   Observer& mObserver;
792
793   Layer mActiveLayer; // Layer for active handles and alike that ensures they are above all else.
794
795   unsigned int mActiveCursor;
796   bool         mActiveGrabHandle;
797   bool         mActiveSelection;
798   bool         mActiveCopyPastePopup;
799
800   CursorImpl mCursor[CURSOR_COUNT];
801
802   Timer mCursorBlinkTimer; // Timer to signal cursor to blink
803   unsigned int mCursorBlinkInterval;
804   float mCursorBlinkDuration;
805   bool mCursorBlinkStatus; // Flag to switch between blink on and blink off
806
807   ImageActor mPrimaryCursor;
808   ImageActor mSecondaryCursor;
809
810   ImageActor mGrabHandle;
811   Actor mGrabArea;
812   float mGrabDisplacementX;
813   float mGrabDisplacementY;
814
815   SelectionHandleImpl mSelectionHandle[SELECTION_HANDLE_COUNT];
816
817   MeshActor         mHighlightMeshActor;        ///< Mesh Actor to display highlight
818   Mesh              mHighlightMesh;             ///< Mesh for highlight
819   MeshData          mHighlightMeshData;         ///< Mesh Data for highlight
820   Material          mHighlightMaterial;         ///< Material used for highlight
821   Vector4           mHighlightColor;            ///< Color of the highlight
822   QuadContainer     mHighlightQuadList;         ///< Sub-selections that combine to create the complete selection highlight
823
824   TextSelectionPopup mCopyPastePopup;
825
826   Image mCursorImage;
827   Image mGrabHandleImage;
828
829   TapGestureDetector mTapDetector;
830   PanGestureDetector mPanGestureDetector;
831
832   Rect<int> mBoundingBox;
833 };
834
835 DecoratorPtr Decorator::New( Internal::Control& parent, Observer& observer )
836 {
837   return DecoratorPtr( new Decorator(parent, observer) );
838 }
839
840 void Decorator::SetBoundingBox( const Rect<int>& boundingBox )
841 {
842   mImpl->mBoundingBox = boundingBox;
843 }
844
845 const Rect<int>& Decorator::GetBoundingBox() const
846 {
847   return mImpl->mBoundingBox;
848 }
849
850 void Decorator::Relayout( const Vector2& size, const Vector2& scrollPosition )
851 {
852   mImpl->Relayout( size, scrollPosition );
853 }
854
855 /** Cursor **/
856
857 void Decorator::SetActiveCursor( ActiveCursor activeCursor )
858 {
859   mImpl->mActiveCursor = activeCursor;
860 }
861
862 unsigned int Decorator::GetActiveCursor() const
863 {
864   return mImpl->mActiveCursor;
865 }
866
867 void Decorator::SetPosition( Cursor cursor, float x, float y, float cursorHeight, float lineHeight )
868 {
869   // Adjust grab handle displacement
870   mImpl->mGrabDisplacementX -= x - mImpl->mCursor[cursor].x;
871   mImpl->mGrabDisplacementY -= y - mImpl->mCursor[cursor].y;
872
873   mImpl->mCursor[cursor].x = x;
874   mImpl->mCursor[cursor].y = y;
875   mImpl->mCursor[cursor].cursorHeight = cursorHeight;
876   mImpl->mCursor[cursor].lineHeight = lineHeight;
877 }
878
879 void Decorator::GetPosition( Cursor cursor, float& x, float& y, float& cursorHeight, float& lineHeight ) const
880 {
881   x = mImpl->mCursor[cursor].x;
882   y = mImpl->mCursor[cursor].y;
883   cursorHeight = mImpl->mCursor[cursor].cursorHeight;
884   lineHeight = mImpl->mCursor[cursor].lineHeight;
885 }
886
887 void Decorator::SetColor( Cursor cursor, const Dali::Vector4& color )
888 {
889   mImpl->mCursor[cursor].color = color;
890 }
891
892 const Dali::Vector4& Decorator::GetColor( Cursor cursor ) const
893 {
894   return mImpl->mCursor[cursor].color;
895 }
896
897 void Decorator::StartCursorBlink()
898 {
899   if ( !mImpl->mCursorBlinkTimer )
900   {
901     mImpl->mCursorBlinkTimer = Timer::New( mImpl->mCursorBlinkInterval );
902     mImpl->mCursorBlinkTimer.TickSignal().Connect( mImpl, &Decorator::Impl::OnCursorBlinkTimerTick );
903   }
904
905   if ( !mImpl->mCursorBlinkTimer.IsRunning() )
906   {
907     mImpl->mCursorBlinkTimer.Start();
908   }
909 }
910
911 void Decorator::StopCursorBlink()
912 {
913   if ( mImpl->mCursorBlinkTimer )
914   {
915     mImpl->mCursorBlinkTimer.Stop();
916   }
917 }
918
919 void Decorator::SetCursorBlinkInterval( float seconds )
920 {
921   mImpl->mCursorBlinkInterval = seconds*MILLISECONDS; // Convert to milliseconds
922 }
923
924 float Decorator::GetCursorBlinkInterval() const
925 {
926   return mImpl->mCursorBlinkInterval;
927 }
928
929 void Decorator::SetCursorBlinkDuration( float seconds )
930 {
931   mImpl->mCursorBlinkDuration = seconds;
932 }
933
934 float Decorator::GetCursorBlinkDuration() const
935 {
936   return mImpl->mCursorBlinkDuration;
937 }
938
939 /** GrabHandle **/
940
941 void Decorator::SetGrabHandleActive( bool active )
942 {
943   mImpl->mActiveGrabHandle = active;
944 }
945
946 bool Decorator::IsGrabHandleActive() const
947 {
948   return mImpl->mActiveGrabHandle;
949 }
950
951 void Decorator::SetGrabHandleImage( Dali::Image image )
952 {
953   mImpl->mGrabHandleImage = image;
954 }
955
956 Dali::Image Decorator::GetGrabHandleImage() const
957 {
958   return mImpl->mGrabHandleImage;
959 }
960
961 /** Selection **/
962
963 void Decorator::SetSelectionActive( bool active )
964 {
965   mImpl->mActiveSelection = active;
966 }
967
968 bool Decorator::IsSelectionActive() const
969 {
970   return mImpl->mActiveSelection;
971 }
972
973 void Decorator::SetPosition( SelectionHandle handle, float x, float y, float height )
974 {
975   mImpl->mSelectionHandle[handle].x = x;
976   mImpl->mSelectionHandle[handle].y = y;
977   mImpl->mSelectionHandle[handle].lineHeight = height;
978 }
979
980 void Decorator::GetPosition( SelectionHandle handle, float& x, float& y, float& height ) const
981 {
982   x = mImpl->mSelectionHandle[handle].x;
983   y = mImpl->mSelectionHandle[handle].y;
984   height = mImpl->mSelectionHandle[handle].lineHeight;
985 }
986
987 void Decorator::SetImage( SelectionHandle handle, SelectionHandleState state, Dali::Image image )
988 {
989   if( SELECTION_HANDLE_PRESSED == state )
990   {
991     mImpl->mSelectionHandle[handle].pressedImage = image;
992   }
993   else
994   {
995     mImpl->mSelectionHandle[handle].releasedImage = image;
996   }
997 }
998
999 Dali::Image Decorator::GetImage( SelectionHandle handle, SelectionHandleState state ) const
1000 {
1001   if( SELECTION_HANDLE_PRESSED == state )
1002   {
1003     return mImpl->mSelectionHandle[handle].pressedImage;
1004   }
1005
1006   return mImpl->mSelectionHandle[handle].releasedImage;
1007 }
1008
1009 void Decorator::AddHighlight( float x1, float y1, float x2, float y2 )
1010 {
1011   mImpl->mHighlightQuadList.push_back( QuadCoordinates(x1, y1, x2, y2) );
1012 }
1013
1014 void Decorator::ClearHighlights()
1015 {
1016   mImpl->mHighlightQuadList.clear();
1017 }
1018
1019 void Decorator::SetPopupActive( bool active )
1020 {
1021   mImpl->mActiveCopyPastePopup = active;
1022 }
1023
1024 bool Decorator::IsPopupActive() const
1025 {
1026   return mImpl->mActiveCopyPastePopup ;
1027 }
1028
1029 Decorator::~Decorator()
1030 {
1031   delete mImpl;
1032 }
1033
1034 Decorator::Decorator( Dali::Toolkit::Internal::Control& parent, Observer& observer )
1035 : mImpl( NULL )
1036 {
1037   mImpl = new Decorator::Impl( parent, observer );
1038 }
1039
1040 } // namespace Text
1041
1042 } // namespace Toolkit
1043
1044 } // namespace Dali